How can I validate a field in a Toolset Form, so that when for example the user would have to submit an image but doesn't, it automatically adds a "dummy" image to that field?
How can I do that?
You could simply add a default value to the Custom Field, so if it’s not edited, that value is used.
But that may look not so smooth, hence a „in the background“ action is required.
Since this is not really a validation where we throw an error but just ensuring that the field is somehow populated, we can apply a CRED cred_save_data() action.
Otherwise - if we want to throw an error, we use the cred_form_validate() hook.
This hook allows you to fire any PHP at the moment when the post is saved to the database.
This means you can check the Field in the $_POST and if empty, you can then update_post_meta() that field with anything you want.
The hooks allow you to perform your custom code a the right moment, that is all that our API does, along with providing several data sets in those hooks so you can use it in the code.
Let me give a simple example.
add_action('cred_save_data', 'my_save_data_action',10,2); function my_save_data_action($post_id, $form_data) { // if a specific form if ($form_data['id']==12) { if (!isset($_POST['my_custom_field']))//Change "my_custom_field" to your wpcf-field { // since $_POST['my_custom_field'] is not set (!isset()) update_post_meta($post_id, 'my_custom_field', 'whatever-value-you-like-or-url-to-image'); } } }
Above PHP code checks if the $_POST input (my image field) is set, and if not, it adds a value.
The entire code is based on PHP and WordPress API - but hooks into our Toolset Forms API to ensure it fires at the right moment.
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)
This topic contains 2 replies, has 2 voices.
Last updated by 6 years, 9 months ago.
Assisted by: Beda.