Symfony2 forms - filtering parent objects when adding a child object in OneToMany relation - forms

I have two entities - Category and Article with OneToMany relation.
When I render the form for adding/editing Article object, I see all categories in an html select, but I want to see only a part of the categories (in future I would also like to add categories dinamically, according to different conditions).
How to override the query, made automatically by Doctrine, which retrieves the categories, in order to filter them?
Thanks in advance,
Nikolay

Passing query_builder parameter in your category field at your ArticleType, you can customize the query for retrieve category elements.
$form = $this->createFormBuilder()
->add('category', 'entity', array(
'class' => 'ArticleBundle:Category',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.name', 'ASC');
//add more query elements here
},)
)
->getForm();
View more details here

You can do this by setting the query_builder option to a closure that accepts the repository a an argument and returns a query builder.

Related

How can I relation a foreign key with a form in symfony?

Hi I'm trying to make a relation between two entities, a user creates proyectes, but in the create a project form I don't know how do it.
If I do this:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('Nombre')
->add('Resumen')
->add('Creados')
;
}
I have the following error:
What can i do to make the form that make a relation and show the user how creates the proyect? It's my first time using stakoverflow, thank you!
you could use the EntityType for a to-one relationship like:
$builder->add('users', EntityType::class, [
'class' => User::class,
// uses the User.username property as the visible option string
'choice_label' => 'username',
]);
Have a look at the documentation, too. This will help you understand other form field types as well.
For a to-many relationship you can use Collection which is a bit more complicated.

How to manage only one oneToMany entity in parent form

I have an Entity Criteria which can have several Entity Vote (associated).
I want to DISPLAY a list of criteria and to show only ONE Vote form in front of each Criteria (not zero, not many), to allow user to vote for each Criteria.
But, as I have a oneToMany association, in my CriteriaForm, I must have a CollectionType of Vote (I think ?). I tried to have only a VoteType :
$builder->add('votesCritere', VoteCritereType::class);
but I have an error :
The form's view data is expected to be an instance of class LabelBundle\Entity\VoteCritere, but is an instance of class Doctrine\ORM\PersistentCollection
So I think I must have a CollectionType. But, if I have a collection type, I start with ZERO form (because My Criteria does not contain any Vote yet).
I want to have only (and always) one Vote form in front of each criteria, to add a vote to the criteria (I don't want the number of forms reflects the number of votes)
How can I do that ?
Thanks for your help !
Let's think out loudly - in case you use entity bind form with collection type for votes, it'll allways show all of yours votes that would be bind to each criteria.
In this case I would recommend the array of forms based on criteria entity IDs.
Create Vote form type:
class VoteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('answer', ChoiceType::class, array(
'choices' => array(
'Yes' => true,
'No' => false,
)
))
->add('note', TextareaType::class),
->add('criteriaId', HiddenType::class),
->add('vote', SubmitType::class);
...
...
}
In the controller - get traversable of criterias (e.g. method findAll() method of repository) and create array of named forms based on criteria entity IDs:
$ff = $this->get('form.factory');
foreach ($criterias as $criteria) {
$voteForms[] = $ff->createNamedBuilder(
'vote_'.$criteria->getId(),
new VoteType,
array(
'criteriaId' => $criteria->getId()
)
)
->getForm()
->createView();
}
return $this->render(someView, array("voteForms" => $forms));
And when the form is submitted then you can identify to which criteria the vote belongs by the hidden criteriaId field.
EDIT - Added: How to submit all forms with one button
'criteriaId' field and 'vote' submit in the VoteType is no longer needed - so:
class VoteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('answer', ChoiceType::class, array(
'choices' => array(
'Yes' => true,
'No' => false,
)
))
->add('note', TextareaType::class);
...
...
}
And in the controller just create form with VoteTypes members:
$fb = $this->createFormBuilder();
foreach ($criterias as $criteria) {
$fb->add('vote-criteria-'.$criteria->getId(), VoteType::class);
}
$fb->add('submit', SubmitType::class);
$frm = $fb->getForm();
$frm->handleRequest($request);
if ($frm->isSubmitted() && $frm->isValid()) {
// all criteria vote data
$frm->getData();
...
}
return $this->render(someView, array('form' => $frm->createView()));

How should a `FormType` be structured in order to include an `EntityType` field which doesn't exist in the `FormType` entity?

