Home › Forums › Add-ons › Repeater Field › Automatically creating sub_fields of repeater/flexible content depending on name
I can’t seem to figure this out. Basically, I have sub html blocks I am building that can be reused depending on the parent block. For example, I have a video carousel and video grid. These are the parent blocks and both have repeaters named video_repeate_blocks. In filters.php
, I have added:
//template: sub_block/video
add_filter('acf/load_field/name=video_repeater_blocks', function($field) {
if(empty($field['sub_fields'])) //tried this, didn't work.
{
$field['sub_fields'] = array(
array('ID' => $field['ID']+1,
'parent' => $field['ID'],
'prefix' => 'acf',
'key' => 'field_' . uniqid(),
'label' => 'Title',
'name' => 'title',
'_name' => 'title',
'type' => 'text',
'instructions' => '',
'required' => 0,
'default' => 'test',
'wrapper' => array('id' => '', 'class' => '', 'width' => '',),
),
array('ID' => $field['ID']+1,
'parent' => $field['ID'],
'prefix' => 'acf',
'key' => 'field_' . uniqid(),
'label' => 'Video ID',
'name' => 'video_id',
'_name' => 'title',
'type' => 'text',
'instructions' => '',
'required' => 1,
//'default' => 'test',
'wrapper' => array('id' => '', 'class' => '', 'width' => '',),
),
);
}
///print_r($field);
return $field;
});
The expected behavior is similar to how I autopopulate select fields. Once I make the field with the proper name, it automatically fills in the options. In this case, creates the sub_fields/blocks.
However, the problem is that it seems to be overriding the values put into these automatically created subfields when I actually go to make a block. It won’t save the values. I have to comment this out in filters.php to get it to save my custom values on the wordpress page. I suspect I am using the wrong filter, and it is remaking the fields on each refresh. How do I do this? Thanks.
The reason that this is happening is that every time you run the code the sub fields get assigned a different field key
key' => 'field_' . uniqid(),
When ACF tries to get the value of the new field by the key there is no field value in the DB that using that’s field key. The field key must be the same every time the field is added.
There are probably a lot of ways to do it. The only thing that matters it that it is never changed.
I would probably just do something like
'key' => 'field_videorepeatertitle'
You just need to use something unique.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.