Skip Navigation

[Resolved] Dynamic Field values from CPT

This support ticket is created 4 years, 3 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

Author
Posts
#1716487

I have multiple CPT relationships setup. What I would like to do is the following:

Setup a CRED form that has multiple fields (ok, no problem there 🙂 )
Within the CRED form add several fields from another CPT that I've 'related' to the CPT. This CPT's fields are Text fields but already have values in them. I would like to dynamically pull the values from those fields (like auto complete or as select fields).
Then save the final selections to the CRED form .

Is this possible?

#1716879

Hi,

Thank you for contacting us and I'd be happy to assist.

Something like this can be achieved using the generic fields and the filter "wpt_field_options".
( ref: https://toolset.com/documentation/programmer-reference/types-api-filters/#wpt_field_options )

If you could share temporary admin login details along with the information about the form and the required fields from the other CPTs, I'll be in a better position to guide you in more detail.

Note: Your next reply will be private and please make a complete backup copy, before sharing the access details.

regards,
Waqar

#1720541

Hi,

Thank you for waiting and I apologize for the delay in getting back on this.

Just wanted to let you know that I'm completing some testing and research related to this requirement and will share my detailed findings within the next few hours.

Thank you for your patience.

regards,
Waqar

#1721729

Hi,

Thank you for waiting as this investigation took longer than initially anticipated.

From reviewing the "Add Vehicle" form, I understand that your goal is to automatically populate the available options for the fields "TMNA SIte", "TMNA Function or Area", "TMNA Location" and "TMNA Section".
( these are single-line type fields, but you'd like to use them as select/dropdown field )

This form is also loading the view named "Locations with Fields", to show these fields as the select/dropdown fields.

Instead of using a separate view for this purpose, I'll suggest the following approach which uses a custom shortcode:

1. First, you'll need to register a custom shortcode, which can get all the available values for a specified custom field key from the "wpv-control-postmeta" shortcode ( ref: https://toolset.com/documentation/programmer-reference/views/views-shortcodes/#wpv-control-postmeta ) and create a select/dropdown field using those values:


add_shortcode('get_dynamic_select_options', 'get_dynamic_select_options_fn');
function get_dynamic_select_options_fn($atts) {
	$field = $atts['field'];
	$empty_text = $atts['empty_text'];
	$data = do_shortcode('[wpv-control-postmeta type="select" field="'.$field.'" url_param="wpv-'.$field.'"]');
	$data_arr = explode('value="', $data);

	if(sizeof($data_arr) >= 2)
	{
		for ($i=1; $i < sizeof($data_arr) ; $i++) { 
			$temp_arr = explode('">', $data_arr[$i]);
			if(!empty($temp_arr[1])) {
				$final_data[] = $temp_arr[0];
			}
		}
		if(!empty($final_data))
		{
			ob_start();
			echo '<select class="form-control wpt-form-select form-select select" output="bootstrap" preset_value="" urlparam="" preview="" previewsize="" select_label="" edit_label="" value_escape="" make_readonly="" placeholder="" select_text="" data-wpt-type="select" name="'.$field.'">';
			echo '<option value="">'.$empty_text.'</option>';

			foreach ($final_data as $final_data_item) {
				echo '<option value="'.$final_data_item.'" class="wpt-form-option form-option option" data-wpt-type="option" data-wpt-name="'.$field.'">'.$final_data_item.'</option>';
			}
			echo '</select>';
			return ob_get_clean();
		}
	}
}

2. For this example, suppose that your form has only one field "tmna-site", which needs this transformation.

In the form, right below the actual "tmna-site" field, you can include the "HTML content" block and place this newly registered shortcode, like this:


[get_dynamic_select_options field="wpcf-tmna-site" empty_text="--select--"]

As a result, there will be a select/dropdown field below the actual single-line text input field.

3. You can include some custom CSS code in the form, to hide the original single-line text input field:


input[type="text"][name="wpcf-tmna-site"] {
  display:none;
}

4. Lastly, you can include some custom script in the form, to make this select/dropdown field, use the "select2" script:


jQuery(document).ready(function() {
    jQuery('select[name="wpcf-tmna-site"]').toolset_select2();
});

You can repeat the same steps for the other fields too and when the form will be submitted, the selected values will be saved with the respective custom fields, for the created post.

I hope this helps and please let me know if any point is not clear.

Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

regards,
Waqar

#1723563

Waqar,

This is working great so far and I really appreciate the hard work and research. There are a few questions:

1 - Only the first field displays as select2 - was I supposed to modify something?
2 - Is there a way make the relationships work? What I mean is, if user selects 'x' value from the first field, it should clear away 'y' values from the second, third, and fourth fields (and so on). Kind of like how filters work in a view. I'm asking because there are hundreds of values.
3 - Is there a way to set the 'default' value using select2?
4 - Can I reuse this same function on other forms for the same four fields?

Thanks!

#1724273

Also - when I save (in an edit form) how can I get the select field) to keep showing the selected value?

#1726877

Hi,

Thanks for the update and glad that it is working.

1 - Only the first field displays as select2 - was I supposed to modify something?

- Yes, as I mentioned in the previous reply, I only shared the instructions for a single field "tmna-site".

For all 4 fields, the custom JS code from step 4 would look like this:


jQuery(document).ready(function() {
	jQuery('select[name="wpcf-tmna-site"]').toolset_select2();
	jQuery('select[name="wpcf-tmna-function-or-area"]').toolset_select2();
	jQuery('select[name="wpcf-tmna-location"]').toolset_select2();
	jQuery('select[name="wpcf-tmna-section"]').toolset_select2();
});

2 - Is there a way make the relationships work? What I mean is, if user selects 'x' value from the first field, it should clear away 'y' values from the second, third, and fourth fields (and so on). Kind of like how filters work in a view. I'm asking because there are hundreds of values.

- I'm afraid, this will require quite complex customization, which would be beyond the scope of support that we can provide over the forum.

3 - Is there a way to set the 'default' value using select2?

- In order to pass on the "default" selected option's label and value, you can update the custom shortcode from step 1, to:


add_shortcode('get_dynamic_select_options', 'get_dynamic_select_options_fn');
function get_dynamic_select_options_fn($atts) {
    $field = $atts['field'];
    $default_text = $atts['default_text'];
    $default_value = $atts['default_value'];
    $data = do_shortcode('[wpv-control-postmeta type="select" field="'.$field.'" url_param="wpv-'.$field.'"]');
    $data_arr = explode('value="', $data);
 
    if(sizeof($data_arr) >= 2)
    {
        for ($i=1; $i < sizeof($data_arr) ; $i++) { 
            $temp_arr = explode('">', $data_arr[$i]);
            if(!empty($temp_arr[1])) {
                $final_data[] = $temp_arr[0];
            }
        }
        if(!empty($final_data))
        {
            ob_start();
            echo '<select class="form-control wpt-form-select form-select select" output="bootstrap" preset_value="" urlparam="" preview="" previewsize="" select_label="" edit_label="" value_escape="" make_readonly="" placeholder="" select_text="" data-wpt-type="select" name="'.$field.'">';
            echo '<option value="'.$default_value.'" selected="selected">'.$default_text.'</option>';
 
            foreach ($final_data as $final_data_item) {
                echo '<option value="'.$final_data_item.'" class="wpt-form-option form-option option" data-wpt-type="option" data-wpt-name="'.$field.'">'.$final_data_item.'</option>';
            }
            echo '</select>';
            return ob_get_clean();
        }
    }
}

The updated usage of this shortcode with its new attributes ( step 2 in the previous reply ), would look like this:


[get_dynamic_select_options field="wpcf-tmna-site" default_text="--select--" default_value=""]

Feel free to adjust the values for the attributes "default_text" & "default_value", as needed.

4 - Can I reuse this same function on other forms for the same four fields?

- Yes, the custom shortcode from step 1 would just need to be included once and it can be re-used in other forms too.

Of course, you'll need to include the custom CSS and JS code from the other steps, in each form.

5. Also - when I save (in an edit form) how can I get the select field) to keep showing the selected value?

