Zend_Form radio element - php

Below is sample code to create a radio button element with Yes/No options in Zend_Form. Any ideas on how to set the required answer to Yes, so if No is selected, it'll fail validation? The code below will accept either Yes or No.
$question= new Zend_Form_Element_Radio('question');
$question->setRequired(true)
->setLabel('Are you sure?')
->setMultiOptions(array('Yes', 'No'));

Not sure if this is the best way, but it worked for me:
$questionValid = new Zend_Validate_InArray(array('Yes'));
$questionValid->setMessage('Yes is required!');
$question = new Zend_Form_Element_Radio('question');
$question->setRequired(true)
->setLabel('Are you sure?')
->setMultiOptions(array('Yes'=>'Yes', 'No'=>'No'))
->addValidator($questionValid);

A quicker way, though this wouldn't work for other situations:
$question = new Zend_Form_Element_Radio('question');
$question->setRequired(true)
->setLabel('Are you sure?')
->setMultiOptions(array('Yes'=>'Yes', 'No'=>'No'))
->addValidator('StringLength', false, array('min' => 3, 'messages' => "You must be sure."));
Since "no" is less than 3 characters, this will fail unless "yes" is selected. It's a little "hacky", but I like this way because it uses less code and also makes use of the built-in validators.

Related

What does isDirty() mean in Laravel?

First of all, I am not familiar with Laravel so much (or with the term "dirty" for that matter).
I stumbled upon this line of code -
if ($this->isDirty('status')) {
if (Notification::has('website-status-' . strtolower($this->status))) {
Notification::set($this->account, 'website-status-' . strtolower($this->status), $this->emailAttributes())
->email();
}
}
And I couldn't understand what that means exactly. I tried to find out on the internet but the Laravel site only says this
"Determine if a given attribute is dirty"
which doesn't really help...
When you want to know if the model has been edited since it was queried from the database, or isn't saved at all, then you use the ->isDirty() function.
The isDirty method determines if any attributes have been changed since the model was loaded. You may pass a specific attribute name to determine if a particular attribute is dirty.
$user = User::create([
'first_name' => 'Amir',
'last_name' => 'Kaftari',
'title' => 'Developer',
]);
$user->title = 'Jafar';
$user->isDirty(); // true
$user->isDirty('title'); // true
$user->isDirty('first_name'); // false
Eloquent provides the isDirty, isClean, and wasChanged methods to examine the internal state of your model and determine how its attributes have changed from when they were originally loaded.
You can find complete description and examples of these three methods here in the official document:
https://laravel.com/docs/9.x/eloquent#examining-attribute-changes
As support for the accepted answer:
$model = Model::find(1);
$model->first_column = $request->first_value;
$model->second_column = $request->second_value;
$model->third_column = $request->third_value;
if($model->isDirty()){
// the model has been edited, else codes here will not be executed
}
$model->save();

Laravel - both input values can't be no how to validate?

I'm using Laravel for a project and want to know how to validate a particular scenario I'm facing. I would like to do this with the native features of Laravel if this is possible?
I have a form which has two questions (as dropdowns), for which both the answer can either be yes or no, however it should throw a validation error if both of the dropdowns equal to no, but they can both be yes.
I've check the laravel documentation, but was unsure what rule to apply here, if there is one at all that can be used? Would I need to write my own rule in this case?
very simple:
let's say both the fields names are foo and bar respectively.
then:
// Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc
// if validation passes, add this (i.e. inside if($validator->passes()))
if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
{
$messages = new Illuminate\Support\MessageBag;
$messages->add('customError', 'both fields can not be no');
return Redirect::route('route.name')->withErrors($validator);
}
the error messge will appear while retrieving.
if you get confuse, just dump the $error var and check how to retrieve it. even if validation passes but it gets failed in the above code, it won't be any difference than what would have happened if indeed validation failed.
Obviously don't know what your form fields are called, but this should work.
This is using the sometimes() method to add a conditional query, where the field value should not be no if the corresponding field equals no.
$data = array(
'field1' => 'no',
'field2' => 'no'
);
$validator = Validator::make($data, array());
$validator->sometimes('field1', 'not_in:no', function($input) {
return $input->field2 == 'no';
});
$validator->sometimes('field2', 'not_in:no', function($input) {
return $input->field1 == 'no';
});
if ($validator->fails()) {
// will fail in this instance
// changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
}
Just to note, this will only work in Laravel 4.2+

How to Zend_Dojo_Form_Element_FilteringSelect onchange submit

Well the title pretty much says it all. I had:
$strata = new Zend_Form_Element_Select('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', 'this.form.submit()');
Then I need to use some fancy dojo form elements in other forms. So I decided to make them all look the same and did this:
$strata = new Zend_Dojo_Form_Element_FilteringSelect('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', 'this.form.submit()');
It shows up and looks fine, but the form is not submitted when I change the FilteringSelect. If I look at the HTML that is rendered, sure enough:
<select name="strata" id="strata" onChange="this.form.submit()">
I suspect that Dojo elements cannot or do not work like this. So how do I make this form submit when I change the FilteringSelect?
Here it is:
When defining the form, give it an id:
$this->setName('StrataSelect');
or
$this->setAttrib('id', 'StrataSelect');
Then the onChange event uses getElementById:
$strata = new Zend_Dojo_Form_Element_FilteringSelect('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', "document.dojo.byId('StrataSelect').submit();");
or
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', "document.getElementById('StrataSelect').submit();");
Why this now works and none of the "old school" submit() calls probably has something to do with dojo handling the onchange event. So submit or this.form are not objects, methods, etc etc etc.
I don't want to put any javascript this form depends on into the view. I want this form to be "portable". So therefore I don't want to use dojo.connect
There are probably better ways to do this. So I'll leave this unanswered for now.
Do you have parseOnLoad enabled? If you're building the form in php you can do this:
$form = new Zend_Form_Dojo();
$form->addElement(
'FilteringSelect',
'myId',
array(
'label' => 'Prerequisite:',
'autocomplete' => true,
'jsId' => 'myJsId',
),
array(), //attributes
array( //your select values
'id1' => 'name1',
'id2' => 'name2',
'id3' => 'name3',
)
);
you might need to set a few attributes on your $form.
try this:
$form->setAttribs( array('jsId'=>'MyFormName') );
Then in your onClick:
MyFormName.submit()
If your form passes validation (presuming you have some), it should submit.

