Skip Navigation

[Gelöst] Dynamically populated third part form field by custom field of the child post

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.

This topic contains 14 Antworten, has 3 Stimmen.

Last updated by Ljuba vor 3 Jahre, 2 Monate.

Assigned support staff: Beda.

Author
Artikel
#1126999

Tell us what you are trying to do?

==> Nigel successfully created snippet for Formidable Forms Dropdown field dynamically populated by child post title (of custom post where form appear). Now I would like to extend solution and to populate another field (slider) with custom fields values from that child post (ie - room numbers, adults capacity, child's capacity, ...).

I guess that only (functional) part of the code

foreach ($posts as $p) {
            $values['options'][$p->ID] = $p->post_title;
        }

should be changed with something (I guess field slug - ie for adults capacity > 'clientes-dormir-en-habitacion' - form field ID is instead of 94 > 71) in part of the 'post_title', but to be honest, no idea is it correct.

Entire code is as

add_filter('frm_setup_new_fields_vars', 'frm_populate_posts', 20, 2);
function frm_populate_posts($values, $field) {
 
    if ($field->id == 94) {
        // edit field ID as required
 
        // Get the parent post id from $post or wp_get_referer
        // depending on whether initial page load or ajax request
 
        if (wp_doing_ajax()) {
 
            $url = wp_get_referer();
            $parent_id = url_to_postid($url);
 
        } else {
            global $post;
            $parent_id = $post->ID;
        }
	  
        $relationship = "alojamiento-habitacion";
 
        $posts = toolset_get_related_posts(
            $parent_id, // get posts related to this one
            $relationship, // relationship between the posts
            'parent', // get posts where $parent_post is the parent in given relationship
            999, 0, // pagination
            array(), // arguments not required
            'post_object',
            'child'
        );
 
        unset($values['options']);
        $values['options'] = array(''); //remove this line if you are using a checkbox or radio button field
        $values['options'][''] = '';
        foreach ($posts as $p) {
            $values['options'][$p->ID] = $p->post_title;
        }
        $values['use_key'] = true; //this will set the field to save the post ID instead of post title
        unset($values['options'][0]);
    }
    return $values;
}

Also, can it be done within update of the code of the same snippet or must be used different snippet for each field?

#1127382

Nigel
Supporter

Languages: Englisch (English ) Spanisch (Español )

Timezone: Europe/London (GMT+00:00)

First, about re-using the same code.

If you are going to be modifying several form fields where you need to get data from child posts, the first part of the code is going to be needed each time, so I'd suggest you structure the code so that you first compare the field id against an array of field ids you want to modify for this particular relationship, and then after you have obtained the parent post id and retrieved the list of child posts, you use switch-case blocks to do different things to customise the field values depending on the id of the field.

So your code structure might look like this:

add_filter('frm_setup_new_fields_vars', 'frm_populate_posts', 20, 2);
function frm_populate_posts($values, $field) {
  
    // IDs of fields to be modified by this code for this relationship
    $modify_fields = array( 10, 55, 94, 101 );
    $relationship = "alojamiento-habitacion";

    if ( in_array( $field->id, $modify_fields ) ) {

        // Get the parent post id from $post or wp_get_referer
        // depending on whether initial page load or ajax request
        if (wp_doing_ajax()) {
            $url = wp_get_referer();
            $parent_id = url_to_postid($url);
          } else {
            global $post;
            $parent_id = $post->ID;
        }
       
        $posts = toolset_get_related_posts(
            $parent_id, // get posts related to this one
            $relationship, // relationship between the posts
            'parent', // get posts where $parent_post is the parent in given relationship
            999, 0, // pagination
            array(), // arguments not required
            'post_object',
            'child'
        );
  

        switch ( $field->id ) {
            case '94':
                # modify values for field 94
                unset($values['options']);
                $values['options'] = array(''); //remove this line if you are using a checkbox or radio button field
                $values['options'][''] = '';
                foreach ($posts as $p) {
                    $values['options'][$p->ID] = $p->post_title;
                }
                $values['use_key'] = true; //this will set the field to save the post ID instead of post title
                unset($values['options'][0]);

                break;
            
        }
    }


    return $values;
}

That should work as before.

But as for what the code itself should be for each field, well... I don't know. You are using the Formidable Forms API to dynamically set up the field values. I think it was Beda that created the example used above to set the values for a select dropdown, which simply dynamically recreates what you would see if you had manually created a select dropdown in the UI with the same options.

For other fields, I would manually create some sample fields which you would like to emulate dynamically.

Make use of dumping the available variables—specifically the $values attribute that must be returned—to the error logs to see what is expected, and then try to reproduce that.

I've shown how you can get the ID of the post where the form is displayed, and the Toolset API to posts connected to it through a relationship, and you can use standard functions such as get_post_meta to get field values of such posts to use as option values for the Formidable fields.

It is a question of working through manually created examples of the fields you want to include, and then recreating the $values structure with values of fields you get from the parent or child posts.

#1128826

Hello Nigel,

Thanks for code. It works 100% - regards the multiple fields usage.

You probably could to imagine that I asked Formidable for second part for support and despite that I have "Elite support" (it is actually more than cynical idea from Firmidable to call it as it is), that support replied - ZERO HELP (not even API links, documentation, etc - NOTHING -> support statement).

So, can you please ask Beda can he take a look for moment and maybe get idea how to solve it?

Otherwise, we can close ticket (nothing else is left).

#1129593

Nigel
Supporter

Languages: Englisch (English ) Spanisch (Español )

Timezone: Europe/London (GMT+00:00)

I'll try and take another look when my queue is quieter.

#1130093

Thanks. What you think about idea to switch in form to dropdown fields instead of sliders (as dropdown proven works)?

#1135054

Nigel
Supporter

Languages: Englisch (English ) Spanisch (Español )

Timezone: Europe/London (GMT+00:00)

Screenshot 2018-10-26 at 15.07.39.png

Hi Ljuba

I just had a few minutes to look at this before I stop and have a week off.

I'm logged in to your site, and testing the Hostal Bumba alojamiento post.

The code we used before means that the select dropdown for "Seleccione la habitación" includes the child habitaciones posts as options, both in the first instance and when adding a repeater, which leaves where you see in the screenshot.

What I'm not sure is what is supposed to happen next.

You have several fields, habitaciones, adultos, and niños, plus start and end dates.

From your question it seems like these should be customised automatically, but I don't really understand.

Aren't these fields that the user making the booking request is supposed to fill in?

Maybe they are only supposed to fill them in once (same start and end date for each room, total number of adults and children for the booking, not individual numbers per room), but if that's the case I'm not sure that these fields belong to the habitaciones.

Can you clarify? I might not be able to look again for a while.

#1135125

I will try now to be systematic. Important part is to understand how exactly Booking form is less important to get that feature, but from other side is excellent to explain the goal of topic. Accordingly, at the end, I will expose real benefits in same (but other) forms, for Gastronomia, Servicios and Compras CPT forms (forms will be done on same grounds).

FORM STRUCTURE (fields mapping)

Form contain 3 kind of fields (regards data population):

1) 'Child post title' field (here in Formidable Booking Form is field "Seleccione la habitación" and have Formidable ID 94). It is populated by child post titles and it works just fine.

