I have a custom taxonomy with a parent/child structure. Let's suppose for this exercise my taxonomy is called Cars and my structure is like this:-
Ford
- Ranger
- Escort
Volvo
- XC60
- V90
I want to be able to return an error on post form submission if the user has selected a parent, i.e. Ford or Volvo.
How do I do this please?
Minesh
Supporter
Languages:
English (English )
Timezone:
Asia/Kolkata (GMT+05:30)
Hello. Thank you for contacting the Toolset support.
You can use the Toolset form's hook "cred_form_validate" to validate the form.
For example:
- Please try to add the following hook to "Custom Code" section offered by Toolset:
=> https://toolset.com/documentation/programmer-reference/adding-custom-code/using-toolset-to-add-custom-code/#adding-custom-php-code-using-toolset
add_filter('cred_form_validate','func_validate_taxonomy_parent_terms',10,2);
function func_validate_taxonomy_parent_terms($field_data, $form_data){
list($fields,$errors)=$field_data;
if ($form_data['id']==99999){
$tax_slug = 'trainer-specialty'; // replace taxonomy slug
$terms = $fields[$tax_slug]['value'];
$found = get_terms( array( 'taxonomy' => $tax_slug, 'parent' => 0,'include'=>$terms));
if(count($found) > 0) {
$errors[$tax_slug]='Please select child terms only.';
}
}
return array($fields,$errors);
}
Where:
- Replace 99999 with your original form ID.
- Replace taxonomy slug where applicable.
More info:
- https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
Hi Minesh
Thank you for your response.
Your suggestion works well if the taxonomy selected is ANY parent but how do I retrieve the parent's name so that instead of returning a general 'please select child terms only' message, I could be more specific?
Using my sample taxonomy of Cars where Volvo is the parent and V90 and XC60 are models, how would I return an error message that said 'Volvo is a car manufacturer. Please select a Volvo model' if the user selected Volvo not V90 or XC60
Thank you!
Minesh
Supporter
Languages:
English (English )
Timezone:
Asia/Kolkata (GMT+05:30)
To display the names of selected terms, You can use the following code:
add_filter('cred_form_validate','func_validate_taxonomy_parent_terms',10,2);
function func_validate_taxonomy_parent_terms($field_data, $form_data){
list($fields,$errors)=$field_data;
if ($form_data['id']==99999){
$tax_slug = 'trainer-specialty'; // replace taxonomy slug
$terms = $fields[$tax_slug]['value'];
$found = get_terms( array( 'taxonomy' => $tax_slug, 'parent' => 0,'include'=>$terms));
if(count($found) > 0) {
foreach($found as $k=>$v):
$names[]= $v->name;
endforeach;
$name = join(",",$names);
$errors[$tax_slug ]="$name is a car manufacturer. Please select a $name model";
}
}
return array($fields,$errors);
}
Where:
- Replace 99999 with your original form ID.
- Replace taxonomy slug where applicable.
More info:
- https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
Excellent, Minesh thank you!