Support Forum
Support › MB Frontend Submission › How can I pre-populate fields in new frontend submission?Resolved
I have two custom post types - tramp-detail and tramp-log, with field tramp_id and tramp_log_id joined by a MB Relationship.
Website visitors viewing a tramp single page can click a link that will take them to a new tramp-log frontend submission form.
I want to pass the tramp_id to the front-end submission form via url parameter (example.com/add-tramp-log/?tramp_id=123) and use it to pre-populate the tramp_id in the relationship field.
Is it possible to pre-populate fields in a frontend submission form? If so, is someone able to give an example please? I've searched for some time and haven't found any examples.
Thanks in advance!
Hello Phil,
I think it is possible. You will need to register the relationship by code to use the select
field and some jQuery code to pre-select the dropdown value. For example:
Code to register the relationship:
MB_Relationships_API::register( [
'id' => 'tramp_detail_to_tramp_log',
'from' => [
'object_type' => 'post',
'post_type' => 'tramp-detail',
'field' => [
'field_type' => 'select',
]
],
'to' => [
'object_type' => 'post',
'post_type' => 'tramp-log',
'field' => [
'field_type' => 'select',
]
],
] );
jQuery code:
jQuery(document).ready(function($) {
//get the ID from the URL and assign it to "value"
$('#tramp_detail_to_tramp_log_to option[value=123]').attr('selected', 'selected');
});
you can change tramp_detail_to_tramp_log_to
to tramp_detail_to_tramp_log_from
depending on the relationship side.
Note: the code is for example. If you cannot complete the task, please contact an expert developer to help you in this case.
Thank you.
Here's how I ended up doing this with code in functions.php:
// Check if the current page is the "add new post" front end submission page for the "tramp-log" custom post type
$current_page_id = get_the_ID();
//if (is_page('15585')) {
if ($current_page_id == "15585") {
/* see https://docs.metabox.io/filters/rwmb-field-meta/ */
add_filter("rwmb_tramp_id_field_meta",function ($value, $field, $saved) {
$value = isset($_GET["tramp_id"]) ? $_GET["tramp_id"] : $value;
return [$value, $field];
},10,3);
}