Home › Forums › ACF PRO › check if block instance already exists › Reply To: check if block instance already exists
Hi @carlparkerwp that’s correct, but it’s a bit more complex than that.
I’m trying to update the entire $fields array with default values (which I’m pulling from a block in another post) at once, and I want to make sure the edit-form fields are populated correctly as well.
I actually found my solution after some trial and error. It turns out that in the acf/pre_render_fields
filter get_fields()
will return false
if the current block was not saved to the database previously.
So, this works for my case:
add_filter( 'acf/pre_render_fields', function( $fields, $post_id ) {
if(!get_fields($post_id)) {
// add some default values to the $fields array
}
$return fields;
}, 10, 2
Actually, I’m doing some additional checks to see If I’m actually loading field blocks, so my actual code is this:
add_filter( 'acf/pre_render_fields', function( $fields, $post_id ) {
if (
// check if we are fetching a block
($_POST['action'] ?? '') !== 'acf/ajax/fetch-block' ||
// check if we are loading the block's edit-form (not the preview)
($_POST['query']['form'] ?? '') !== 'true' ||
// check if the block is a new block
get_fields() !== false
) {
return $fields;
}
$fields = populate_fields_with_default_data($fields, $fields[0]['parent']);
return $fields;
}, 20, 2 );
For brevity I haven’t included the entire populate_fields_with_default_data()
function. This is a pretty complicated custom function that I have written for my own use case, so I don’t think others will benefit from this 🙂
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.