symfony2 how to save specific data with entity in formbuilder - symfony

I need to store userinfo for active user represented by $id, which I parsed from controller. In this case (in code) I obtain in form list of all users, but I need to obtain only actual user which I work with.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$id = $this->id;
$builder
->add('companyname')
->add('address')
->add('city')
->add('zip')
->add('userinfo', 'entity', array('property' => 'id', 'class' => 'Admin\SecureBundle\Entity\Userinfo', 'attr' => array('value' => $id), 'empty_value' => $id));
idea: I have a user and an invoice address for that user. In database onetoone rel.
I need to create invoiceaddress of the active user - id of this user should be stored in userinfo.
Any ideas?

This is from the Symfony2-Doc about the entity form:
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.isActive = 1')
->orderBy('u.username', 'ASC');
},
));
You need to make your own query here.

Related

Placeholder When Query Builder Returns Null on Entity Type

I've created a form with an EntityType field with a query builder:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$entity = $builder->getData();
$relatedParentId = $entity->getParentEntity()->getId();
$builder->add('myEntity', EntityType::class, array(
'class' => myEntity::class,
'query_builder' => function(\AppBundle\Repository\myEntityRepository $eR) use ($relatedEntityId) {
return $aR->getByParentId($relatedEntityId);
},
))
}
When the query returns a value, it's fine. When null is returned however it shows on the form as just a blank option with a dropdown to nothing and is not very user friendly. I want to have a message to say no results have been returned.
Note that when a result is returned no message is required so the 'placeholder' option will not be enough. I'm possibly missing something obvious in the documentation but I've had with no luck so far.
Use the placeholder option:
$builder->add('states', EntityType::class, array(
'class' => myEntity::class,
'query_builder' => function(\AppBundle\Repository\myEntityRepository $eR) use ($relatedEntityId) {
return $aR->getByParentId($relatedEntityId);
}
'placeholder' => $hasResults ? false : 'No results',
));
Where you build the hasResult flag before.

Symfony Dynamic Modification of Form without Entity

I am following the Symfony (v2.7) Cookbook recipe for dynamic form modification. What I am aiming for is displaying certain fields based on a user's radio button selection. For example, if a user wishes to filter a search based on records from the last fiscal year, he selects the "Fiscal Year" radio button from the criteriaFilter choice field type (example below), and the appropriate fields are generated. If he changes his mind and selects "Semester" instead, the fiscal year fields are replaced with the semester fields, and so on.
Example code:
$builder
->add('librarian', 'entity', array(
'class' => 'AppBundle:Staff',
'query_builder' => function(EntityRepository $er){
$qb = $er->createQueryBuilder('st');
$qb
->where('st.employmentStatus = :employmentStatus')
->setParameter('employmentStatus', 'faclib')
->orderBy('st.lastName', 'DESC')
->getQuery();
return $qb;
},
'placeholder' => 'All Librarians',
'required' => false
))
->add('program', 'entity', array(
'class' => 'AppBundle:LiaisonSubject',
'query_builder'=>function(EntityRepository $er){
$qb = $er->createQueryBuilder('ls');
$qb
->orderBy('ls.root, ls.lvl, ls.name', 'ASC')
->getQuery();
return $qb;
},
'property' => 'indentedTitle',
'placeholder' => 'All Programs',
'required' => false,
'label' => 'Program'
))
->add('criteriaFilter', 'choice', array(
'expanded' => true,
'multiple' => false,
'choices' => array(
'academic' => 'Academic Year',
'fiscal' => 'Fiscal Year',
'semester' => 'Semester',
'custom' => 'Custom Range'
),
))
;
This seems pretty straighforward based on the cookbook entry. However, the form I am creating is not bound to an entity. Therefore, fetching data via the method
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){
$form = $event->getForm();
//normally the entity, but NULL in this case
$data = $event->getData();
...
which would normally allow for calling of getter methods on entity properties returns null. So obviously this can't work in this case.
So the question is, is there another way to dynamically generate fields inside of a form that is not tied to an entity?
You can pass options to the form, including data. So something like (from memory but it's untested):
// controller
$this->createForm(SomeForm::class, null, ['fiscalYears' => [2001, 2002]);
// type
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['fiscalyears' => []);
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$fiscalYears = $options['fiscalYears'];
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($fiscalYears) {
$form = $event->getForm();
$form->add('fiscalYear', ChoiceType::class, [
'choices' => $fiscalYears
]);
}
}

Form select via Entity always return 0 when save to database

I've a form with select via entity (don't have relation to other table)
but always return 0 when save to database, i can't find error
this is my build form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label' => 'Company Name'))
->add('address')
->add('idProvince', 'entity', array(
'mapped' => false,
'class' => 'SettingBundle:Province',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('e')->orderBy('e.name', 'ASC');
},
))
select form show perfect with no error, but when i save to database, it always return Zero or null
Whats wrong with my code? do you have a clue or sample for this,
Thanks
it solved with entity-relationships-associations http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations
thanks

