Skip Navigation

[Resolved] Create M2M related post with information from current post

This thread is resolved. Here is a description of the problem and solution.

Problem: I have two post types, Patients and Threads, in an M2M relationship. On the Patient single post, I would like to allow site Users to create a new Thread, and automatically relate it to the current Patient. I would also like to include information from the current Patient in the post body of the new Thread.

Solution: It's not currently possible to create a new post and related it to another post in an M2M relationship using only one Form, so you would have to use custom code.
1. Create the new Thread Form and modify the Form contents so that only the submit button is shown, and add a generic field to contain the current Patient ID:

[credform]
    [cred_field field="form_messages" class="alert alert-warning"]
    <div style="display:none;">
        [cred_field field="post_title" class="form-control" output="bootstrap" value="Re: [wpv-post-title]"]
        [cred_field field='post_content' output='bootstrap' value="Re: [wpv-post-link]"]
        [cred_generic_field type='hidden' field='patient']
{
"default":"[wpv-post-id]"
}
[/cred_generic_field]
    </div>
    [cred_field field="form_submit" output="bootstrap" value="Create Thread" class="btn btn-primary btn-lg"]
[/credform]

2. Set up the Form to redirect to any other custom Page after submission.
3. Insert that View in your Template Layout for Patients.
4. Use the Forms API and the Post Relationships API to automatically connect the new Thread to the current Patient:

add_action('cred_save_data', 'cred_link_patient_and_thread',10,2);
function cred_link_patient_and_thread($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id'] == 12345 )
    {
      toolset_connect_posts( 'patient-thread', $post_id, $_POST['patient'] );
    }
}

5. Create an Edit Thread Form and place it in an unassigned Layout.
6. Use the Forms API to programmatically modify the Form redirect for the New Thread Form, and point it to the Edit Thread Form URL:

add_filter('cred_success_redirect', 'custom_redirect_to_edit_thread',10,3);
function custom_redirect_to_edit_thread($url, $post_id, $form_data)
{
    if ($form_data['id']==12345)
      $redirect = get_the_permalink($post_id) . '?layout_id=67890';  
      return $redirect;
    return $url;
}

7. Use the Forms API to add complex HTML to the new Thread post_content, including information from the Patient post:

add_action('cred_before_save_data', 'cred_generate_new_thread_content',10,1);
function cred_generate_new_thread_content($form_data)
{
    // if a specific form
    if ($form_data['id']==12345)
    {
        if (isset($_POST['patient']))
        {
            // build the post_content using the patient's information
            $patient = $_POST['patient'];
            $dob = types_render_field("date-of-birth", array("style" => "text", "id" => $patient) );
            $body = "<h2>Patient: " . get_the_title( $patient ) . "</h2>";
            $body .= "<div>Patient's date of birth: " . $dob . "</div>";
            $_POST['post_content'] = $body;
        }
    }
}

Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/

This support ticket is created 6 years, 2 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
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 14 replies, has 2 voices.

Last updated by Ido Angel 6 years, 2 months ago.

Assisted by: Christian Cox.

Author
Posts
#1131911

Hey,

I have 2 cpts:

1) patients
2) threads (for discussion)

I want to create a button within a single patient, which will enable me to create a new thread with the title copied from the patient and the body includes a link to the single patient which i shared.

I created a relationship (many to many) between the two, and a relationship form (which i inserted into the single-patient layout). But the form only enables me to connect the current patient to an existing thread, while what i want is to create a new thread related to that same patient.

I also would like to have the new thread created have the title be something like "re: [patient-name]" and the body to automatically include a link to the patient's page.

Is this possible?

Thanks!

#1132123

Creating and relating M2M posts in a single Form isn't a built-in feature, but I can show you how to do something similar with a bit of custom code using the Post Relationships API. Can you clarify what happens when the User clicks a button to create a new thread from the patient post? Are you saying the User is redirected to a page containing a New Thread Post Form, with some information already predefined, or are you saying the Thread post is created automatically without the User's input in any Form fields?

#1132129

Hey Chris!
Thx, that would be great 🙂
I already have an existing patient. Pressing the "share" button should move to a new page and create a new thread with the patient-thread relationship view inside it's body + leaving room for the actual new thread' body.

Right now this is possible only if I first create the thread then via credit relationship form I connect the patient to the thread.

Thx!

#1132200