- In case of an edit form, the custom JS code shared in question 1 of this message would need to be slightly modified, so that it can get the value from the respective input field (hidden) and then select the matching option, before initializing the select2 script:


jQuery(document).ready(function() {
	var wpcftmnasite = jQuery('input[type="text"][name="wpcf-tmna-site"]').val();
	jQuery('option:selected', 'select[name="wpcf-tmna-site"]').removeAttr('selected');
	jQuery('select[name="wpcf-tmna-site').find('option[value="'+wpcftmnasite+'"]').attr("selected",true);
	jQuery('select[name="wpcf-tmna-site"]').toolset_select2();

	var wpcftmnafunctionorarea = jQuery('input[type="text"][name="wpcf-tmna-function-or-area"]').val();
	jQuery('option:selected', 'select[name="wpcf-tmna-function-or-area"]').removeAttr('selected');
	jQuery('select[name="wpcf-tmna-function-or-area').find('option[value="'+wpcftmnafunctionorarea+'"]').attr("selected",true);
	jQuery('select[name="wpcf-tmna-function-or-area"]').toolset_select2();

	var wpcftmnalocation = jQuery('input[type="text"][name="wpcf-tmna-location"]').val();
	jQuery('option:selected', 'select[name="wpcf-tmna-location"]').removeAttr('selected');
	jQuery('select[name="wpcf-tmna-location').find('option[value="'+wpcftmnalocation+'"]').attr("selected",true);
	jQuery('select[name="wpcf-tmna-location"]').toolset_select2();

	var wpcftmnasection = jQuery('input[type="text"][name="wpcf-tmna-section"]').val();
	jQuery('option:selected', 'select[name="wpcf-tmna-section"]').removeAttr('selected');
	jQuery('select[name="wpcf-tmna-section').find('option[value="'+wpcftmnasection+'"]').attr("selected",true);
	jQuery('select[name="wpcf-tmna-section"]').toolset_select2();
});