Symfony2 FormBuilder with Entity class

I have a form that works well, there is just one issue with it and I'm hoping that I'll get an answer on how to do what I need to do.
<?php
namespace ADS\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContext;
class UserType extends AbstractType {
private $type;
public function __construct($type) {
$this->type = $type;
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('firstName', 'text', array('required' => true))
->add('lastName', 'text', array('required' => true));
$builder->add('email', 'email', array('required' => true));
$builder->add('parentCompany', 'entity', array(
'class' => 'ADSUserBundle:Company',
'expanded' => false,
'empty_value' => 'CHOOSE ONE',
'required' => false,
'property' => 'companyName'
))
->add('enabled', 'choice', array('choices' => array('1' => 'Enabled', '0' => 'Disabled')))
->add('roles', 'entity', array(
'class' => 'ADSUserBundle:Roles',
'required' => true,
'property' => 'displayName',
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array('data_class' => 'ADS\UserBundle\Entity\User'));
}
public function getName() { return 'ads_userbundle_user'; }
}
I have this form, the portion I am looking at is the 'roles' portion... Right now it created a multiple select box ( as I expect it to ), though the value is sequentially ie: 0,1,2,3,4...
What I really need is to figure out how to take this entity, and make the property to be the displayName ( as it is now ) and get the value to be the corresponding internalName This way it'll give me an array like:
array('ROLE_EXAMPLE' => 'EXAMPLE', 'ROLE_EXAMPLE1' => 'EXAMPLE1')
Any ideas how to accomplish this is greatly appreciated.
Kamil Adryjanek is correct, it is going to be much easier if you change it from an entity to a choice field. I've done some testing, both with FOSUserBundle and without the bundle - in both cases I hit some interesting road blocks.
First, I tried to run it through QueryBuilder in a repository, that didn't work out as it should have. The reason being, the fact that you wanted to be returning an array instead of a ORM object causes an error.
So next, I started looking at creating the choice field. All the guides, say to use the fieldname role instead of roles so I tried that, but I then had to duplicate the UserInterface from FOSUserBundle - I didn't want to do that -- so here I am stressed, and trying to figure it out.
Here is what I ended up doing, which works well.
private $normalRoles = array();
then in the __construct I add: $this->normalRoles = $roles;
Here is the builder:
$builder
->add('roles', 'choice', array(
'multiple' => true,
'choices' => $this->normalRoles
))
;
Originally, I left the multiple part out, figuring that it'd at least let me see an option box. I ended up getting an Array to String conversion error. So, adding the 'multiple' => true in, fixes that error.
Then, in my repository I created a function called normalizeRoles
public function normalizeRoles() {
$data = array();
$qb = $this->getEntityManager();
$query = $qb->createQuery(
"SELECT r.internalName, r.displayName FROM AcmeUserBundle:Roles r"
)->getArrayResult();
foreach ($query as $k => $v) {
$data[$v['internalName']] = $v['displayName'];
}
return $data;
}
From here, we just have to make some small edits in the DefaultController of the UserBundle in the newAction and editAction ( both are the same changes )
So, first off is to put into your Controller use Acme/UserBundle/Entity/Roles in order to avoid any errors and be able to get that repository.
Next, right before you create the form you run the normalizeRoles() function
$roles = $em->getRepository('AcmeUserBundle:Roles')->normalizeRoles()
Then, you pass it through the construct via: new UserType($roles)
full line for that would look like this:
$form = $this->createForm(new UserType($roles), $entity, array(
'action' => $this->generateUrl('acmd.user.edit', array(
'id' => $id)
)
));
or for new:
$form = $this->createForm(new UserType($roles), $entity, array(
'action' => $this->generateUrl('acmd.user.new')
)
));
At this point -- You'll have a working system that will allow you to dynamically add roles into a database table, and then associate those with a new or current user.
You can try do it via query_builder attribute:
$builder->add('roles', 'entity', array(
'class' => 'ADSUserBundle:Roles',
'required' => true,
'property' => 'displayName',
'query_builder' => function (RolesRepository $queryBuilder) {
return $queryBuilder->someMethod() // some method in this repository that return correct query to db.
},
));
In this case it would be better to use choice field Type (http://symfony.com/doc/current/reference/forms/types/choice.html) instead of entity and pass some role choices as option to form because entity field Type get entity id as key for choices:
public function buildForm(FormBuilderInterface $builder, array $options) {
...
$builder->add('roles', 'choice', array(
'choices' => $options['role_choices']
));
...
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'ADS\UserBundle\Entity\User',
'role_choices' => array()
));
}
Notice: it's recommended to pass variables to form through options parameter, not in constructor.
if I understand your question correctly, you need a data transformers. They help you to show data in form as you want.
Documentation: http://symfony.com/doc/current/cookbook/form/data_transformers.html