Okay first set up a "Create New Thread" Form. Strip out everything except the post title field, the post content field, and the submit button. Hide the title and content fields with CSS. Set the new Thread title and content using the "value" attribute of each field, and add a generic hidden field that contains the ID of the Patient post, like this:

[credform]
	[cred_field field="form_messages" class="alert alert-warning"]
	<div style="display:none;">
		[cred_field field="post_title" class="form-control" output="bootstrap" value="Re: [wpv-post-title]"]
		[cred_field field='post_content' output='bootstrap' value="Re: [wpv-post-link]"]
		[cred_generic_field type='hidden' field='patient']
{
"default":"[wpv-post-id]"
}
[/cred_generic_field]
	</div>
	[cred_field field="form_submit" output="bootstrap" value="Create Thread" class="btn btn-primary btn-lg"]
[/credform]

Now insert this Form in your Patient template, so your Users can click "Create Thread" to create a new Thread post. Add this custom code to automatically connect the new Thread with the current Patient:

add_action('cred_save_data', 'cred_link_patient_and_thread',10,2);
function cred_link_patient_and_thread($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id'] == 12345 )
    {
      toolset_connect_posts( 'patient-thread', $_POST['patient'], $post_id );
    }
}

Replace 12345 with the numeric ID of the New Thread Form, and replace patient-thread with the slug of the M2M relationship. I'm assuming Patient is the parent and Thread is the child. If not, the last two parameters should be switched. Now when the "Create Thread" button is clicked, a new Thread will be created and automatically linked to the Patient post. Next, you want to redirect the User to a page containing an Edit Thread Form, so they can add to the post content.

Next create an "Edit Thread" Form. Autogenerate the Form contents, and then insert the Form in an unassigned Content Template (or Template Layout if your site uses Layouts). Edit the New Thread Form and be sure that it is set up to "Go to a post" after the Form is submitted (choose any post, we will override this in code).

Now add this custom code to redirect to the Edit Thread Form:

add_filter('cred_success_redirect', 'custom_redirect_to_edit_thread',10,3);
function custom_redirect_to_edit_thread($url, $post_id, $form_data)
{
    if ($form_data['id']==12345)
      $redirect = get_the_permalink($post_id) . '?content-template-id=67890';  
      return $redirect;
    return $url;
}

Replace 12345 with the numeric ID of the New Thread Form, and replace 67890 with the numeric ID of the Content Template containing the Edit Thread Form. The syntax is slightly different if your site uses Layouts:

...
$redirect = get_the_permalink($post_id) . '?layout_id=67890'; 
...
#1132213

Thanks!

I did everything until after this code:

add_action('cred_save_data', 'cred_link_patient_and_thread',10,2);
function cred_link_patient_and_thread($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id'] == 219 )
    {
      toolset_connect_posts( 'thread-patient', $_POST['patient'], $post_id );
    }
}

but when i press the button it takes me to a bad url like:

hidden link

what did i do wrong?

#1132218

...however - i see the thread WAS created. It has the right title but in the content all i get it "No items found".

#1132233

but when i press the button it takes me to a bad url
First, check the settings in the New Thread Form. In the settings "What to show after submitting the form:", you should choose "Go to a page..." and select any custom page. See the screenshot.
Next, be sure to add the cred_success_redirect code I included above. This will redirect your Users to the correct URL to edit the new Thread.

in the content all i get it "No items found".
Try changing the wpv-post-link shortcode to be wpv-post-url and see if that helps:

[cred_field field='post_content' output='bootstrap' value="Re: [wpv-post-url]"]

If not, I'll need to take a closer look.

#1132234

done evething - same problem...

#1132237

Okay can I take a look in wp-admin? Private reply fields are active here.

#1132244

In your thread-patient relationship, Threads are parents and Patients are children. You can see that here: hidden link

With that in mind, you should change the order of the last two toolset_connect_posts function parameters like this:

toolset_connect_posts( 'thread-patient', $post_id, $_POST['patient'] );

I made this change in your child theme's functions.php file, and now I'm being redirected to the Edit Thread Form as expected when I click "Create Thread". Test again and let me know if it's not working as expected. Be sure to copy the updated functions.php file down to your local working files.

https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_connect_posts

#1132248
Untitled-1.jpg

working now! i switched it before because you said:
replace patient-thread with the slug of the M2M relationship. I'm assuming Patient is the parent and Thread is the child. If not, the last two parameters should be switched... or i thought i did? 🙂 anyway - works now, great!
the only thing is i don't want to post the pateint's link, but the entire patient's view.
so what i did is replace:

