Home › Forums › Front-end Issues › Post Object Field – Set selected value programatically
Hello,
I have a front-end form that contains a Post Object Relationship field and I am trying to dynamically set the selected value of the field when the page is loaded. Can anyone point me in the right direction?
I am creating the form like this:
$post_id = $_GET['post']; //I need to set this value as the selected post id in the field (ID #field_57319b21314aa)
$clip_id = $_GET['clip'];
$options = array(
'post_id' => $clip_id,
'post_title' => false,
'field_groups' => array(131),
'submit_value' => 'Save Video Clip',
'uploader' => 'wp'
);
acf_form( $options );
//not sure what I should add next?
You can use the update_field function to put the post ID in outside of anything related to the ACF form:
<?php update_field($selector, $value, $post_id); ?>
$selector would be the field ID: field_57319b21314aa
Depending on the rest of the setup I think would depend on how would be most effective to get that information into the form, whether it’s populated before or after you submit. It could be possible to use the WP pre_get_posts() hook or the acf/save_post hook, grab the post ID and then update the field with it in the relevant place.
I would also like to know how to set the value programmatically but using JavaScript after the page has been loaded.
I believe you can do it by using the acf/prepare_field hook. Here’s an example to do it:
function my_acf_prepare_field4( $field ) {
if( isset($_GET['post']) ){
$post_id = $_GET['post'];
$field['value'] = $post_id;
}
return $field;
}
// name
add_filter('acf/prepare_field/name=custom_field_name', 'my_acf_prepare_field4');
ACF uses select2 for the post object. To do it, please take a look at this thread: http://stackoverflow.com/questions/19639951/how-do-i-change-selected-value-of-select2-dropdown-with-jqgrid. Also, please take a look at this page to learn more how to use ACF with Javascript: https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/.
I hope this helps 🙂
The topic ‘Post Object Field – Set selected value programatically’ is closed to new replies.
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.