Can't add values to ManyToMany after creating an entity of the JoinTable (1-n-1)

At first I had a ManyToMany relation between the User and Club entity.
Now, I wanted to add a column in the JoinTable (users_clubs) so I had to create a third entity UserClub. I ran the doctrine:schema:update --force command and all seemed to be fine.
I have my ProfileForm setup with an Entity field like this:
->add(
'clubs', 'entity', array(
'class' => 'AcmeMainBundle:Club',
'property' => 'name',
'multiple' => 'true',
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder('club')
->orderBy('club.name', 'ASC');
},
)
)
The form renders well but I get this error when saving the form:
Catchable Fatal Error: Argument 1 passed to Acme\UserBundle\Entity\User::addClub() must be an instance of Acme\MainBundle\Entity\UserClub, instance of Acme\MainBundle\Entity\Club given in /src/Acme/UserBundle/Entity/User.php
User entity addClub function:
/**
* Add clubs
*
* #param UserClub $userClub
* #return User
*/
public function addClub(UserClub $userClub)
{
if (!$this->userClubs->contains($userClub))
{
$this->userClubs->add($userClub);
$userClub->setUser($this);
}
return $this;
}
->add(
'clubs', 'entity', array(
'class' => 'AcmeMainBundle:Club',
'property' => 'name',
'multiple' => 'true',
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder('club')
->orderBy('club.name', 'ASC');
},
)
)
Can you post your user Entity please ?
Does your user club are nammed user_clubs in your User entity ?
If yes :
->add(
'userclubs', 'entity', array(....
not :
->add(
'clubs', 'entity', array(
I solved it by following this guide:
http://www.prowebdev.us/2012/07/symfnoy2-many-to-many-relation-with.html
I changed my addClub function and added a setClubs function which takes care of setting the club and user in the new UserClub entity.

Resources