Custom Zend Error message for checkboxes - zend-framework

I have a form in a Zend-based site which has a required "Terms and Conditions" checkbox.
I have set a custom message which says "you must agree with terms and conditions".
however, because the checkbox is "presence='required'", it returns
Field 'terms' is required by rule 'terms', but the field is missing
which is this constant defined in the Zend framework:
self::MISSING_MESSAGE => "Field '%field%' is required by rule '%rule%', but the field is missing",
I could edit this constant, but this would change the error reporting for all required checkboxes.
How can I affect the error reporting for this specific case?

If you are using the Zend_Form_Element_Checkbox you can customize the error messages on the Zend_Validate validators.
$form->addElement('checkbox', 'terms', array(
'label'=>'Terms and Services',
'uncheckedValue'=> '',
'checkedValue' => 'I Agree',
'validators' => array(
// array($validator, $breakOnChainFailure, $options)
array('notEmpty', true, array(
'messages' => array(
'isEmpty'=>'You must agree to the terms'
)
))
),
'required'=>true,
);
You want to make sure the unchecked value is "blank" and that the field is "required"

You can override the default message like this:
$options = array(
'missingMessage' => "Field '%field%' is required by rule '%rule%', dawg!"
);
And then:
$input = new Zend_Filter_Input($filters, $validators, $myData);
Or
$input = new Zend_Filter_Input($filters, $validators, $myData);
$input->setOptions($options);
...and finally:
if ($input->hasInvalid() || $input->hasMissing()) {
$messages = $input->getMessages();
}
It's mentioned on the Zend_Filter_Input manual page.

Following #gnarf answer, for those of you who may set Form Fields in a slightly different way (like me), you could also do the following:
$agree_tc_and_privacy = new Zend_Form_Element_Checkbox('agree_tc_and_privacy');
$agree_tc_and_privacy
->setLabel("My T&Cs Agreement text ...")
->addValidator('NotEmpty', false, array('messages' => 'You must and agree...'))
->setRequired(true)
->setOptions(
array(
'uncheckedValue'=> '', //important as explained by gnarf above
'checkedValue' => '1',
)
);
$this->addElement($agree_tc_and_privacy);

Related

Symfony form ChoiceType is ignoring the required attribute

On a form I add a field like this
$builder->add('cse',
ChoiceType::class,
array(
'label' => '',
'required' => true,
'translation_domain' => 'messages',
'choices' => array(
'I agree' => true
),
'expanded' => true,
'multiple' => true,
'data' => null,
'attr' => array( 'class' => 'form_f' ),
)
)
While all other fields added to the form that have 'required' set to 'true' will prevent the form from being send the required attribute for this field is ignored (the form is sent anyways no matter if checked or not).
Do I have to handle this with Assert statements? If yes - still: why is required not working here?
Yes, use Assert.
Because multiple=true print checkbox. Html validator can test radio, but no checkbox.
Always use Assert for all forms, because html validator isn't safe :)
In my case, I cannot use the asserts, and since was not possible to handle this in user side (unless you use javascript), I made the checks in server side, in the FormEvents::PRE_SUBMIT hook:
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
if ($field->required && !isset($event->getData()[$field->name])) {
$event->getForm()->addError(new FormError('One option must be chosen on "' . $field->label . '"'));
}
});

Symfony2: Create form binded to an entity with a field which is not a property

