An array field type in essence for a symfony type select field

I would like to create a UserForm to create a user in my system backend. I am using an object with a "role" field as an array of types. I want to use the type of a select type select field with this object field. I use a transformer class system to convert data between Entity and form.

but I turn in my head and nothing works correctly.

When I use the "multiple" options of the select type, my field is displayed correctly, but I do not want to display and select multiple values ​​for this field.

I have a mistake Notice: Undefined offset: 0 or I haveContextErrorException: Notice: Array to string conversion

Here are some essential codes:

Class userform

    $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'));
}

part of the essence

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

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

Symfony

, ?

, -, , .

...

+4
1

symfony

getRoles - , , ( ) :

  • role string
  • getter setter getRole() setRole()
  • getRoles :

    public function getRoles()
    {
        return array($this->role);
    }
    
  • "role" 'multiple' => false

;)

+3

Source: https://habr.com/ru/post/1531223/


All Articles