Symfony Form OneToMany Entity ManyToOne Relationship - symfony

Three entities exists; Topic, Meta and User.
Topic OneToMany Meta ManyToOne User
How can this be created using Symfony Forms?
Originally this was a ManyToMany relationship between Topic and User but this has been altered to allow additional information about the relationship to be stored in Meta.
Original form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('users')
;
}
Modified form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('users', EntityType::class, [
'multiple' => true,
'class' => 'FooBarBundle:User',
'choice_label' => 'username',
])
;
}
This renders a form with Title and a multi select for User. The problem is User doesn't map to Meta and so the User data won't be persisted. Is mapped=false and using the controller to attach the Meta entity to Thread the correct way to handle this relationship? Or is there a way to use a DataTransformer to convert the Users to Metas?
--- UPDATE ---
public function setUsers($users) {
foreach($users AS $user) {
$meta = new Meta();
$meta
->setUser($user)
->setThread($this);
$this->addMeta($meta);
}
return $this;
}
Or is using the call from within Form::handleRequest to Thread::setUsers the right place to convert a User to a Meta?

Related

Symfony2 Nested CollectionType form w/ Dependency injection data not saving

I have a problem with the dependency injection, and saving it to the database, I have a following formType inside another form which i use in two different controller routes which handle the same entity: Creating a new entity and editing it. When i'm trying to create a new entity and set $user field for it, it will save user field as empty string.
class SomeClass extends AbstractType
{
private $tokenStorage;
private $user;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$user = $this->tokenStorage->getToken()->getUser();
$builder
->add('price', null, array(
'label' => 'price',
'required' => true,
'translation_domain' => 'some_translation',
'attr' => array(
'placeholder' => 'price'
)
))
->add('user', HiddenType::class, array(
'data' => $user
));
// dump($user);
// exit(0);
}
I have tried it out and dumped it and debugged and what i've found out is that when i dump $user i get the proper data i need firstName, lastName etc. , but when i submit the data it does not save it to the database instead i get empty string. Then i dumped out the whole form after submit in the controller and found out that the user field is null.
However it does work when i go to edit route and edit the existing entity, but if i create new entity on the edit form it does work on the one that exists, but not the newly made entity.
I have also checked the controller and the Entity class itself and those are not the problem.

symfony filter collection field type like entity field type

I have a form with a collection field type.
I'd like to filter it as we can do for entity field types but I'm not finding the solution.
i found other similar questions but no satisfiable answer so far. Can we do something like :
$builder
->add('userIngredients', 'collection', array(
'type' => new UserImportedIngredientType($this->userIngredients),
'query_builder'=>$this->queryBuilder,
))
;
If not, can we use form listener event to exclude some elements based on the object property ? How ?
This collection represents userIngredients that I want the user to be able to change if they have their property isImported set to true, hence the search for the query_builder solution.
Well, I figured I could do something as simple as build a regular form not attached to a parent entity.
In case this might help someone :
class UserImportedIngredientType extends AbstractType
{
protected $userIngredients;
protected $userImportedIngredients;
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($this->userImportedIngredients as $userImportedIngredient)
{
/**
* #var $userImportedIngredient UserIngredient
*/
$builder
->add($userImportedIngredient->getId(), 'genemu_jqueryselect2_entity', array(
'query_builder'=>$this->userIngredients,
'class' => 'AppBundle:FoodAnalytics\UserIngredient',
'multiple' => false,
'label' => $userImportedIngredient->getName(),
'required'=>false,
'mapped' => false,
'data' => $userImportedIngredient
))
;
}
}
/**
* #return string
*/
public function getName()
{
return 'appbundle_foodanalytics_user_imported_ingredient';
}
public function __construct($userIngredients, $userImportedIngredients)
{
$this->userIngredients=$userIngredients;
$this->userImportedIngredients=$userImportedIngredients;
}
}
I solved it like this in my case with additionally Sonata on top of Symfony. What I did was feeding the 'data' parameter the specifically doctrine queried array of entities result. (In Repository: return $queryBuilder->getQuery()->getResult();)
/** #var MyEntityRepository $myEntityRepository */
$myEntityRepository = $this->getEntityManager()->getRepository(MyEntity::class);
/** #var MyEntity[] $myEntities */
$myEntities = $myEntityRepository->findBySomeCriteriaFilter(
$parameter, Constants::specificConstant
);
$formMapper->add(
// html name=
'myEntityProperty',
\Symfony\Component\Form\Extension\Core\Type\CollectionType::class,
[
// specific form for MyEntity
'entry_type' => new Form\MyEntity\MyEntityType(),
'allow_add' => true,
'label' => false,
'entry_options' => [
'label' => false
],
// the filtered array of entities from doctrine repository query above
'data' => $myEntities,
]
);
Use this instead of sonata_type_model_list, I guess.
Also if you want to filter sonata_type_model, use EntityType instead and use the 'query_builder' option with a Closure and returning the queryBuilder instead of the array of entities. This is all very inconsistent, best don't use symfony and sonata at all.
As far as I know Collection does not have the query_builder option
So you cannot go this way.
Is hard to decipher what you are trying to do with 4 lines of formType.
Your code looks alright, except the unsuppported query_builder, and you are already passing the userIngredients to the constructor.
My though is that if you need to filter this, then you shouldn't do it in the collection Type, but in other place.
EDITED:
On a second though, you are trying to filter the collection in the wrong place. Is not on the base collection , but in :
class UserImportedIngredientType extends AbstractType {
function __construct( $userIngredients ) {
// Do your stuff
}
function buildForm( FormBuilderInterface $builder, array $options) {
// Add here your entity with the query_filter option :)
}
}
Check the other entries in SO over Collections, there are many of them

