Symfony 2 : render string as choice in a form - symfony

I have a entity, Comment. and when a user adds a comment, besides the comment he gives, he can choose between "good", "OK", "bad" etc.
I know how to do it by using two related entities, one for Comment, another for the choice ("good", "bad", etc). then create a relation between these two entities.
But it seems like an overkill for this. Anyone knows a simple way to achieve it? I wish I can save the choice as a string, but render it as a choice in the comment form.
Thanks!

You could just save it as a string along with the comment. In your Comment FormType, just add a field for the rating, something like:
$builder->add('rating', 'choice', array(
'choices' => array(
'good' => 'Good',
'ok' => 'OK',
'bad' => 'Bad',
)
));
And in your Comment Entity, just add the corresponding field and setter/getter.

Related

How it is possible to show a choice field (checkboxes) with the selected value

I use an Symfony2 form with a choice field based on 4 checkboxes. Now i have the Problem, that i can't reload data in this choice field.That means, when in the database the value 9 is stored, will the checkbox "unknown if "lang test" performed" not be selected, when i load the entity in this form.
->add('fu5LangTest', 'choice', array(
'choices' =>array(
'poor compliance'=>0,
'negative'=>1,
'positive (recognizes at least 1 image reliably)'=>2,
'unknown if "lang test" performed'=>9),
'choice_value' =>function (DataEFu5 $entity = null) {
return $entity ? $entity->getFu5LangTest() : '';
},
'expanded'=>true))
I tried a lot of things with the choice_value Attribut, but i think i'm using it wrong. Whats the right way? i didn't found some useful Information. What i have to do, that the correct checkbox will be selected after an reload?
The storing process is working fine.
Thanks for an feedback
The form is not the right place to do domain Logic.
Anyway, the data has the current fu5LangTest value. You should use
->add('fu5LangTest', 'choice', array(
'choices' =>array(
'poor compliance'=>0,
'negative'=>1,
'positive (recognizes at least 1 image reliably)'=>2,
'unknown if "lang test" performed'=>9
),
// ...
Form creation in Controller:
$object = new DataEFu5(); //or get it by your repository
//this condition will be better in a service as it is business logic ;)
if(!in_array($object->getFu5LangTest, [0,1,2])) {
$object->setFu5LangTest(9);
}
$form = $this->createForm(ObjectType, $object);

doctrine join column joined on other entity

I have 3 tables:
Post -> Type -> Category
I need to get the category on the Post entity passing per Type to use this on a filter form
This is possible?
like a join and subjoin
If I understand correctly, you want to be able to filter Post's by Category.
Like with any other field you wish to filter by, you have to add a Form to the filter's FormBuilder. The problem in this case is that the Entity bound to the form doesn't have the property category. It's its property type who does.
Thus, you need to tell the Form how to access the right property. This is achieved by using the property_path option. Here's the documentation for it.
You would do something like this in your filter's Type:
$builder
->add('category', 'entity', array(
'label' => 'Category',
'data_class' => 'Category',
'property_path' => 'type.category',
))
;
The property_path option is very powerful. It will accept any path that the PropertyAccess component does. Read its documentation here.
Multiple joins are possible in doctrine. Please, read this section in doctrine documentation.

Symfony2: Using two form fields for one entity property?

This is an existing schema I'm working with and I'm trying to not make any changes for the time being. I have an entity property that represents a university semester, like "fall12", "spring11", etc.
When adding or editing this entity with a form, I want to split that property into two form fields: "Season" (fall or spring") and "Year" (2011, 2012, etc):
...
->add('formSemesterSeason', 'choice', array(
'label' => 'Season',
'mapped' => false,
'choices' => array('fall' => 'Fall', 'spring' => 'Spring'),
))
->add('formSemesterYear', 'choice', array(
'label' => 'Year',
'mapped' => false,
'choices' => $this->courseManager->getYearChoices(),
))
...
When submitting the form, the values need to be combined and saved to the "semester" property on the entity as a string
When viewing the edit form, the existing "semester" value needs to be split between the two.
I don't think data transformers help here, since they apply to transforming just one form item.
Right now I'm using a form event POST_SET_DATA to fill out the two form fields when editing an existing entity:
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) use ($course_manager) {
$course = $event->getData();
$form = $event->getForm();
$semester = $course->getSemester();
$parsed_semester = $course_manager->parseSemesterMachineName($semester);
$form->get('formSemesterSeason')->setData($parsed_semester->season);
$form->get('formSemesterYear')->setData($parsed_semester->yearFull);
});
This works well, but how do I then combine the values back after the form has been submitted? I can do it easily in the controller, but I think I should be able to use form events, and have the data manipulation take place before form validation.
You can combine them back in a POST_SUBMIT listener.
The best way (reuseable) would be to create your own custom form type with a data transformer to split/combine the fields internally.
There are "recipes" in the cookbook but the best way that I found to create it was to rip apart the DateTime field type and associated transformers (DataTransformerChain, DateTimeToArrayTransformer & ArrayToPartsTransformer) for parts and build my own from that.

Symfony2 Form entity

I have a problem, I want to create a simple search form with a filter assembly. These filters are attributes that belong to attribute groups.
group 1
[] Attribute 1
[] Attribute 2
[] Attribute 3
group 2
[] Attribute 1
[] Attribute 2
[] Attribute 3
But the problem is that I can not do (graphic aspect)
$builder->add('attribut', 'entity', array(
'class' => 'RestoFrontBundle:Attribut',
'group_by' => 'groupeAttribut.id',
'expanded' => true,
'multiple' => true,
'query_builder' => function(AttributRepository $er) {
return $er->createQueryBuilder('a')
->join("a.groupeAttribut", 'g')
->where("a.statut = 1");
}
))
->getForm();
Also I can not manage the game if the checkbox has been checked.
You note that the graphic aspect is the hard part. That is due to the way checkboxes are used in HTML. Unlike select inputs there is no notion of an optgroup. The closest analog for checkboxes would be a fieldset with a legend.
You may want explore using a Choice Field type rather than an entity type. Provide your choices via some provider function within which you format the options array(s) whether or not you retrieved them from a database. ( For the record, that's exactly how I populate the select at http://stayattache.com which has multiple places to retrieve options from. ) You may even want to explore creating your own form field type and template to format the output. Checkout the documentation on creating your own field type.
I hope that helps a bit. There are probably plenty of other ways to approach this as well.

Allow multiple date formats in symfony2 form builder

A client requested this. He wants to allow multiple date formats for a birthday field. The documentation didn't give me any clues how to realize it and neither did google.
Anyone who experienced such a request before and has a lead how to achieve this?
Currently it looks like this:
$builder->add('xxx', 'birthday', array('widget' => 'single_text', 'invalid_message' => 'some message (dd-MM-yyyy)', 'format' => 'dd-MM-yyyy'))
If you want to handle different date formats in your form, you ought to look at DataTransformer
It helps you to transform data from one format to another, for example:
2013-03-26 ==transform==> 2013/03/26
2013.03.26 ==transform==> 2013/03/26
26.03.2013 ==transform==> 2013/03/26
Data transformer should NOT be used in this case.
The main point of data transformer is to convert a data back and forth between view <=> norm <=> model.
It's not your case, you don't want a bidirectional transformation.
What you want is to filter the data, and for that, you can use a form event:
$builder->add(
$builder
->create('xxx', 'birthday', [...])
->addEventListener(
FormEvents::PRE_SUBMIT,
function(FormEvent $event) {
$value = $event->getData();
// Do the filtering you want (for example replacement of special chars with a dash)
// $value = preg_replace('[^\d]', '-', $value)
$event->setData($value);
}
)
);
And you are done, the data is filtered on the PRE_SUBMIT event, before validation.
I wrote this example from memory and didn't tested it, maybe you'll should adapt it (and add your field option instead of [...].

Resources