2) 'Child post fields' fields (here in Formidable Booking Form are "Habitaciones", "Adultos" and "Niños" and have Formidable ID respectively 70, 71 and 72). At the moment, they are populated by fix numbers (could be words also), but they should be populated by child post filed values, as follows:

a) "Habitaciones" should be populated by Habitaciones child post field ("Número de habitaciones (de este tipo)" - slug is "numero-de-habitaciones-de-este-tipo") values.

b) "Adultos" should be populated by Habitaciones child post field ("¿Cuántos clientes pueden dormir en esta habitación?" - slug is "clientes-dormir-en-habitacion") values.

c) "Niños" should be populated by Niños child post field ("Niño adicional" - slug is "nino-adicional") values.

P.S. - So, you can see that here is two different Alojamientos child post types involved.

3) 'Generic post fields' (all other form fields).

EXPLANATION

It is obvious how for Booking form is not some bid deal to get those fields populated by some fixed values (on the net, that is the mostly how it is done). But I'm much more interested for other forms and here I will expose Food Order Form example (and let it to be Pizzeria, as Gastronomia post type).

Obviously, pizza types will be (Menu) child post titles - so, 100% equally to "Seleccione la habitación", will be "Selecciona la pizza".

Problematic part is now how to let customers/visitors to customize pizza and set (populate) "custom values" in order form ("pizza size", "pizza crust", "extra toppings", ....). It cannot be by administrator populated values, as it is different per geographic areas, season, pizzeria itself, .... Same is with Compras and example of T-shirts numbers and colors (can't be fix values).

BACK TO FORM

So, equally to pizza "extra toppings", or T-Shirt "available colors", owner of Alojamiento, should to fill capacity of the particular room (ie - Familiar) and to set room capacity ("Adultos") or number of available familiar rooms and such custom values should to populate fields and not the fix values set by administrator.

Hopefully, I was clear.

#1136743

Hi Ljuba

Do you need help with getting data of Toolset with Toolset API or populating a 3rd party Field with data?

For first, I do not see how else we can help as Nigel seems to have provided working examples(https://toolset.com/forums/topic/dynamically-populated-third-part-form-field-by-custom-field-of-the-child-post/#post-1127382) on how to get the data, is this Correct?

For the second (https://toolset.com/forums/topic/dynamically-populated-third-part-form-field-by-custom-field-of-the-child-post/#post-1128826), we cannot help as that is not within our support umbrella.
3rd Party Software should support and document their features and functions independently from Toolset.
https://toolset.com/toolset-support-policy/

#1136979

Hi Beda,

Answering to your post is not so simple, as there are several dimensions of topic (and issue, generally).

1) If we observe by itself Formidable Support - it sucks 101% and there is nothing to discuss.

2) If we observe Toolset Support (specifically Nigel), it is AMAZING - 101% sure. So, he already did more than I expected and there is nothing to discuss, as well.

3) (first) Problem appear with your questions, as nether one of that is subject of topic. It is third.