To create check box in symfony using widgets and also validate it?

the code in symfony that i am using,
$this->setWidgets(array(
'mobile' =>new sfWidgetFormInput(),
'subscribetosms' =>new sfWidgetFormInputCheckbox(),
));
i want to validate the checkbox, and also code to take values from check box
to validate form fields in symfony u need to set validators like this (assuming you are in a form class):
$this->setValidators(array(
'mobile' => new sfValidatorString(array(...)),
'subscribetosms' => new sfValidatorInteger(array(...))
));
Question is, what do you want to validate? If you want some kind of value send to your php script if the checkbox is selected you need to set this value in the widget.
new sfWidgetFormInputCheckbox(array('value_attribute_value'=>'your_value' )
Now you could configure your validator to validate this value (sfValidatorString for a string, of sfValidatorInteger for an integer).
To get the value in your action after the validation:
if ($this->form->isValid()) {
$myValue = $this->form->getValue('subscribetosms');
}

Zend_Form -> Nicely change setRequired() validate message

Say I create a text element like this:
$firstName = new Zend_Form_Element_Text('firstName');
$firstName->setRequired(true);
Whats the best way to change the default error message from:
Value is empty, but a non-empty value
is required
to a custom message? I read somewhere that to replace the message, just use addValidator(..., instead (NO setRequired), like this:
$firstName = new Zend_Form_Element_Text('firstName');
$firstName->addValidator('NotEmpty', false, array('messages'=>'Cannot be empty'));
but in my testing, this doesn't work - it doesn't validate at all - it will pass with an empty text field. Using both (addValidator('NotEmp.. + setRequired(true)) at the same time doesn't work either - it double validates, giving two error messages.
Any ideas?
Thanks!
An easier way to set this "site-wide" would be to possibly do the following in a bootstrap or maybe a base zend_controller:
<?php
$translateValidators = array(
Zend_Validate_NotEmpty::IS_EMPTY => 'Value must be entered',
Zend_Validate_Regex::NOT_MATCH => 'Invalid value entered',
Zend_Validate_StringLength::TOO_SHORT => 'Value cannot be less than %min% characters',
Zend_Validate_StringLength::TOO_LONG => 'Value cannot be longer than %max% characters',
Zend_Validate_EmailAddress::INVALID => 'Invalid e-mail address'
);
$translator = new Zend_Translate('array', $translateValidators);
Zend_Validate_Abstract::setDefaultTranslator($translator);
?>
Give this a shot:
$firstName = new Zend_Form_Element_Text('firstName');
$firstName->setLabel('First Name')
->setRequired(true)
->addValidator('NotEmpty', true)
->addErrorMessage('Value is empty, but a non-empty value is required.');
The key is that "true" on the validator if you set that to true, it'll kill the other validations after it. If you add more than one validation method, but set that to false, it will validate all methods.
Zend_Form sets the required validation error as 'isEmpty', so you can override its message using setErrorMessages(). For example:
//Your Required Element
$element->setRequired(true)->setErrorMessages(array(
'isEmpty'=>'Please fill this field'
));
It worked for me, using ZF 1.11
Try
->addValidator('Digits', false);
or
->addValidator('Digits');
You assume that to check Digits it has to have a string length anyway.
Also, I like to do some custom error messages like this:
$firstName->getValidator('NotEmpty')->setMessage('Please enter your first name');
This allows you to "get" the validator and then "set" properties of it.
Try the following.
$subjectElement->setRequired(true)->addErrorMessage('Please enter a subject for your message');
This worked form me.
But try this:
$firstName->setRequired(true)
->addValidator('NotEmpty', false, array('messages' => 'bar'))
->addValidator('Alpha', false, array('messages'=>'Must contain only letters'));
If left empty and submitted, itll give two messages bar & '' is an empty string. Its that second message thats coming from setRequired(true) thats the problem
if you put:
$element->setRequired(false);
the validations don't work at all, you have to define:
$element->setAllowEmpty(false);
in order to get the correct behavior of the validations.
Try this..
$ausPostcode = new Zend_Form_Element_Text('aus_postcode'); $ausPostcode->setLabel('Australian Postcode')
->setRequired(true)
->addValidator('StringLength', false, array(4, 4))
->addValidator(new Zend_Validate_Digits(), false)
->getValidator('digits')->setMessage('Postcode can only contain digits');
This sets the custom error message only for the Digits validator.
One small issue. This code:
$zipCode->setLabel('Postal Code')
->addValidator('StringLength', true, array( 5, 5 ) )
->addErrorMessage('More than 5')
->addValidator('Digits', true)
->addErrorMessage('Not a digit');
Will generate both error messages if either validation fails. Isn't is supposed to stop after the first fails?
use a zend translator with zend_validate.php from
ZendFramework-1.11.3\resources\languages\en\Zend_Validate.php and then modify this file how you need
and then modify it accordingly to your needs

Categories