你好
請問我如何把自定義欄位設定前置表單為必填,但後端為非必填?
謝謝您
Hi, I see you refer to some issue related to Custom Fields added to a form, but the results are unexpected, however, I do not understand more unfortunately 🙂
Luo, our Supporter in charge for the Chinese Forum, will be back next week.
If you have time to wait until then, I will assign this Thread to him.
If not, can you please reformulate the Question in English so I could help?
Thanks!
Hi Beda,
How can I set the custom field setting pre-form as required, but the backend is not required?
Thank you.
That could be done only on the Form itself.
This means, whatever field you use (A Post Field or a Generic Form Field) would need to be required on the Form only.
This is possible out of the box with Generic Fields (but they will not be saved automatically to the database without custom code).
The other possible approach is to create a Custom Field that is not required in Toolset > Post Fields
Include this field in the Form.
Now either validate this Field with the Forms API:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
add_filter('cred_form_validate','my_validation',10,2);
function my_validation($error_fields, $form_data)
{
//field data are field values and errors
list($fields,$errors)=$error_fields;
//uncomment this if you want to print the field values
//print_r($fields);
//validate if specific form
if ($form_data['id']==12)//Change forms ID
{
//check my_field value
if ($fields['wpcf-my_field']['value']=='')//my_field is your custom field slug, if it's empty string, or could be empty()
{
//set error message for my_field
$errors['wpcf-my_field']='this field is required';
}
}
//return result
return array($fields,$errors);
}
This would work in PHP
Or, you can wrap the Forms submit button in a Form conditionally that checks if your field is empty or not.
If it's empty it shows a message instead of the submit button:
"Fill in fields before submit":
https://toolset.com/documentation/user-guides/conditional-display-for-form-inputs/
[cred_show_group if="($(your_field) ne '' )" mode='fade-slide']
[cred_field field='form_submit' value='Submit' urlparam='' class='btn btn-primary btn-lg' output='bootstrap']
[/cred_show_group]
[cred_show_group if="($(your_field) eq '' )" mode='fade-slide']
Fill in fields before submit
[/cred_show_group]
This works on the front end and does not require reloading of the page (you do not submit the form until its complete)