==> I need help with getting data from Toolset child post field values with Toolset API.

So, it is completely different from your first option, as it is too much generalized by term - 'data'. Fact is that BY YOU (in other topic) is solved how to get child post title and it is 'fixed' by Nigel (also in other topic). In this topic, Nigel solved how to use same function within one (third party or CRED) form. And I confirmed that it works.

==> However, I don't want to claim how Toolset Support cover such question (this topic). If you will insist how it is not covered by support, I will not argue (as well as I didn't with Formidable).

BTW, Formidable basically claim how they can't support how to getting data from Toolset child post field values with Toolset API, as it is about the values from CPT and custom fields created by third part plugin (Toolset) and not by Formidable Form - and that is correct claim.

Problem is that until when two plugins Supports claim lack of responsibility (jurisdiction) over the issue, customer remain without functionality. But, no problem, as this is my fault to choose (and pay) plugins.

5) Also, in your reply, it looks how you overlooked another topic (covered by you - and closed), where we both concluded how Toolset most likely NEVER WILL PROVIDE similar functionality (what I need and you stated that wish to get such option available, as well) and I'm slightly confused that you want so easy to 'drop it'.

FINAL

So, if you decide that Toolset don't have interests to provide such extended functionalities (what by itself probably never will get), no problem.

But primary, you should be clear, about Toolset support regards:

==> I need help with getting data from Toolset child post field values with Toolset API.

Is it covered or not?

#1137456

I have no idea what you need, Ljuba, I asked what you need, not how you think our Support should work.

It is the same issue as in all other tickets, it is not clear, what is needed.

Please tell me what you need, and if Toolset can help with or do it, I will show you how.

If you need to get data of posts in a Toolset Relationship, then Formidable PRO is just fine telling you that they cannot help you with this, and we will and do help you with this.
We do not help you to populate a 3rd party with that data.
But, that is not a problem, because if you need to get that data, and we help with, later you can take that data, go to Formidable Pro support and tell them:
"I need to populate your select field with this array of ID's" (for example)
They, in turn, will then be able (or not) to help you with this.

Hence, I need to know what you need from us on this ticket.

I understand:
Dynamically populated third part form field by custom field of the child post

So, that we cannot help with.
We can help with "by custom field of the child post".
This means, I can show you (I did in past already, but I can again) how to get data, that is related to a certain Post, data related in a Toolset Relationship.
This is as shown in past, done with toolset_get_related_post(s) API:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/

Those functions generally return Post ID and from that Post ID, you can get anything of the Post using native WordPress API.
That data, whether a field, ID; text, or else, can then (if they have an API for it) be passed in the exact format as expected by that API to the 3rd party.
Conversion to correct format, and coding 3rd party API will not be supported here.
How to get the data will be supported on hand of examples by our support at any time you need this.

Please let me know if you need such an example of how to get data of Toolset Related posts.

#1137766

