Skip foreach loop, get value from first item

Below code works but how do you skip the foreach loop altogether? In my scenario there will always be one row. Would be awesome if someone could help :slight_smile:

'rows' => function ($value) {
    $rows  = Yaml::decode($value);
    $value = [];

    foreach ($rows as $index => $row) {
      if($index == 0) {
        if (is_array($row) === false) {
            continue;
        }

        $value[] = $this->form($row)->values();
      }
    }

    return $value;
}

I’m working on a custom field that is exactly as the structure field but you can only add one item. I was thinking to skip all foreach loops as they are not necessary because there will always only be one row. Help much appreciated!

$rows[0]

should give you the first item.

Something like :thinking: (not working yet):

'rows' => function ($value) {
    $rows  = Yaml::decode($value);
    $value = $rows[0]->values();

    return $value;
}

You can’t call values on an array item

What about like that?

return $this->form($rows[0])->values();

Still getting “Undefined offset: 0”

Full plugin:

<?php

Kirby::plugin('your/plugin', [
    'fields' => [
        'hello' => [
            'extends' => 'structure',
            'methods' => [
              'rows' => function ($value) {
                  $rows  = Yaml::decode($value);

                  return $this->form($rows[0])->values();
              },
          ]
        ]
    ]
]);

It may give an error because I do not know the data. We can add additional control:

return empty($rows) === false ? $this->form(current($rows))->values() : [];

No error but existing fields are empty… no data.

A question within the question, I’m asking this because it might be part of the issue :thinking:

If I copy the full method (see below) from the original structure field, I get this error: Class 'Form' not found

In my original plugin above, I didn’t include the ‘form’ do I need to include this?

<?php

Kirby::plugin('your/plugin', [
    'fields' => [
        'hello' => [
            'extends' => 'structure',
            'methods' => [
                'rows' => function ($value) {
                    $rows  = Yaml::decode($value);
                    $value = [];

                    foreach ($rows as $index => $row) {
                        if (is_array($row) === false) {
                            continue;
                        }

                        $value[] = $this->form($row)->values();
                    }

                    return $value;
                },
                'form' => function (array $values = []) {
                    return new Form([
                        'fields' => $this->attrs['fields'],
                        'values' => $values,
                        'model'  => $this->model
                    ]);
                },
            ]
        ]
    ]
]);

Try with new Kirby\Form\Form()?

Thanks, yes that fixed the form not found issue.