Symfony2 FOSUserbundle add user to group - symfony

i'm using FOSUserBundle Groups.
Now i want to add the groups to my user (when adding a new)
I tried to load the groups to my form but failed.
Here the form:
$builder
->add('enabled','checkbox',array(
'required' => false))
->add('locked','checkbox',array(
'required' => false))
->add('username','text',array(
'required' => true))
->add('email','email',array(
'required' => true))
->add('password','password',array(
'required' => true))
->add('roles', 'choice', array(
'choices' => array('ROLE_ADMIN' => 'Admin', 'ROLE_USER' => 'Benutzer'),
'required' => true,
'multiple' => true
))
->add('groups', 'choice',array(
'choices' => $this->getGroups(),
'multiple' => true
))
->add('save','submit')
;
}
Also i tried
$builder
->add('enabled','checkbox',array(
'required' => false))
->add('locked','checkbox',array(
'required' => false))
->add('username','text',array(
'required' => true))
->add('email','email',array(
'required' => true))
->add('password','password',array(
'required' => true))
->add('roles', 'choice', array(
'choices' => array('ROLE_ADMIN' => 'Admin', 'ROLE_USER' => 'Benutzer'),
'required' => true,
'multiple' => true
))
->add('groups', 'collection', array(
'type' => 'choice',
))
->add('save','submit')
;
Thanks for your help :)

I now get the output with:
->add('groups','entity',array(
'class' => 'UniteUserBundle:usergroup' ,
'property' => 'name' ,
'multiple' => true ,
))
Not the next problem... it don't persist to my table 'fos_user_user_group' :(

Have you tried creating a GroupType and instantiating that type in the collection?
->add('groups', 'collection', array(
'type' => new Name\Space\To\GroupType(),
))
For example your GroupType might look like the following code. Notice it's mapped to the Group entity.
<?php
namespace Name\Space\To\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class GroupType extends AbstractType
{
public $group;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('group', 'hidden', array(
'error_bubbling' => false,
'required' => false,
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Name\Space\To\Entity\Group',
));
}
public function getName()
{
return 'namespaceto_grouptype';
}
}

Related

Symfony query builder with post submit data is not changing the values in EventListener

I have a filter form which is filtering for markets, types and airlines. When submitted, I'd like another dropdown (documentlist) to be filtered after the selected values. Therefore I created a post_submit eventlistener which is working (I dumped the values as you can see in the following code). But when then trying to update the documentlist values through a query builder and with the data from my filters, it's not working. Any ideas:
<?php
namespace DocumentBundle\Form\Document;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM;
use Doctrine\ORM\EntityRepository;
use Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use DocumentBundle\Form\Document\DocumentFilterType;
class DocumentDeactivationType extends DocumentFilterType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', 'choice', array('choices' => array(
'document_types.contract' => 1,
'document_types.general'=>2,
'document_types.goodwill_policy'=>3,
'document_types.pricesheet'=>4,
'document_types.yq_update'=>5,
'document_types.contract_addendum'=>6),
'choices_as_values' => true, 'label' => 'label.types',
'expanded' => false, 'multiple' => true,
'label' => 'label.type', 'required' => false,
'translation_domain' => 'Documents'))
->add('airlines', 'entity', array(
'class' => 'AppBundle:Airline', 'property' => 'id',
'query_builder' => function (EntityRepository $er){
return $er->createQueryBuilder('a')
->addOrderBy('a.id', 'ASC');
},
'choice_value' => 'id',
'choice_label' => 'id', 'label' => 'label.airlines',
'expanded' => false, 'multiple' => true, 'required' => false,
'translation_domain' => 'Documents'))
->add('markets', 'entity', array(
'class' => 'AppBundle:Market', 'property' => 'id',
'query_builder' => function (EntityRepository $er){
return $er->createQueryBuilder('m')
->addOrderBy('m.id', 'ASC');
},
'choice_value' => 'id',
'choice_label' => 'id', 'label' => 'label.markets',
'expanded' => false, 'multiple' => true, 'required' => false,
'translation_domain' => 'Documents'))
->add('documentlist', EntityType::class, array(
'class' => 'DocumentBundle:Document',
'property' => 'name',
'expanded' => false, 'multiple' => true,
'label' => 'label.document_list',
'empty_value' => "Select document",
'required' => false,
'mapped' => false,
'translation_domain' => 'Documents'));
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($builder)
{
$form = $event->getForm();
$data = $event->getData();
$markets = $data['markets'];
$type = $data['type'];
$airlines = $data['airlines'];
dump($markets, $type);
$builder
->add('documentlist', EntityType::class, array(
'class' => 'DocumentBundle:Document',
'property' => 'name',
'expanded' => false, 'multiple' => true,
'label' => 'label.document_list',
'empty_value' => "Select document",
'required' => false,
'mapped' => false,
'translation_domain' => 'Documents',
'query_builder' => function (EntityRepository $er) use ($markets, $type, $airlines){
return $er->createQueryBuilder('e')
->where('e.markets = :markets')
->andWhere('e.airlines IN (:airlines)')
->andWhere('e.products IN (:products)')
->setParameter('e.markets', $markets)
->setParameter('e.airlines', $airlines)
->setParameter('e.type', $type);
},
));
});
}
public function getName()
{
return 'document_deactivation';
}
}
You cannot change the form (add or remove fields) in a POST_SUBMIT event. But you can in a PRE_SUBMIT event, so you just need to change POST_SUBMIT with PRE_SUBMIT.
But be careful because your form data won't be normalized in PRE_SUBMIT, so you will have to work with raw data from your form (an array), or to normalize manually your data.