Symfony Forms - dynamic number of items

I'm trying to build a product page that will contain a form with a dynamic number of "options" (either select boxes or input fields) depending on the product. After reading the documentation, I can't see how to create a form entity that would work when building this form. I feel like I'm missing something obvious.
What you need to do is basically create form field of collection type, which will be your collection of select boxes, input fields, whatever.
Check documentation and read about embeding forms, it is described pretty well ther
Your parent form:
class ParentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', 'hidden')
->add('name')
->add('yourCollection', 'collection', array(
'type' => new ChildType(),
'label' => 'Label for your child form',
));
}
}
Your child form:
class ChildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', 'hidden')
->add('category', 'choice')
;
}
}

Symfony2 + Doctrine2 / building a form from 2 joined entity objects

Is it possible to build a form from 2 joined entity objects?
I have two entities property & propertylanguage which are joined on onetomany relation.
(One property can have many languages)
Language has a title and description colomns.
So one property can have a english, french, german title.
I am trying to build a form out of that.
See below.
Controller: addProperty.php
class AddPropertyController extends Controller
{
// ....
public function indexAction(Request $request)
{
$property = new property;
$language = new propertyLanguage;
$property ->addpropertylanguage($language);
$form = $this->createForm(new propertyType($this->getDoctrine()),$property);
// .....
}
Form type: propertType.php
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('title', 'text');
// other ->add() below.
}
It returns the following error:
Neither property "title" nor method "getTitle()" nor method
"isTitle()" exists in class "\defaultBundle\Entity\property"
Of course there is no property Title in property, but there is one in propertylanguage..
Even if I try:
->add('title', 'entity', array('class'=>defaultBundle:propertylanguage));
it doesn't work.
Thanks if you have time to help me.
Best,
Pierre.
What you will want to do is make a PropertyLanguageType class as well as a PropertyType.
Then, in your PropertyType you will embed the PropertyLanguageType:
public function buildForm(FormBuilder $builder, array $options)
{
// $builder->add('propertyLanguage', new PropertyLanguageType());
// Since we have a 1 to many relation, then a collection is needed
$builder->add('propertyLanguage', 'collection', array('type' => new PropertyLanguageType()));
The PropertyLanguageType is where you add the title.
It's all in the forms section in the manual but it might take several readings.
A second approach is to add a getTitle to your Property entity which would return the title from the PropertyLanguage entity. By doing this, your original form will work. But it can be a bit of a mess when you start to have multiple associations with multiple attributes. Best to just define a type for each entity.
You could use a query_builder when defining the form. Here's how your form class might look like. Of course it will certainly not be exactly as so but that will give you a good start ;)
public function __construct($id)
{
$this->propertylanguageId = $id;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('propertylanguage', 'entity', array(
'label' => 'Property Language',
'class' => 'YourAdressToBundle:Propertylanguage',
'query_builder' => function(EntityRepository $er) use ($propertylanguageId) {
return $er->createQueryBuilder('p')
->join('p.property', 'prop', Expr\Join::WITH, 'prop.id = :propertylanguageId')
->setParameter('propertylanguageId', $propertylanguageId);
},
));
}
Hope that'll be helpful

Display ManyToOne field in Symfony2 forms?

I am having two entity files one as user.php and another as usertype.php. now i want to display a login form with 3 fields viz username, password and usertype. the usertype will be a selection that will fetch data from usertype table. here is the code that i wrote inside user.php to create a manytoone field for usertype_id
/**
* #ORM\ManyToOne(targetEntity="Usertype")
*/
protected $usertype;
Below is my Form generation Code
class LoginForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('login', 'text', array('label' => 'Username',));
$builder->add('password');
}
}
Now I need to add one more field to my form builder that will be a selection of usertype table.
...
use Acme\YourBundle\Entity\Usertype;
class LoginForm extends AbstractType {
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('usertype', 'entity',
array(
'class' => 'AcmeYourBundle:Usertype'
'label' => 'User Type',
)
);
}
}
You can read more informations about the entity field type wich will give you the options available for this type of field.
Don't forget to add a __toString() method to your model to tell the form builder what to display.
namespace Acme\YourBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
class Usertype
{
public function __toString()
{
return $this->getName();
}
}
There are other ways to do it, but you can try this:
$builder->add('usertype', 'entity',
array(
'class' => 'YourBundle:UserType
'required' => true, // Choose if it's required or not
'empty_value' => 'User type', // Remove this line if you don't want empty values
'label' => 'Type', // You can put a label here or remove this line
)
);
I hope it helped!
http://symfony.com/doc/2.0/reference/forms/types/entity.html
property¶
type: string
This is the property that should be used for displaying the entities as text in the HTML element. If left blank, the entity object will be cast into a string and so must have a __toString() method.

Resources