regards,
Waqar

#1727719

One last question. If I wanted to use the post-title as one of the fields, is the process the same? IOW, If I had a custom field called 'alt-post-title' and then


[get_dynamic_select_options field="wpcf-alt-post-title" default_text="--select--" default_value=""]

jQuery(document).ready(function() {
    var wpcfaltpostitle = jQuery('input[type="text"][name="wpcf-alt-post-title"]').val();
    jQuery('option:selected', 'select[name="wpcf-alt-post-title"]').removeAttr('selected');
    jQuery('select[name="wpcf-alt-post-title').find('option[value="'+wpcfaltpostitle+'"]').attr("selected",true);
    jQuery('select[name="wpcf-alt-post-title"]').toolset_select2();
});

Thanks!

#1729381

Hi,

Thanks for writing back.

Your understanding of the steps for a different field is correct and it should work the same way.

regards,
Waqar

#1729979

Ok, I think I'm either overcomplicating this in my head or misunderstanding my own instructions 🙂

How do I call the post title from a different CPT into the CRED form of another for this function to work? I don't see the post-title option in the CRED editor. Do I need to figure out the relationship using views and insert it that way? ie [wpv-post-title item="@vehicle-tmna-location.child"] ???

New threads created by Waqar and linked to this one are listed below:

https://toolset.com/forums/topic/split-call-the-post-title-from-one-cpt-into-the-cred-form-of-another/

#1730903

Hi,

Since in this thread, we have been discussing getting the values of available custom fields to create a dynamic list for the select/dropdown, I've split this question related to post titles into a separate ticket, to avoid any confusion.
( ref: https://toolset.com/forums/topic/split-call-the-post-title-from-one-cpt-into-the-cred-form-of-another/ )

You're welcome to mark this ticket as resolved and I'll follow-up about the post title requirement on that new ticket.

regards,
Waqar

#1731189

My issue is resolved now. Thank you!

#1753601

Hi,

I've reopened this ticket as you mentioned you need some further assistance on this.
( ref: https://toolset.com/forums/topic/view-with-weekday-filtering/#post-1750439 )

Please feel free to share the exact details of what is not working here.

regards,
Waqar

#1754173

After you are logged in go to :

homepage and you will see a section called 'All Vehicles". In that section there is a column called 'Garage' which should list the current locations based upon the 'TMNA Location" CPT title that had been selected previously. But that has gone away for some reason.

The view associated with that section is:

view_id=674

You can review the functions file directly from within the dashboard using wpfilemanager.

So there are two things that are broken (all of a sudden) 1) the previously selected vehicle location within each 'Vehicle' post is now missing. This selection is a select field that points to the 'TMNA Location' post titles. 2) because the first thing is broken, the previously selected locations are not appearing in the view.

BTW- if you look at any random post under the 'vehicles' CPT and scroll down to the 'vehicles TMNA Locations' relationship block it does still show the correct information. It just doesn't populate the information in the 'vehicle location' custom field as it's supposed to do.

Thanks

#1755993

Thank you for sharing these details.

I noticed that for showing the "tmna-location" field values in the "Garage" column, the shortcode used was:


[types field='tmna-location' item='@vehicle-tmna-location.parent'][/types]

But since in this "vehicle-tmna-location" relationship, "vehicle" post type is the parent and the "tmna-location" is the child, it should be the other way around:
( ref: https://toolset.com/documentation/programmer-reference/views/views-shortcodes/item-attribute/ )


[types field='tmna-location' item='@vehicle-tmna-location.child'][/types]

I've updated this shortcode and the field values are now showing correctly in the "Garage" column.