Using Form class makes base field unaware of the $page object

To answer this question I think you need to be a really good friend with the Kirby Panel core.

In a custom field there is an input() function where I call a template.php file. In that file I do this:

$form = (string)new Form($fields, $values);
echo $form;

For many cases it works fine, but for fields that uses the $page object, it does not work.

I found out that it comes down to that the base field is not aware of the $page object. I can’t figure out why and I can’t squeeze it in there.

My ugly workaround

input function of my custom field

I set the page id as a global variable.

kirby()->set('option', 'page.id', $this->page->id());

base-field

I register a base-field (replacing the old one) that is a a copy of the original. Then I add a constructor where I set the page object to the global variable.

public function __construct() {
  $this->page = page(kirby()->get('option', 'page.id'));
}

While it works, I think it’s an ugly solution. If a new Kirby version comes out, maybe the base-field has been updated and that would cause problem.

I’ve been trying to solve this issue for 1 day now without success. Any ideas would be helpful.

I’ve narrowed the problem down quite a bit.

In this example it works because the text field does not need the $this->page object in order to work.

<?php
class MyField extends BaseField {
	public function input() {
		$class = 'text' . 'field';
		$field = new $class;
		echo $field;
	}
}

In this example it does not work, because the image field needs $this->page object to be set.

<?php
class MyField extends BaseField {
	public function input() {
		$class = 'image' . 'field';
		$field = new $class;
		echo $field;
	}
}

I’ve taken the code above from here: https://github.com/getkirby/panel/blob/master/app/src/panel/form.php#L245

The image field does not set $this->page anywhere. The image field is based on selectField which is based on baseField. $this->page is not set on these classes either.

  1. How can the image field be aware of $this->page when used by the code or the structure field?
  2. How can I make image and other fields be aware of the $this->page?

I’ve spent 2 days on this problem but I don’t get anywhere.

Update

I finally solved it. I just needed to set the page on the instance of the class. That worked.

$class = 'image' . 'field';
$field = new $class;
$field->page = $this->page;
echo $field;