I'm trying my best to be precise. I thought that I wrote clearly on initial post that I'm asking what should to be changed in part of the code (now after Nigel change in https://toolset.com/forums/topic/dynamically-populated-third-part-form-field-by-custom-field-of-the-child-post/#post-1127382):

        switch ( $field->id ) {
            case '94':
                # modify values for field 94
                unset($values['options']);
                $values['options'] = array(''); //remove this line if you are using a checkbox or radio button field
                $values['options'][''] = '';
                foreach ($posts as $p) {
                    $values['options'][$p->ID] = $p->post_title;
                }
                $values['use_key'] = true; //this will set the field to save the post ID instead of post title
                unset($values['options'][0]);
 
                break;
             
        }

for what I believe (I could be wrong, but Formidable claim that it is Toolset part of the code) that is the part of the code handled by Toolset.

If I'm not wrong, this part of the code provide title of the child post.

In this topic, instead of child post title, I need values from the custom fields from that same child post (fields mapping already explained in https://toolset.com/forums/topic/dynamically-populated-third-part-form-field-by-custom-field-of-the-child-post/#post-1135125).

Hopefully, it is enough clear.

#1138076
//This is not a Toolset Filter. See <em><u>hidden link</u></em>
add_filter('frm_setup_new_fields_vars', 'frm_populate_posts', 20, 2);

//Here you create a Function that then is called in above filter. Not Toolset Code. 
function frm_populate_posts($values, $field) {
   
    // Here you manually set some ID's. No Toolset API involved.
    $modify_fields = array( 10, 55, 94, 101 );

    //Here you set the relationship slug. This is the Toolset Relationship.
    $relationship = "alojamiento-habitacion";
 
    //Here check if your hardcoded $modify_fields values match $field->id. $field->id is NOT a Toolset data or API. It's Formidable Pro. I do not know and cannot know what it delivers, you can find out with var_dump($field->id).
    if ( in_array( $field->id, $modify_fields ) ) {
 
         
        // You are not using a single toolset API code or line here, this is all pure PHP, where you check if you are doing AJAX, then you define a $url with a WordPress native function wp_get_referer() and get it's url_to_postid (also a WP Native Function). You else get the $post global (also WordPress) and it's ID. No Toolset API or Data is involved here, eventually, this can be used or done without Toolset at all, since you just use WordPress code.
        if (wp_doing_ajax()) {
            $url = wp_get_referer();
            $parent_id = url_to_postid($url);
          } else {
            global $post;
            $parent_id = $post->ID;
        }
         
       //THIS is Toolset API and HERE only we can and will help
      // Now here, we toolset_get_related_posts. This means we will get ALL posts that are related to a post we tell the code to check for. This is the $parent_id you defined above, you will receive all related posts OBJECTS (as you say 'post_object', to be returned) of the related posts. a Post OBJECT is big, it holds ALL Data of the post, so if you here want ONLY the ID; then you would tell the code, according to our doc, to return only the Post ID. https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/

        $posts = toolset_get_related_posts(
            $parent_id, // get posts related to this one
            $relationship, // relationship between the posts
            'parent', // get posts where $parent_post is the parent in given relationship
            999, 0, // pagination
            array(), // arguments not required
            'post_object',
            'child'
        );
   
       //switch is a PHP function <em><u>hidden link</u></em>
       //$field is not Toolset data it is from Formidable pro. The WHOLE code following is Formidable Pro Code.
      //It seems to populate an array of options, and they will expect a certain type of data.
      //You seem to want to pass the Post Title as it's value to it. 
      //What you need to know is:
      //1. What does Formidable Pro expect in $values['options'][$p->ID]? Then, populate it with it.
      //If it expects an ID make sure, that $posts as $p->ID really gives you the ID of the Post. This can be done with var_dump($posts) and var_dump($p) in the respective places
        switch ( $field->id ) {
            case '94':
                # modify values for field 94
                unset($values['options']);
                $values['options'] = array(''); //remove this line if you are using a checkbox or radio button field
                $values['options'][''] = '';
                foreach ($posts as $p) {
                    $values['options'][$p->ID] = $p->post_title;
                }
                $values['use_key'] = true; //this will set the field to save the post ID instead of post title
                unset($values['options'][0]);
 
                break;
             
        }
    }
 
 
    return $values;
}

There is not a single line referring to any of Toolset's API's or data unless the toolset_get_related_posts.

I commented the code detailed.

Related to the problem:

I guess that only (functional) part of the code
foreach ($posts as $p) {
$values['options'][$p->ID] = $p->post_title;
}
should be changed with something (I guess field slug - ie for adults capacity > 'clientes-dormir-en-habitacion' - form field ID is instead of 94 > 71) in part of the 'post_title', but to be honest, no idea is it correct.

This is not something we can answer but Formidable Pro can because that code is 100% related to the API of that plugin.
Just imagine instead of Toolset Posts you get hardcoded posts, then that line is STILL defining the data passed to Formidable Pro and handled by their Function, not by ours.

You need to know what Formidable Pro expects in it's function and variables.
Then, we can help to get that data with Toolset API, if you need help with.

You can ask them for a simple example, you do not need to mention that later you will get related data by toolset. All you need is an example of their code that does what you want with a preset amount of posts in a post type of your choice, you can even chose pages for the example, so you can ask for an example on a vanilla install.
We cannot provide that example as simply it's not our API populating that field.

I hope this is clear.

We are eager to help and will/do help, but cannot become experts in 3rd Parties we do not produce or use.

#1138249

Thanks Beda. It is now clear for me. As now are holidays, I will ask Formidable and still let ticket open until the answer come (I have 'Elite support' - should be within 24 hours at working day).

#1138872

Sure!

FYI, I will be (exceptionally) away tomorrow Saturday and back only next Tuesday.
If you need fast assistance and post a comment here, I will see it and can assign the issue back to Nigel, in case.

Thanks!

#1140630

As my "Elite Support" on Formidable Pro expired at November 4 and that "Elite Support" in any case obviously didn't want to help, I will close ticket and quit from these feature.