Taking the below as an example, OrderType is based on the entity Order. The form that is required needs to contain the following two EntityType dropdowns within it:
Category (this does not exist in Order - it is just to subset the dropdown of Product to make it more manageable)
Product
The identifying Category variables (Category_id and CatName) only exists within the Product entity (the Order can include multiple Products) and as a result, Symfony throws back an error saying:
Neither the property "category_id" nor one of the methods "getcategory_id()", "category_id()", "iscategory_id()", "hascategory_id()", "__get()" exist and have public access in class "AppBundle\Entity\Order".
Is there a way that this Category field can be included even though it doesn't exist in the Order entity?
It doesn't seem right to add category_id to the Order entity. I was thinking of something along the lines of below using 'mapped'=>'false' but I can't get it to work:
$builder
->add('category_id','entity',array(
'class'=>'AppBundle:Product',
'placeholder' => '-- Choose --',
'choice_label'=>'CatName',
'mapped'=>'false',
'query_builder'=>function(EntityRepository $er) {
return $er->createQueryBuilder('p');
}))
...and then after an Ajax response, feed in the category back in with $category?
->add('products','entity',array(
'class'=>'AppBundle:Order',
'placeholder' => '-- Choose --',
'choice_label'=>'ProductName',
'query_builder'=>function(EntityRepository $er, $category ) {
return $er->createQueryBuilder('p')
->where('p.category_id = :id')
->setParameter('id', $category )
->orderBy('p.ProductName','ASC');
}));
}
As you say, adding a Category property to the Order entity just for forms is less than ideal. What I would do is make a OrderCategoryType and pass in Order and Category as an array.
// Controller
$order = new Order();
$category = new Category(); // Or create from $order->getProduct()
$data = ['order' => $order, 'category' => $category);
$form = $this->createFormBuilder($data)
->add('order',new OrderType(),
->add('category',new CategoryType()
);
You will have to do some messing around to keep everything in sync but it should work just fine.

A set of fields for one property entity in Symfony 2

My Product entity has the following structure:
private $id;
private $title;
/**
* #ManyToOne(targetEntity="Category")
* #JoinColumn(name="cat_id", referencedColumnName="id")
*/
private $category;
Category have nested structure. And each level of nesting is shown in 5 separate fields:
In class form code, I solve it in this way:
$builder
->add('cat_1', 'entity', array(
...
'query_builder' => function() { return someSelectLogic1(); }
))
->add('cat_2', 'entity', array(
...
'query_builder' => function() { return someSelectLogic2(); }
))
->add('cat_3', 'entity', array(
...
'query_builder' => function() { return someSelectLogic3(); }
))
->add('cat_4', 'entity', array(
...
'query_builder' => function() { return someSelectLogic4(); }
))
->add('cat_5', 'entity', array(
...
'query_builder' => function() { return someSelectLogic5(); }
))
Now I need to know which field is filled in the last turn and pass the value of that field in the entity property.
In all that I do not like:
complex logic to determine which field with category was filled at the end
each of these fields is not tied to the entity 'mapped' => false
1) What the right way to organize code of my form?
2) And is there a way to bring these fields into a separate class which will deal with the logic of determining which category was chosen in the end?
I would suggest the following:
1) Create a new custom form field type and put all those entity in there.
This process is not much different from ordinary creation of form type. Just enclose those fields in it's own buildForm() and that should do the trick. Docs.
2) Mark all those entity fields with property "property_path => false".
Clearly you wont be storing these values inside your model.
3) Add two more fields: chosen and lastOne.
Now, this might be tricky: I would either set the chosen to text type (basically, generic type) or would use entity as well. If you go for entity you would need to include all possible answers from all entity fields. As for the lastOne set it to text as it will reflect which field (by name) was selected last.
Either way, those two fields will be invisible. Don't forget to set property_path to false for lastOne field.
4) Finally, add ValueTransformer (docs) which will contain logic to "see" which field was selected last.
Now, I dealt with it only once and don't understand it just quite yet, so your best bet would be trial and error with examples from official docs, unfortunately.
What basically you should do is to, within value-transformer, read the value of field lastOne. This will give you the name of field which was selected last. Then, using that value, read the actual last value selected. Last, set that value (object, if you've went for entity type, or it's ID otherwise) to chosen field.
That should basically do the thing.
As for the JS, I don't know if you're using any framework but I will assume jQuery. You will need to set lastOne field as your selecting items in your form.
$(function(){
$('#myform').find('select').on('change', function(){
var $this = $(this);
$this.closest('form').find('#__ID_OF_YOUR_LASTONE_FIELD').val($this.attr('name'));
});
});
I'm sorry I cannot provide you with code samples for PHP right now. It's a bit late here and will do my best to further update this answer tomorrow.

Entity mapping in a Symfony2 choice field with optgroup

Suppose to have an entity in Symfony2 that has a field bestfriend, which is a User entity selected from a list of User entities that satisfy a complex requirement.
You can render this field in a form by specifying that it is an entity field type, i.e.:
$builder->add('bestfriend', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'property' => 'username',
));
This form field is rendered as a <select>, where each one of the displayed values is in the form:
<option value="user_id">user_username</option>
So, one would render the field by using the <optgroup> tags to highlight such special feature of the friends.
Following this principle, I created a field type, namely FriendType, that creates the array of choices as in this answer, which is rendered as follows:
$builder->add('bestfriend', new FriendType(...));
The FriendType class creates a <select> organized with the same <option>s but organized under <optgroup>s.
Here I come to the problem! When submitting the form, the framework recognize that the user field is not an instance of User, but it is an integer. How can I let Symfony2 understand that the passed int is the id of an entity of type User?
Here follows my solution.
Notice that it is not mentioned in the Symfony2 official docs, but it works! I exploited the fact that the entity field type is child of choice.
Hence, you can just pass the array of choices as a param.
$builder->add('bestfriend', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'choices' => $this->getArrayOfEntities()
));
where the function getArrayOfEntities() is a function that fills the choice list with the friends of my friends, organized by my friends:
private function getArrayOfEntities(){
$repo = $this->em->getRepository('AcmeHelloBundle:User');
$friends = $repo->findAllFriendByComplexCriteria(...);
$list = array();
foreach($friends as $friend){
$name = $friend->getUsername();
if(count($friend->getFriends())>0){
$list[$name] = array();
foreach($friend->getFriends() as $ff){
$list[$name][$ff->getUsername()] = $ff;
}
}
}
return $list;
}
I know the example could be meaningless, but it works...
PS: You need to pass the entity manager to let it working...