Field with query should not be blank

How do I add validation constraints "Field is required" in symfony2 PostType class? Any suggestions? I am new in SF2 and I'm just editing what has been done by previous developer.
use Symfony\Component\Validator\Constraints\NotBlank;
class BlogPostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$blogPostCategories = BlogPostCategoryQuery::create()
->filterByBlogPost($builder->getData())
->find();
$categoryIds = array();
foreach ($blogPostCategories as $blogPostCategory) {
$categoryIds[] = $blogPostCategory->getCategory()->getId();
}
$queryOptions = array(
'option_status' => Categorypeer::STATUS_ACTIVE,
'option_category_ids' => $categoryIds
);
$categories = CategoryQuery::create()
->filterActiveCategoriesByOptions($queryOptions)
->find();
$builder->add('category_ids', 'model', array(
'label' => 'Category',
'mapped' => false,
'class' => 'Deal\MainBundle\Model\Category',
'query' => CategoryQuery::create()
->filterActiveCategoriesByOptions()
->orderByName(),
'property' => 'name',
'empty_value' => 'Select categories',
'empty_data' => null,
'required' => true,
'multiple' => true,
'data' => $categories,
'constraints' => array(
new NotBlank(array(
'message' => 'Your message can not be blank! Ouch!'
)),
)
));
Thank you
You should set required => true for this type from the parent form when calling (that's the form type that uses your BlogPostType):
$formBuilder->add('whatever', BlogPostType::class, ['required' => true]);
Also, you could set required = true by default for BlogPostType:
class BlogPostType extends AbstractType
{
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'required' => true
]);
}
}
You can do it with constraints key. Like this:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('message', TextareaType::class, array(
'required' => true,
'constraints' => array(
new NotBlank(array(
'message' => 'Your message can not be blank! Ouch!'
)),
)
))
;
}
do not forget to add uses:
use Symfony\Component\Validator\Constraints\NotBlank;

Symfony 2.8 - FormBuilder : why field becomes required when I define its type?

I'm building a form like with two non mandatory fileds :
$form = $this->createFormBuilder($contact);
$form->add('name');
$form->add('subject', TextType::class);
$form->getForm();
After rendering the first field is not required (it's normal) but why the second is ?! What's wrong with this code ?
Thanks :)
The problem must be the related entity to this form. Are name and subject nullable?. If no ORM configured then you need to manually set the required attribute to each form field. Look the example of a contact form without ORM.
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('fullName', null, array(
'required' => true,
'attr' => array(
'placeholder' => 'Name',
'class' => 'text gradient'
)))
->add('email','email', array(
'required' => true,
'attr' => array(
'placeholder' => 'Email',
'class' => 'text gradient'
)))
->add('subject', null, array(
'required' => true,
'attr' => array(
'placeholder' => 'Subject',
'class' => 'text gradient'
)))
->add('body', 'textarea', array(
'required' => true,
'attr' => array(
'placeholder' => 'Message',
'class' => 'text gradient'
)));
}
required default value is defined in type class method configureOptions()
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'required' => true,
));
}
and in all parents for this type (parent is defined by getParent() method)
first parent is Symfony\Component\Form\Extension\Core\Type\FormType and there required default value is defined as true, to it is strange that first input is not required.
you can define required while adding new element $form->add('subject', TextType::class, array('required' => false));

