Startseite › Toolset Professional Support › [Gelöst] Validate Birthdate / Calculate Age / Store to Database / Display in Form Notif.
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 |
---|---|---|---|---|---|---|
- | - | 14:00 – 20:00 | 14:00 – 20:00 | 14:00 – 20:00 | 14:00 – 20:00 | 14:00 – 20:00 |
- | - | - | - | - | - | - |
Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)
Dieses Thema enthält 12 Antworten, hat 2 Stimmen.
Zuletzt aktualisiert von ThorstenS967 vor 4 Jahren, 8 Monaten.
Assistiert von: Beda.
Hi,
I'am referencing to a topic, opened by me some time ago: https://toolset.com/forums/topic/regex-and-calculating-age/
In the meantime I developed the code in PHP for calculating the age:
$veranstaltungsDatum = DateTime::createFromFormat("d.m.Y", "24.05.2020"); $geburtstag = "25.05.1979"; $dt = DateTime::createFromFormat("d.m.Y", $geburtstag); if ($dt === false || array_sum($dt::getLastErrors())) { echo "Geben Sie ein korrektes Datum im Format TT.MM.JJJJ an (z.B. 15.12.2009)!"; return false; } else { echo "Richtiges Datum<br>"; $geburtsDatum = new DateTime($geburtstag); $age = $geburtsDatum->diff($veranstaltungsDatum)->y; echo $age; return $age; }
Now I'am trying to put this code into toolset with some filters/hooks, which Waqar gave me in the topic described above. I done this so far for the validation:
add_filter('cred_form_validate','birthdate_validation',10,2); function birthdate_validation($error_fields, $form_data) { $veranstaltungsBeginn = $_POST['veranstaltungsBeginn']; $geburtstag = $fields['wpfc-geburtstag']['value']; $veranstaltungsDatum = DateTime::createFromFormat("d.m.Y", $veranstaltungsBeginn); $dt = DateTime::createFromFormat("d.m.Y", $geburtstag); list($fields,$errors)=$error_fields; if ($form_data['id']==1297) { if ($dt === false || array_sum($dt::getLastErrors())) { $errors['wpfc-geburtstag']='Geben Sie ein korrektes Datum im Format TT.MM.JJJJ an (z.B. 15.12.2009)!'; } if (empty($fields['wpfc-geburtstag']['value'])) { $errors['wpfc-geburtstag']='Das Feld darf nicht leer sein!'; } return array($fields,$errors); }
In the variable "$veranstaltungsBeginn" I save value from a custom field "Veranstaltungsbeginn" (event beginning), which the client sets in the backend. That is displayed by a view. Now to have this field in in the form, I use the following right at the beginning of the cred form:
<input type="hidden" id="veranstaltungsBeginn" name="veranstaltungsBeginn" value='[wpcf-veranstaltungs-anfang]'>
Is this the correct way to get the value of the field "Veranstaltungsbeginn"?
I hope, that the vaidation is function I wrote is correct. As you can see in the first code at the top, I want to calculate the age from the person. Right now I don't know, how to save the birthdate and the calculated age of the person. I don't know, which hook I need for this. I also don't know, how to display the calculated age in the form notification right after send the form data.
Thanks
Thorsten
We can be of limited assistance with custom code only.
https://toolset.com/toolset-support-policy/
However, let me see if I can help:
1. Is this the correct way to get the value of the field "Veranstaltungsbeginn"?
If the field is an Input Field in a Form, you can always get its value using $_POST
This is the theory behind, based on a generic HTML Form:
<form name="form" action="" method="get"> <!-- THIS IS OUR INPUT --> <input type="text" name="subject" id="subject" value="Car Loan"> </form>
We can now get that value of the input "subject" with:
$_GET['subject']
So yes, this will work in a cred_save or other Forms API that acts on the form when you submit it - as long that field has a value, of course
See also the "generic tips" I added at the bottom of my reply for more help.
2. As you can see in the first code at the top, I want to calculate the age from the person
About calculation or else, you should refer to the PHP Documentation, as that task is merely related on how you manipulate your data and is not directly related to Toolset
3. Right now I don't know, how to save the birthdate and the calculated age of the person
In whichever $variable you will have your (calculated) result you want to store, you need to use that variable in a update_post_metat() for example, if you want to update the data to the posts meta, or wp_update_post(), if you want to update some post data with it.
For example, you want to put your calculated value in a single line field of the post, then you would use update_post_meta() like it is described here:
https://developer.wordpress.org/reference/functions/update_post_meta/
Note that with Toolset Fields you will need to consider the wpcf- prefix that Types Custom Fields have in the slug, additional to the slug you see in the GUIs.
Then you can use update_post_meta on your form, best with cred_save_data() actually, as you want to save data:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
4. I also don't know, how to display the calculated age in the form notification right after send the form data.
If you save the data in a Custom Field you could display it with a ShortCode, possibly referencing the post just created in the "item" shortcode attribute for fields, so you can pull data from the just created Post.
When you use Success Messages in Toolset Forms, that adds some URL parameters when the message is displaying, which you can use to populate that "item" attribute with the right post id.
Use the "_target" URL parameter like so in the ShortCode that displays your field:
[wpv-post-title item="[wpv-search-term param='_target']"]
(Note, I display the just created post Title, you can do this however with any Field or other shortcode)
You justs use the wpv-search-term shortcode to get the ID from the _target URL parameter which is the post just created.
That is how you can display this new data already in the success message.
Generic Tips
1. Activate WP Debug when you custom code, and "look" what is in your $variables using
error_log(print_r($your_variable, true));
This will dump everything what is the $your_variable to a error log file in your install
2. Always keep error logging and variable logging on while coding, remove it when it's finalized
I hope this helps!
Hi Beda,
thanks for your hints, which where very helpful.
The validation of the birthdate works fine. 🙂
Regarding the calculation of the age: The client enters a date in a custom field (types field) in the backend, which is being displayed in the corresponding event at the frontend. How can I get/retrieve this value from this custom field and save it in a variable for my calculation? The types field has the slug 'veranstaltungs-anfang'.
You can get the value with get_post_meta() using a meta key that has a prefix wpcf-
So for example
$var = get_post_meta( $post_id, 'wpcf-veranstaltungs-anfang' );
Since you do this in a Form Hook after submit you can use $post_id for the Post ID as that's delivered by the Toolset API already.
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
On validate moment the post doesn't yet exist so you can't retrieve any data from it unless it's an edit form
In that case, you can use maybe the container_id (the post where the form is shown) or directly pull from $_POST (it entirely depends on where and when you want to use that data)
$_POST is explained here versteckter Link
Let me know if this helps?
Thanks! One last thing left for me: I want to display the calculated age into the notification mail, that is sent to the customers after the form was sent. Here is the documentation I found: https://toolset.com/documentation/user-guides/front-end-forms/how-to-use-custom-placeholders-in-cred-notifications/
As fas as I understand from this documentation, I have to take the "cred_body_notification_codes" hook fot this. Also I have to create a generic field in the form. But the following code is unclear for me from this documentation:
[cred_generic_field field='producttitle' type='hidden' class='' urlparam=''] { "required":0, "validate_format":0, "default":"[wpv-post-title]" } [/cred_generic_field]
The part with "required", "validate_format" and "default" (especially "default") is unclear. What do I have to use for this default? I calculate the age, as you also wrote, in the "cred_save_data" hook. How do I display the age in the notification mail?
Why don't you save the calculated age to a post field or user field (depending on what you edit)?
You can update the field for each time it's calculated for the same object or create a new if the object hasn't yet any calculated age.
So, in your system, you'd not only have a veranstaltungs-anfang field (which is a date in the past), which you get with get_post_meta (note here you will receive a Timestamp, which is a number, I forgot to mentions this earlier), but you also would add a Field "age".
That field gets populated in the same code with update_post_meta() which functions in a similar way as the get_post_meta but it updates it:
https://developer.wordpress.org/reference/functions/update_post_meta/
You would obviously update that field (it can be a simple line field) with a numeric value (age) which the calculated value in your code.
So you would use something like this:
$calculated_age = //Magic that calculates the age since... update_post_meta($post_id,'wpcf-age', $calculated_age);
That - since it's now a field - can be added easily to the Forms notification.
Referring to your last question in regard to Generic Fields, let me explain below:
"required":0, // this can be 0 or 1, it means whether the field input will b required or not.
"validate_format":0, // this can be 0 or 1, it means whether to validate or not the input (number, string, date)
"default":"[wpv-post-title]" // this can be any string or shortcode expanding to a string, it's a default value meaning what will be set as value if no value is provided.
However I don't suggest using this for the goal you have, rather use meta because, thinking ahead, having the age saved in a field also allows you all sorts of Queries in Views with that field (you might want to sort by age, or query by age, without complex data queries, for example)
With above-described approach you get a clean form and database interaction, additionally, all data is stored safely, can be reused, so you don't need to repeat this information, and is easily usable in Forms Notifications as well
Thanks, that is very clear described.
The problem is, that the variable, in which I save the value of the 'wpcf-veranstaltungs-anfang' (with get_post_meta function) is empty.
$veranstaltungsBeginn = get_post_meta($post_id, 'wpcf-veranstaltungs-anfang', true);
I don't know, why the value is empty. I thnik, the problem is, that there are 2 custom field groups. One group contains the custom fields for the event itself (for example the beginning of the event -> 'veranstaltungs-anfang'), which are filled out by the team staff of the the website (my client) and one group with the fields for the cred form, which will be filled out by the customers who book the event. In the former solution it was a datepicker and some custom jquery code to calculate the age, for which Nigel did some custom code. He used the following field in the cred form to retrieve the data from the field 'veranstaltungs-anfang':
<p id="veranstaltungs-beginn" class="hidden">[types field='veranstaltungs-anfang' output='raw'][/types]</p>
Than he gets the value of the field with the jQuery code:
var eventStart = jQuery(eventSelector).text();
Could that be the problem, that the beginning of the event date custom field is not "reachable" in the cred_save_data hook in the get_post_meta() function?
When cred_save_data is fired all post meta is available even if completed only on that form (not existing previously)
This means your field is indeed empty or the slug is wrong or the Post ID used is wrong.
Can you access other post meta of the edited/added post?
Can you see the Post ID?
(You can use error_log(print_r($post_id, true)); )
This will tell more about why the code returns empty.
The field 'veranstaltungs-anfang' seems indeed to be empty for some reason.
I successfully received the $post_id and a test value of the first name field of the cred form. The field slug 'veranstaltungs-anfang' is definately correct, I triple checked.
If it's empty, the post has no such value or field.
You need to check that post if it has such field and value.
This is not a toolset issue, it would happen as well with other custom fields, let's say manually registered ones if it's empty, nothing can be "get_" from the database.
Maybe you can try a later hook (like https://toolset.com/documentation/programmer-reference/cred-api/#cred_submit_complete) or a later priority (30 or 40 instead of 10) in the hook?
I've tried both of your suggestions (increasing the priority to 40 as well as using the cred_submit_complete hook) but unfortunately the value of the "veranstaltungs-anfang" field is still empty. Is there another way to get that value?
Please verify the field exist and has a value, there is no other method in WordPress API to get fields data.
If the field exists and has value it will work just like it works for other fields which you confirmed
I suspect either the form doesn't edit the post with field or the field isn't stored with that slug for that post.
The Custom fields were indeed empty. So I tried some hours another solution and got it finally working with this code:
add_action('cred_save_data', 'age_calculation',10,2); function age_calculation($post_id, $form_data) { if ($form_data['id']==1297) { $veranstaltungsBeginn = $_POST['wpcf-alter-neu']; $veranstaltungsDatum = DateTime::createFromFormat("d.m.Y", $veranstaltungsBeginn); $geburtstag = $_POST['wpcf-geburtstag']; $geburtsDatum = new DateTime($geburtstag); $age = $geburtsDatum->diff($veranstaltungsDatum)->y; update_post_meta($post_id,'wpcf-alter-berechnet', $age); } }
I also had to set the value of the "veranstaltungs-beginn" date into a cred field in order to receive the value, because as you know, with get_post_meta(...) it was not possivle to receive the value, because it was empty and also I found out, that the value was not set:
<div class="form-group"> [cred-field field="alter-neu" force_type='field' readonly="true" class='form-control hidden' output='bootstrap' value='[types field="veranstaltungs-anfang" format="d.m.Y"]'] </div>
Now it all works as expected.