The field “My first field” is empty. “My second field” is not even set, that is why the above line is empty.
As far as I know $field->key does not know the difference.
Question
How do I know if the field is empty OR not set? For me, if the field is set, it is known and empty. If the field does not even exist, it is unknown and has no value, not even empty. How can I know the difference without ugly workarounds? Possible?
Silly workaround
I have a workaround that I don’t like.
Template
global $fields;
$fields = $page->content()->toArray();
$page->my_second_field()->my_method();
Field method
field::$methods['my_method'] = function( $field ) {
global $fields; // This does the "magic"
if( array_key_exists( $field->key, $fields ) ) {
echo 'Field key exist, but can be empty';
} else {
echo 'Field key does not exist';
}
};
There is currently no difference between an empty field and a not set field, as far as I can tell:
kirby/core/content.php:
/**
* Gets a field from the content
*
* @return Field
*/
public function get($key, $arguments = null) {
// case-insensitive data fetching
$key = strtolower($key);
if(isset($this->data[$key])) {
return $this->data[$key];
} else {
// return an empty field as default
return $this->data[$key] = new Field($this->page, $key);
}
}
…inside the method controller, but Kirby adds the key I’m using to the $page->content() before I can test against it. Therefor in my workaround above I have to set it directly in the template and then get it again with global.
This may come up for someone else, but I was able to create conditional formatting if a field is “Not Empty”. All other posts are formatted separately.
Basically if a “link” exists, have the Author’s Name link to a URL. If there is no link present, the Author’s Name should not expect a URL. I am using this for Quotes, where a link to the source material may or may not be available.