Skip Navigation

[Resolved] How can I conditionally make fields as required or not?

This support ticket is created 5 years, 4 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
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 11 replies, has 2 voices.

Last updated by puneetS-3 5 years, 4 months ago.

Assisted by: Luo Yang.

Author
Posts
#1340825

I have a form where I am saving the details of mother and father. I want to optimise this form so that a single parent can also use this form to add their profile.

I have a checkbox for mother and father which asks (if applicable or not) :
No I want that If someone says "Not Applicable" by checking on the checkbox, the fields for the father details go away. I am able to do it right now using "cred_show_group" but it doesn't possibly allows me to save the form, because they are still required.

All the fields are custom fields incluing the checkbox, because I want to store if checked or not for the edit form. Is there any way I can make "fields as required conditionally" ?

#1340835

Hello,

It needs custom JS codes, if you need assistance for it, please provide a test site with the same problem, also point out the problem page URL and form URL, I need to test and debug it in a live website, thanks

Private message box enabled.

#1340875

Thanks for the details, I can log into your website, will update here if there is anything found

#1340975

I have tried these in your website:
Edit the post form "Parent Onboarding form", in section "JS Editor", add below JS codes:

jQuery(document).on('cred_form_ready', function(){
	jQuery('input[name="wpcf-is-only-father"], input[name="wpcf-is-only-mother"]').change(function(){
    	if(jQuery(this).prop("checked") == true){
          jQuery(this).closest( "section" ).children(':hidden').find('input, select').attr('disabled', 'disabled');
        }
    });
});

It can disable all hidden fields, then you can click "Submit" button, but after submit the form, there still be some error messages above those required fields: there are server side validation for those required fields.

I will check it again, will update here tomorrow.

#1340999

Hey Luo,

Yes I am unable to submit the form becuase the server side validation is working on those field.

It would be amazing if this would be something which comes build in with toolset CRED form. I would be happy to raise a request for this feature.

#1341763

Thanks for the patience, I have tried the Toolset form filter hook cred_form_validate in my localhost:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

Those server side validation can not be removed with above filter hook.

So I didn't find other better workaround for this issue.

You can add the feature request here:
https://toolset.com/home/contact-us/suggest-a-new-feature-for-toolset/

Currently, you will need to edit those required fields, disable the "Required" Validation.

#1341779

In that case I would atleast like to add front end validation on the fields atleast. How can I add them, for some fields so that when the checkbox is checked those get removed and not required, if unchecked then they become required.

#1341791

You can setup JS codes to add "required" attribute into those fields, see document:
hidden link

For example:
When the checkbox is checked:
hidden link

Then add "required" attribute into those specific fields:
hidden link

#1341919
Annotation 2019-09-17 153033.png

Hey Luo, I tried applying this, but I getting this error :

An invalid form control with name='wpcf-father-first-name' is not focusable.
An invalid form control with name='wpcf-father-email' is not focusable.

Upon researching I found that this occurs because if the form group is hidden or not visible the form will not submit and as I have a multi-page form, I cannot make it visible.

This is my snippet:


 $(document).ready(function(){

  $("input[name='wpcf-father-first-name']").prop('required',true);
   $("input[name='wpcf-father-email']").prop('required',true);
   $("input[name='wpcf-father-mobile-number']").prop('required',true);
   $("input[name='wpcf-fathers-date-of-birth[display-only]']").prop('required',true);
   $("select[name='wpcf-father-education']").prop('required',true);
   $("select[name='wpcf-father-profession-sub']").prop('required',true);
   $("select[name='wpcf-annual-household-income']").prop('required',true);
  
        $('input[name="wpcf-is-only-father"]').click(function(){
            if($(this).prop("checked") == true){
                alert("Checkbox is checked.");                          
            }
            else if($(this).prop("checked") == false){
                alert("Checkbox is unchecked.");
            }
        });
    });

You were able to do that with your code, can you help me fix my code. I am unable to make this work.
Also if fixed, would it so in the main error list that gets showen saying "Your profile was not saved because of 6 problems."
Will the custom required fields add up in this after doing it?

#1342555

There is a workaround, you can try these:
1) Keep the JS codes I mentioned above:
https://toolset.com/forums/topic/how-can-i-conditionally-make-fields-as-required-or-not/#post-1340975
It will work in front-end, your user will be able submit the form.
2) use filter hook "wpcf_field" to remove the server side validation, for example:

add_filter('wpcf_field', function($field){
	$field_arr = array('my-field1', 'my-field2'); // here add more field slugs

	if(in_array($field['slug'], $field_arr) && isset($field['data']['validate']) && !isset($_POST['wpcf-' . $field['slug']])){
		unset($field['data']['validate']);
	}
	return $field;
});

Please replace "my-field1" and "my-field2" with those specific required field slugs, you can also add more field slugs into PHP array $field_arr.

If you need more assistance for it, please provide FTP access of your website

#1343643

Hey Luo,

I don't know how but everything is working now. I have added the code that you gave me and it seems to work perfectly. I guess you must have made some changes which would have made this effect. But because of this one of my custom code has stopped working. So I had a query(https://toolset.com/forums/topic/whats-the-correct-way-to-add-date-valdations-to-cred-forms/) raised with Christian. I wanted to set the limit for date of birth to be more than 21 years. And last night I was able to make that work now that is not working at all.

add_filter('cred_form_validate','dob_valdiate',10,2);

function dob_valdiate($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
	date_default_timezone_set('Asia/Kolkata');
	$timestamp = time();
	$date = date('d-m-Y', $timestamp);
	
 if ($form_data['id']==1442) {
	 
	 	
	 
 if ( (strtotime($date) - $fields['wpcf-fathers-date-of-birth']['value']['datepicker']) < 21 )
    {
    //set error message for my_field
    $errors['wpcf-fathers-date-of-birth']='Your age must be more than 21';
    }
	 
	 if ( (strtotime($date) - $fields['wpcf-mothers-date-of-birth']['value']['datepicker']) < 21 )
    {
    //set error message for my_field
    $errors['wpcf-mothers-date-of-birth']='Your age must be more than 21';
    }

	 

}
//return result
return array($fields,$errors);
}

This was my code for custom validation.

And this is your version of code that I am currently using.


add_filter('wpcf_field', function($field){
    $field_arr = array('father-first-name','father-email','father-education','father-profession-sub','annual-household-income','mother-first-name','mother-email','mother-mobile-number','mother-education','mother-profession-type',); // here add more field slugs
 
    if(in_array($field['slug'], $field_arr) && isset($field['data']['validate']) && !isset($_POST['wpcf-' . $field['slug']])){
        unset($field['data']['validate']);
    }
    return $field;
});

As you can see I have excluded date of birth from the field array. Still I can't make my custom validations to work .

#1343739

Hey, I fixed the date of birth code on my own. Thanks for the support!