symfony2: how to validate a property which is not mapped to the entity ('property_path' => false) - forms

I'm having a registration form, which contains input fields, almost every field mapped to a property of the User class. But there are some fields which are not mapped. Validation is done via annotations in the User class.
My question is: how do I validate those fields which are not mapped?

Related

Symfony: get new ID in a form

I have an object displaying within a form, a hidden field being related to its PK (field id).
When I create a new object, the field has a null value. Submitting the form, the object is inserted into the DB and it now has an ID, but the field in the page still has a null value.
If a reload the page, now the ID is indeed set in the hidden field.
In my opinion, this is due to the form processing of Symfony: when a create an object, it creates a form, with this form valid the object is saved but the form still uses the data before it was saved.
The question is: how to get the auto-incremented key in the form up-to-date? Shouldn't the form only have a reference to the object? Can't the value be updated?
make sur that you call $entityManager->flush() method after insert and that you bind your form whene you have same data in your request object
$form->submit($request->request->get($form->getName()));
You should have an Entity assigned to your Form by FormFactory. Then Symfony will fill that Entity with submitted values. What's left is only persist the Entity and flush to database.
You can find steb-by-step form submission in Symfony Cookbook

Foreign entity in form into different kind of input

I have two entities: product and category (Symfony 2.3).
I want to create a form in which an user can choose a product by first selecting the category. A user selects the category by clicking on image, then I want to set the image's value into a hidden input, but I don't see how can I change a foreign entity choice list to a hidden input (http://symfony.com/doc/current/reference/forms/types/entity.html).
How can I accomplish this? (how to change form input to hidden)
If I set cascade validation to true, will it for example check if a category really exist. (To prevent putting products with non-existing category from malicious users) ?
Part 1
To do this you need to use a data transformer to do two things:
transform an entity into an identifier that is either a string or integer so a form can render it as a hidden field.
transform the string or integer identifier into the entity when the form is submitted so that the parent entity can be saved with the correct relationship
The symfony docs I linked to above (here too) actually walk though an entire example of using a data transformer with a form.
As a shameless plug (because I believe it is helpful) I have written a little tutorial on using a data transformer for a hidden field with an entity id: http://lrotherfield.com/blog/symfony2-forms-entity-as-hidden-field/
Part 2
If you are using the data transformer then you don't need to worry about malicious users. The data transformer will fail because it will not be able to reverse transform the category from the fake id. In my tutorial the transformer will throw a Symfony\Component\Form\Exception\TransformationFailedException exception.
You can also write a validator (potentially using a call back) if you wanted that checks that the submitted category is real if you want an error to show in the form. Doctrine wont allow you to persist a fake category relationship as the foreign key constraint will fail.

Symfony2 force subform validation when every field is empty

I have two entities (let's call them A and B) bound in a one to one relatioship and a form to populate them.
B entity fields are populated depending on a state in entity A as follows:
entity A: state 0
entity B: both fields empty
entity A: state 1
entity B: field 1 filled field 2 empty
entity A: state 2
entity B: field 1 empty field 2 filled
Both fields filled state is not allowed.
So I made 3 custom callback validators to check states 1, 2 and not allowed.
Unfortunately checking on states 1 and 2 is not triggered when both fields are empty, clearly because fields are empty; infact adding a fake hidden field to the form triggers validation process, because form is populated!
Obviously this is a hackish solution, so I was wondering if there is a way to force subform validation even when every form field is empty.
Symfony does not validate forms, it validates entities. Your best best is to make a validation function in your entities and validate using symfony's 'Getters' validation described here:
http://symfony.com/doc/2.1/book/validation.html#getters
I believe for your case, the entity that has the validation is the one associated with the form type.

How to make Symfony2 entity formtype show entities of type A but save them as type B?

I currently have the option in my application for a user to select favorite Items from a list. The form element is of type Entity and shows the list of objects. Users can select a number of them as their personal favorite.
However, although the list must show Items, what has to be stored is actually a FavoritedItem (which contains extra information about when/how the user favorited his Item).
I cannot figure out how to convert the entity types so that the user can pick from a list of Item entities but that the form stores FavoritedItems connected to the user.
I guess your entity has a relationship with FavoritedItem, when you are creating your form, don't include that field, but a dummy field to contain the data the user selected:
$builder->add('favs', null, array('property_path' => false, 'type'='entity'.....));
Find this line:
if ($form->isValid()) {
// perform some action, such as saving the task to the database
return $this->redirect($this->generateUrl('task_success'));
}
and for each of your items, set the appropriate FavoritedItem on your entity. It would look something like:
$favorites = $form->get('favs')->getData();
foreach($favorites as $f){
$FavItem = new FavoritedItem($f);
$yourEntity->addFavorite($FavItem);
}

MVC2 TryUpdateModel's include attributes not ignoring validations on fields unincluded

I have a form in my MVC 2 application that allows a user to update a set of fields from a model object, this is purely an update as the model object is already existing with its required fields entered. However when I try to update a small set of fields and call TryUpdateModel on my model object it fails and my modelstate has errors based on required fields that have already been filled out.
Here is my controller code:
[HttpPost]
public ActionResult Work(int id, FormCollection forms)
{
var lead = claimRepo.GetLeadByID(id);
if (lead == null)
return View("NotFound");
if (TryUpdateModel(lead, "Lead")) {...}
}
I've even tried explicitly stating which fields to update like so
TryUpdateModel(lead, "Lead", new string[] { "Date", "UserID", ...}) {...}
And it still fails, is there some reason this doesn't ignore validation on fields not included or am I doing something wrong?
Thanks!
EDIT
I found the issue, I had a property on my class that wasn't database backed and was marked as required in metadata, so adding a getter and setter to return what the property represented caused the TryUpdateModel to pass, but I am still curious as to why the explicit include of properties didn't ignore the field I hadn't included.
Another Edit
I have a user model as well with all database backed required fields and trying to explicitly state which fields are being updated still results in modelstate errors on the fields missing in the form, but are filled in on the model object from the db that is being updated.
I am not sure when the default behaviour was changed for validating only incoming data, from what I know I think only asp.net mvc1 supported it, then it changed in asp.net mvc2 anyway you could say [Validate(false)] and allow the partial data to go through and manually do some validation. You could use a ViewModel and validate all fields on the view model if needed as a second option. A helpful link: partial validation