The following (simple) question from me:
$user = new User();
$user->setEventid(2);
$user->setT(new \DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$form = $this->createFormBuilder($user)
->add('email', 'email')
->add('terms', 'checkbox', array(
'label' => 'Read terms?',
'required' => true))
->getForm();
This is my code. Email is property of the user, terms not.
I want them users to save their email and check the terms-checkbox but i just need to save the email, not if they check the box - if they don't they cant submit the form.
You know what i mean? I'm shure its pretty simple to achieve this ;)
Second Question: How can i give the rendered from-tag an id-attribute for further handeling in jquery?
To add a field that doesn't exist in the entity to a form, use this:
->add('terms', 'checkbox', array(
'label' => 'Read terms?',
'required' => true,
'mapped' => false, // this works since Symfony 2.1
'property_path' => false, // this works since Symfony 2.0
))
Symfony generates an ID for each form element; just open the rendered page source and see the ID of the element you need.
If you don't have a 'terms' field in your Entity, it won't be save.
For your second question, it's very simple to set an id to a form in twig, make simply :
{{ form_label(form.name, 'Your Name', { 'attr': {'id': 'foo'} }) }}

Duplicate Validation on Combined Fields in zend form

Hi there I have a table in which combination of three fields is unique. I want to put the check of duplication on this combination. Table looks like
I know how to validate single field, But how to validate the combination is not know. To validate one field I use the following function
public function isValid($data) {
// Options for name field validation
$options = array(
'adapter' => Zend_Db_Table::getDefaultAdapter(),
'table' => 'currencies',
'field' => 'name',
'message'=> ('this currency name already exists in our DB'),
);
// Exclude if a id is given (edit action)
if (isset($data['id'])) {
$options['exclude'] = array('field' => 'id', 'value' => $data['id']);
}
// Validate that name is not already in use
$this->getElement('name')
->addValidator('Db_NoRecordExists', false, $options
);
return parent::isValid($data);
}
Will any body guide me how can I validate duplication on combined fields?
There is no ready to use validator for this, as far as I know. You have either to write your own, or do a check with SQL-query with three conditions (one for each field).
you have to Apply a validation on name element of zend form.
Here is code for add validation on name field.
$name->addValidator(
'Db_NoRecordExists',
true,
array(
'table' => 'currencies',
'field' => 'name',
'messages' => array( "recordFound" => "This Currency Name already exists in our DB") ,
)
);
And you must set required true.

Zend: Form validation: value was not found in the haystack error

I have a form with 2 selects. Based on the value of the first select, it updates the values of the second select using AJAX. Doing this makes the form not being valid. So, I made the next change:
$form=$this->getAddTaskForm(); //the form
if(!$form->isValid($_POST)) {
$values=$form->getValues();
//get the options and put them in $options
$assignMilestone=$form->getElement('assignedMilestone');
$assignMilestone->addMultiOptions($options);
}
if($form->isValid($_POST)) {
//save in the database
}else {
//redisplay the form
}
Basically, I check if it is valid and it isn't if the user changed the value of the first select. I get the options that populated the second select and populate the form with them. Then I try to validate it again. However this doesn't work. Anybody can explain why? The same "value was not found in the haystack" is present.
You could try to deactivate the validator:
in your Form.php
$field = $this->createElement('select', 'fieldname');
$field->setLabel('Second SELECT');
$field->setRegisterInArrayValidator(false);
$this->addElement($field);
The third line will deactivate the validator and it should work.
You can also disable the InArray validator using 'disable_inarray_validator' => true:
For example:
$this->add( array(
'name' => 'progressStatus',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'disable_inarray_validator' => true,
),
));
Additionaly you should add you own InArray Validator in order to protect your db etc.
In Zend Framework 1 it looks like this:
$this->addElement('select', $name, array(
'required' => true,
'label' => 'Choose sth:',
'filters' => array('StringTrim', 'StripTags'),
'multiOptions' => $nestedArrayOptions,
'validators' => array(
array(
'InArray', true, array(
'haystack' => $flatArrayOptionsKeys,
'messages' => array(
Zend_Validate_InArray::NOT_IN_ARRAY => "Value not found"
)
)
)
)
));
Where $nestedArrayOptions is you multiOptions and $flatArrayOptionsKeys contains you all keys.
You may also add options to select element before checking for the form validation. This way you are insured the select value is in range.

Zend Framework Default Error

How can i get rid of Zend default error not to show "Value is required and can't be empty"
Thanks
I'm using this method:
$this->addElement(
'text',
'testname',
array(
'label' => 'User Name',
'required' => true,
'filters' => array(
'StringTrim'
)
)
);
If you need to change the actual message text then use something like this:
$field = new Zend_Form_Element_Text('field');
$field ->setRequired(TRUE)
->addValidator(
'NotEmpty', //validator name
FALSE, //do not break on failure
array(messages' => array(
'isEmpty' => 'INSERT CUSTOM MESSAGE HERE'
)
)
)
Here you change the 'isEmpty' message of the NotEmpty validator.
Or if you defined the element differently.
$element = $this->getElement('text');
$element->addValidator('NotEmpty', //validator name
FALSE, //do not break on failure
array(messages' => array(
'isEmpty' => 'INSERT CUSTOM MESSAGE HERE'
)
)
)
In Zend_Form this is the default error message of the default validator 'Empty'.
To remove this validator, on the element add the removeValidator() function with 'empty' as the parameter:
$element->removeValidator('Empty');
This is assuming you have made a form in Zend_Form, that you have POSTed an empty value and are trying to validate it?
Going forward, please provide more information.