Symfony2 - array to string conversion error

给你一囗甜甜゛ 提交于 2019-11-28 07:31:53

Symfony's trying to convert your $role(array property) to not multiple choice field(string).

There's several ways to deal with this problem:

  1. Set multiple to true in your choice form widget.
  2. Change mapping from array to string for $role property in your entity.
  3. If you insist to have above options unchanged, you can create DataTransformer. That's not the best solution because you will lose data if your array have more than 1 element.

Example:

<?php
namespace Acme\DemoBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class StringToArrayTransformer implements DataTransformerInterface
{
    /**
     * Transforms an array to a string. 
     * POSSIBLE LOSS OF DATA
     *
     * @return string
     */
    public function transform($array)
    {
        return $array[0];
    }

    /**
     * Transforms a string to an array.
     *
     * @param  string $string
     *
     * @return array
     */
    public function reverseTransform($string)
    {
        return array($string);
    }
}

And then in your form class:

use Acme\DemoBundle\Form\DataTransformer\StringToArrayTransformer;
/* ... */
$transformer = new StringToArrayTransformer();
$builder->add($builder->create('role', 'choice', array(
                'label' => 'I am:',
                'mapped' => true,
                'expanded' => true,
                'multiple' => false,
                'choices' => array(
                    'ROLE_NORMAL' => 'Standard',
                    'ROLE_VIP' => 'VIP',
                )
              ))->addModelTransformer($transformer));

You can read more about DataTransformers here: http://symfony.com/doc/current/cookbook/form/data_transformers.html

Make sure that you use proper data type in ORM file. In this case, your role field cannot be string. It must be a many-to-many relation, array or json_array.

If you choose one of them, symfony will insert the data without effort or any type of transformer.

E.g.:

// Resources/config/User.orm.yml
fields:
  role:
      type: array
      nullable: false

So, it will live in your database as like:

a:2:{i:0;s:4:"user";i:1;s:5:"admin";}

I just add a DataTransformer without changing the array type of my roles attribute then I put this in my UserType :

use AppBundle\Form\DataTransformer\StringToArrayTransformer;

//...

$transformer = new StringToArrayTransformer();    
$builder->get('roles')->addModelTransformer($transformer);

And it works for me.

I have your problem .. I solved this with this solution. I hope it helps you

this code work's on login and register form ...

user entity

class User {
    /**
     * @ORM\Column(type="array")
     */
    private $roles ;

    public function getRoles()
    {
        $roles = $this->roles;
         var_dump($roles);
        if ($roles != NULL) {
            return explode(" ",$roles);
        }else {
           return $this->roles;
        }
    }


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

UserType

 ->add('roles', ChoiceType::class, array(
            'attr' => array(
                'class' => 'form-control',
                'value' => $options[0]['roles'],
                'required' => false,
            ),
            'multiple' => true,
            'expanded' => true, // render check-boxes
            'choices' => [
                'admin' => 'ROLE_ADMIN',
                'user' => 'ROLE_USER',
            ]
        ))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!