Checking if field key extsts in field method?

A field method can look like this:

field::$methods['my_method'] = function( $field ) {
     echo $field->key;

It contains the $field->key.

In my content I have this…

My first field:

…and this…


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.


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.


global $fields;
$fields = $page->content()->toArray();


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';
1 Like

Have you tried the new field methods:


And there is also

$page->field()->bool(); //is the same as isTrue()

They all fail because the rely on $field->key which is empty even when not set. I would need a method…


There is currently no difference between an empty field and a not set field, as far as I can tell:


   * 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);

Field defaults to $value = ''.

But this should work then;

<?php if(isset($page->content()->data['title'])) { echo " key does exists"; } else { echo "key does not exist";}?>

because the constructor ignores empty keys;

I tried to use…


…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.

Topic solved in Kirby 2.2 I think:


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.

<?php if($post->link()->isNotEmpty()): ?>
    <a href="<?php echo $post->link() ?>"><?php echo $post->author() ?></a>
<?php else : ?>
    <?php echo $post->author() ?>
<?php endif ?>

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.