form->isValid() empty my model - php

I have a big model with around 13 attributs.
I want to update a few value of them using a form.
But actually using $form->isValid() empty my model and set only value which are feeded in my form or have an inputFilter setted.
Are they a way to avoid it ?

Checkout Validation Groups
http://framework.zend.com/manual/2.0/en/modules/zend.form.quick-start.html#validation-groups
You can partially validate your model, and only get back the values in the Validation Group.

I think you have set filter for all the fields in form ,
check what you are getting with this .
$unfiltered = $form->getUnfilteredValues();
print_r($unfiltered);

Related

Accessing all form fields during validation of Symfony2 form

Consider the following form:
$builder->add('home_team', 'choice', [$options])
->add('away_team', 'choice', [$more_options])
->add('timestamp', 'datetime_picker', [$usual_stuff]);
I wish to validate these fields, and see that no other Match exists with the same home_team, away_team and timestamp.
I have made a UniqueMatchValidator with a validate() function but I need some help here.
I'm going to do a database call with the values from the form to check for duplicates, but in order to do that, I need to know the values of all three fields, while applying the Validator to only one of the fields.
Question
How can I access the values of all the form fields from inside the Validator?
As mentioned above it's better to use FormTypes and data classes.
However even with arrays you can use form validation and get all fields using event listener:
$builder
->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$event->getData(); //you will get array with field values
$event->getForm()->addError(...); // if something happens error can be addded
})
Actually form validator uses this event too.
Your form should basically contains an entity. You need to do your validations using callbacks in the entity. Using callback, you can access all the properties of that entity.
This link will surely help you to understand it better:
Symfony2 Form Validation Callback

Testing for POST in Yii 2.0

In my controllers that Gii creates it is common to see the following:
if($model->load(Yii::$app->request->post()) && $model->save()){
//.....do something such as redirect after save....//
}else
{
//.....render the form in initial state.....//
}
This works to test whether a POST is sent from my form && the model that I am specifying has saved the posted information (as I understand it).
I've done this similarly in controllers that I have created myself but in some situations this conditional gets bypassed because one or both of these conditions is failing and the form simply gets rendered in the initial state after I have submitted the form and I can see the POST going over the network.
Can someone explain why this conditional would fail? I believe the problem is with the 'Yii::$app->request->post()' because I have removed the '$model->save()' piece to test and it still bypasses the conditional.
Example code where it fails in my controller:
public function actionFreqopts()
{
$join = new FreqSubtypeJoin();
$options = new Frequency();
$model = new CreateCrystal();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->insertFreqopts();
return $this->redirect(['fieldmap', 'id' => $join->id]);
} else {
return $this->render('freqopts', ['join' => $join, 'options' => $options]);
}
}
My initial thought was that I'm not specifying the correct "$model" in that I'm trying to save the posted data to FreqSubtypeJoin() in this case and the $model is CreateCrystal(); however, even when I change the model in this conditional it still fails. It would be helpful if someone could briefly explain what the method 'load' is actually doing in layman's terms if possible.
The load() method of Model class is basically populating the model with data from the user, e.g. a post query.
To do this it firstly loads your array of data in a form that matches how Yii stores your record. It assumes that the data you are trying to load is in the form
_POST['Model name']['attribute name']
This is the first thing to check, and, as long as your _POST data is actually getting to the controller, is often where load() fails, especially if you've set your own field names in the form. This is why if you change the model, the model will not load.
It then check to see what attributes can be massively assigned. This just means whether the attributes can be assigned en-mass, like in the $model->load() way, or whether they have to be set one at a time, like in
$model->title = "Some title";
To decide whether or not an attribute can be massively assigned, Yii looks at your validation rules and your scenarios. It doesn't validate them yet, but if there is a validation rule present for that attribute, in that scenario, then it assumes it can be massively assigned.
So, the next things to check is scenarios. If you've not set any, or haven't used them, then there should be no problem here. Yii will use the default scenario which contains all the attributes that you have validation rules for. If you have used scenarios, then Yii will only allow you to load the attributes that you have declared in your scenario.
The next thing to check is your validation rules. Yii will only allow you to massively assign attributes that have associated rules.
These last two will not usually cause load() to fail, you will just get an incomplete model, so if your model is not loading then I'd suggest looking at the way the data is being submitted from the form and check the array of _POST data being sent. Make sure it has the form I suggested above.
I hope this helps!

CakePHP 1.3 - Validate input is numeric within view/controller?

I need to validate that a form input is numeric in CakePHP 1.3. However, the input is not a property of the model, so I don't think I should try to set the validation for it in the model. Instead, some calculations are done on that input and the results are used in the resulting model object. How can I validate this in the view/controller? That is, check that what the user input was numeric and show a validation error message if not before passing it through the calculations? Thanks!
There's nothing wrong with defining model validation rules for non-existing / calculated fields, but you can also use the Validation class which might be cleaner. See 1 and 2.
If you use jquery at least you don't have to do a full page reload to check. Especially if it's only for one value. Just another option, see if it helps!
if($('#Field').val() != "")
{
if(!($.isNumeric($('#Field').val())) {
alert('value must be numeric');
}
}

How do you restore the values of the form in case if validation failed (in Kohana 3)

There is a sample in the bottom of the official documentation http://kohanaframework.org/3.2/guide/kohana/security/validation
But obviously it wont work at the request as long as $post['username'] in View is used but the $post array is empty on first request.
So how do you restore the values in this case? Any general solution?
PS: yes, I do understand I could do isset($post['username']) ? $post['username'] : ''; but it is just annoying
I use the model to display the data in the form. That way the initial form value is the initial value in the model.
I then update the model data with POST data in the controller, if there are validation errors, the model data will contain the POST data. This means I don't have to put any conditional logic in the view, and I just do: Form::input('name', $model->name)
Here's a more detailed explanation of this approach: Kohana ORM and Validation, having problems
I use Arr::get function:
echo Form::input('name', Arr::get($post, 'name'))
I was just looking at the old documentation on Building and Validating a Form.
You can see from the sample code that first you need to initialize an array with the form field names as the key and set the value to an empty string. And if there's an error, fill in the values of each element. In the views, you can simply call Form::input() normally without any if statement or some sort.
I guess Kohana has already been built this way from the start. And it doesn't seem to change. You'll probably just need to do the same thing.

update/validate embedded forms before saving in symfony

I would like to validate an embedded form field before it gets saved in the database. Currently it will save an empty value into the database if the form field is empty. I'm allowing empty fields, but I want nothing inserted if the form field is empty.
Also quick question, how to alter field values before validating/saving an embedded form field?
$this->form->getObject works in the action, but $this->embeddedForm->getObject says object not found
I found a really easy solution. The solution is to override your Form's model class save() method manually.
class SomeUserClass extends myUser {
public function save(Doctrine_Connection $conn = null)
{
$this->setFirstName(trim($this->getFirstName()));
if($this->getFirstName())
{
return parent::save();
}else
{
return null;
}
}
}
In this example, I'm checking if the firstname field is blank. If its not, then save the form. If its empty, then we don't call save on the form.
I haven't been able to get the validators to work properly, and this is an equally clean solution.
Symfony gives you a bunch of hooks into the form/object saving process.
You can overwrite the blank values with null pre/post validation using by overriding the the doSave() or processValues() functions of the form.
You can read more about it here: http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms#chapter_06_saving_object_forms

Categories