Complex query in Symfony2 form using query builder

I'm trying to build some kind of complex query using Doctrine Query Builder to use them in a Form Type, see below what I have done:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('category', 'entity', array(
'class' => 'CategoryBundle:Category',
'property' => 'name',
'required' => false,
'multiple' => true,
'expanded' => false,
'query_builder' => function(EntityRepository $er) {
$qb = $er->createQueryBuilder('c')
->where($qb->expr()->eq('c.parent', '?1'), $qb->expr()->isNull('c.parent'))
->setParameter(1, 0);
}
))
->add('detail_group', 'entity', array('class' => 'ProductBundle:DetailGroup', 'property' => 'name', 'required' => false, 'multiple' => true, 'expanded' => false))
->add('parent', 'entity', array('class' => 'ProductBundle:ProductDetail', 'property' => 'label', 'required' => false))
->add('label')
->add('field_type', 'choice', ['choices' => \ProductBundle\DBAL\Types\FieldType::getChoices()])
->add('values_text', 'collection', array('type' => 'text', 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false))
->add('description', 'text', array('required' => false))
->add('measure_unit', 'text', array('required' => false))
->add('status', 'choice', ['choices' => \ProductBundle\DBAL\Types\StatusType::getChoices()])
->add('to_product', 'checkbox', array('label' => 'Detalle de Stock?', 'required' => false));
}
I need to get in that query all the rows from category table with parent=NULL or parent=0 but it's not working since I get this error:
FatalErrorException: Error: Call to a member function expr() on a
non-object in
/var/www/html/src/ProductBundle/Form/ProductDetailType.php line
22
What I'm doing wrong?
It's because $qb doesn't exists.
$qb = $er->createQueryBuilder('c');
$qb->where($qb->expr()->eq('c.parent', '?1'), $qb->expr()->isNull('c.parent'))
->setParameter(1, 0);

Label not replaced with correct value in prototype from sonata admin bundle collection field

My collection is made of this type
<?php
namespace Gustaw\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AttributeValueType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('value')
->add('translations', 'a2lix_translations');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Gustaw\AdminBundle\Entity\AttributeValue',
'label' => false,
));
}
public function getName()
{
return 'attribute_value_type';
}
}
And this is my form
public function configureFormFields(FormMapper $formMapper) {
$formMapper->with('General')
->add('name', null, array('required' => true))
->add('translations', 'a2lix_translations', array(
'by_reference' => false,
'fields' => array(
'name' => array()
)
))
->add('custom', null, array(
'required' => false,
))
->add('category', 'entity', array(
'required' => true,
'class' => 'GustawAdminBundle:Category',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.root', 'ASC')
->addOrderBy('c.lft', 'ASC');
},))
->end()
->with('Values')
//->add('values', 'sonata_type_collection')
->add('notcustomvalues', 'collection', array(
'type' => new AttributeValueType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'label' => false,
'required' => false,
))
->end();
}
Problem is when adding new elements to collection. Each single AttributeValueType gets a label "__name__label__ *" when I don't want to have any label for this field as I set it to false.
I tried setting "prototype_name" hoping it will change something just to make it worse.
The only ideas that came to my mind are:
1st - create custom theme without label just for this one collection
2nd - edit base.js in SonataAdminBundle
2nd obviously is not really good option so I am left just with the first one.
Question is: Are there any other options I have?
Try to add: 'options' => array(label => 'Some Label');
Like this:
->add('notcustomvalues', 'collection', array(
'type' => new AttributeValueType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'label' => false,
'required' => false,
'options' => array(
'label' => 'Some Label'
),
))

Resources