[cred_field field='post_content' output='bootstrap' value="Re: [wpv-post-link]"]

with:

[cred_field field='post_content' output='bootstrap' value="[wpv-view name='patient-in-thread']"]

- which is a view i created equal to the single patient template.
it works - but now for some reason i get an unneeded "] sign just before the button (see attachment). is there anything i can do to place the view there properly?

#1132620

Ok - so - I understood it was the codes generated by the view i tried to insert which were giving the trouble (because of all the quote marks in them i guess).
So what I did is just insert the actual HTML of the view (including shortcodes) inside the "value" field, like this:

[credform]
    [cred_field field="form_messages" class="alert alert-warning"]
    <div style="display:none;">    
        [cred_field field="post_title" class="form-control" output="bootstrap" value="Re: [wpv-post-title]"]
        [cred_field field="post_content" output="bootstrap" value="
      <h1 class='info-title'>Patient Information:</h1>
<h2 style='text-align: center; font-weight: 700;'>[types field='patient-name'][/types]</h2>
<div class='info-box'>
  <table class='info-table'>
    <tr>
      <td class='info-p'>Date of Birth:</td>
      <td class='info-p'>[types field='date-of-birth' style='text' format='d/m/y'][/types]</td>
    </tr>
      <tr>
        <td class='info-p'>MR #:</td>
         <td class='info-p'>[types field='mr'][/types]</td>
    </tr>
        <tr>
          <td class='info-p'>HX:</td>
           <td class='info-p'>[types field='hx'][/types]</td>
    </tr>
  </table>
</div>
<h3>Right OD:</h3>
<div class='info-images'>
  [wpv-for-each field='wpcf-right-od-images']
<a href='[types field='right-od-images' size='full' url='true'][/types]' rel='lightbox'>[types field='right-od-images' title='%%TITLE%%' alt='%%ALT%%' align='center' size='full' separator=''][/types]</a>
  [/wpv-for-each]
</div>
<h3>Left OS:</h3>
<div class='info-images'>
  [wpv-for-each field='wpcf-left-os-images']
<a href='[types field='left-os-images' size='full' url='true'][/types]' rel='lightbox'>[types field='left-os-images' title='%%TITLE%%' alt='%%ALT%%' size='full' separator=''][/types]</a>
  [/wpv-for-each]
</div>
<h3>Notes:</h3>
[wpv-post-body view_template='None']
      "]
        [cred_generic_field type='hidden' field='patient']
{
"default":"[wpv-post-id]"
}
[/cred_generic_field]
    </div>
    [cred_field field="form_submit" output="bootstrap" value="Create Thread" class="btn btn-primary btn-lg"]
[/credform]

Seems ok - but:

1. it forwards me to the new thread with the code in it and once i submit, the thread is created. before it took me the the new thread and after i submitted i was able to edit the content and add remarks.
2. it works only when i'm admin. when i'm logged in as doctor, the thread body comes empty.
3. i tried to return to the older version of the code:

[cred_field field='post_content' output='bootstrap' value="Re: [wpv-post-link]"]

but the results were the same - and i didn't change anything else...

#1132772

Complex HTML in the value of a field isn't well supported. If you want to apply complex post_content, I recommend doing it on the backend with code instead. We offer the cred_before_save_data API for this purpose. Since you have access to the patient ID from the generic field, you can use that to get any custom field values and build a complex HTML string. Then overwrite the existing post_content with that HTML. Here's a basic example:

add_action('cred_before_save_data', 'cred_generate_new_thread_content',10,1);
function cred_generate_new_thread_content($form_data)
{
    // if a specific form
    if ($form_data['id']==12345)
    {
        if (isset($_POST['patient']))
        {
            // build the post_content using the patient's information
            $patient = $_POST['patient'];
            $dob = types_render_field("date-of-birth", array("style" => "text", "id" => $patient) );
            $body = "<h2>Patient: " . get_the_title( $patient ) . "</h2>";
            $body .= "<div>Patient's date of birth: " . $dob . "</div>";
            $_POST['post_content'] = $body;
        }
    }
}

Documentation for cred_before_save_data:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_before_save_data

Documentation for types_render_field for all field types:
https://toolset.com/documentation/customizing-sites-using-php/functions/

#1132847

thx!
but still, even if i just go back to the original code, it doesn't work the way it's supposed to: it still doesn't let a doctor do it, just the admin...
any ideas?
cheers

#1132853

wait - it does! thx for all the help chris!