miltone
miltone

Reputation: 4721

field array type in entity for form choice type field symfony

I would like to create a UserForm for create user in my system backend. I use a entity with a 'role' field as type array I want use a select choice field type Form with that entity field. I use a transformer class system for convert data between Entity and form.

but I turn around in my head and nothing run correctly.

When I use options 'multiple' of choice type, my field display correctly but I don't want to display and select multiple value for this field.

I have Notice: Undefined offset: 0 error or I have ContextErrorException: Notice: Array to string conversion

Here few essential code :

UserForm class

    $builder->add($builder->create('roles', 'choice', array(
    'label' => 'I am:',
    'mapped' => true,
    'expanded' => false,
    'multiple' => false,
    'choices' => array(
        'ROLE_NORMAL' => 'Standard',
        'ROLE_VIP' => 'VIP',
    )
))->addModelTransformer($transformer));

transformer Class

class StringToArrayTransformer implements DataTransformerInterface
{
    public function transform($array)
    {
        return $array[0];
    }

    public function reverseTransform($string)
    {
        return array($string);
    }
}

controller method

$user = new User(); //init entity
$form = $this->createForm(new UserForm(), $user);

$form->handleRequest($request);

if ($form->isValid())
{
    $em = $this->getDoctrine()->getManager();
    $em->persist($form);
    $em->flush();
    return $this->redirect($this->generateUrl('task_success'));
}

entity part

/**
 * @ORM\Column(name="roles", type="array")
 */
protected $roles;

public function getRoles()
{
    return $this->roles;
}
public function setRoles(array $roles)
{
    $this->roles = $roles;
    return $this;
}

My field roles entity must be a array for run correctly the security component Symfony

can you help me to understand why this field form refuse to display ?

I already readed others questions in same issue but there is anything that I don't understand because nothing help me to resolve my problem.

If you can help me with MY particular context...

Thank for support

Upvotes: 4

Views: 15047

Answers (1)

stollr
stollr

Reputation: 7183

because security symfony component integration

If you only need the "getRoles" method because of the interface you are implementing, it is simpler (and cleaner) to do the following:

  • Change the entities field again to role with type string
  • Rename your getter and setter to getRole() and setRole()
  • and add a getRoles method like this:

    public function getRoles()
    {
        return array($this->role);
    }
    
  • In your form type, change the field name to "role" and 'multiple' => false

  • Remove your model transformer

This should be the solution ;)

Upvotes: 3

Related Questions