johan
April 1, 2020, 11:38am
1
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
'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.
johan
April 1, 2020, 12:46pm
3
Something like (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();
johan
April 1, 2020, 1:08pm
6
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() : [];
johan
April 1, 2020, 1:38pm
8
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
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()
?
johan
April 1, 2020, 1:50pm
10
Thanks, yes that fixed the form not found issue.