userinterface password form forms symfony roles

forms - password - symfony security form



Symfony2-error de conversión de matriz a cadena (4)

Asegúrese de utilizar el tipo de datos adecuado en el archivo ORM. En este caso, su campo de rol no puede ser cadena. Debe ser una relación de muchos a muchos, array o json_array.

Si eliges uno de ellos, Symfony insertará los datos sin esfuerzo o cualquier tipo de transformador.

P.ej:

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

Así, vivirá en su base de datos como:

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

He leído las otras asignaturas, pero no resuelve mi problema, así que:

tengo esto

->add(''role'', ''choice'', array( ''label'' => ''I am:'', ''mapped'' => true, ''expanded'' => true, ''multiple'' => false, ''choices'' => array( ''ROLE_NORMAL'' => ''Standard'', ''ROLE_VIP'' => ''VIP'', ) ))

Y todo lo que hago, me sale este error:

Notice: Array to string conversion in C:/xampp/htdocs/xxx/vendor/symfony/symfony /src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 458

En mi tipo de formulario, el método setRole ni siquiera se llama (cuando cambio el nombre a alguna basura, el error sigue ocurriendo). ¿Por qué está pasando esto?

// EDITAR

Rastreo de pila completa:

in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php at line 458 - */ protected function fixIndex($index) { if (is_bool($index) || (string) (int) $index === (string) $index) { return (int) $index; } at ErrorHandler ->handle (''8'', ''Array to string conversion'', ''C:/xampp/htdocs /xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php'', ''458'', array(''index'' => array())) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php at line 458 + at ChoiceList ->fixIndex (array()) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php at line 476 + at ChoiceList ->fixIndices (array(array())) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/SimpleChoiceList.php at line 152 + at SimpleChoiceList ->fixChoices (array(array())) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php at line 204 + at ChoiceList ->getIndicesForChoices (array(array())) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/DataTransformer/ChoiceToBooleanArrayTransformer.php at line 63 + at ChoiceToBooleanArrayTransformer ->transform (array()) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php at line 1019 + at Form ->normToView (array()) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php at line 332 + at Form ->setData (array()) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php at line 59 + at PropertyPathMapper ->mapDataToForms (object(User), object(RecursiveIteratorIterator)) in C:/xampp/htdocs/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php at line 375 + at Form ->setData (object(User)) in C:/xampp/htdocs/xxx/vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Controller/RegistrationController.php at line 49 + at RegistrationController ->registerAction (object(Request)) at call_user_func_array (array(object(RegistrationController), ''registerAction''), array(object(Request))) in C:/xampp/htdocs/xxx/app/bootstrap.php.cache at line 2770 + at HttpKernel ->handleRaw (object(Request), ''1'') in C:/xampp/htdocs/xxx/app/bootstrap.php.cache at line 2744 + at HttpKernel ->handle (object(Request), ''1'', true) in C:/xampp/htdocs/xxx/app/bootstrap.php.cache at line 2874 + at ContainerAwareHttpKernel ->handle (object(Request), ''1'', true) in C:/xampp/htdocs/xxx/app/bootstrap.php.cache at line 2175 + at Kernel ->handle (object(Request)) in C:/xampp/htdocs/xxx/web/app_dev.php at line 29 +


Simplemente agrego un DataTransformer sin cambiar el tipo de matriz de mi atributo de roles y luego lo coloco en mi UserType:

use AppBundle/Form/DataTransformer/StringToArrayTransformer; //... $transformer = new StringToArrayTransformer(); $builder->get(''roles'')->addModelTransformer($transformer);

Y funciona para mi.


Symfony está intentando convertir tu rol $ (propiedad de matriz) en un campo de opción múltiple (cadena).

Hay varias maneras de lidiar con este problema:

  1. Establezca múltiplo en verdadero en su widget de formulario de elección.
  2. Cambie la asignación de la matriz a la cadena para la propiedad $ role en su entidad.
  3. Si insiste en que las opciones anteriores no se hayan modificado, puede crear DataTransformer. Esa no es la mejor solución porque perderá datos si su matriz tiene más de 1 elemento .

Ejemplo:

<?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); } }

Y luego en su clase de formulario:

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));

Puede leer más sobre DataTransformers aquí: http://symfony.com/doc/current/cookbook/form/data_transformers.html


Tengo tu problema ... Resolví esto con esta solución. Espero que te ayude

Este código de trabajo está en el formulario de inicio de sesión y registro ...

entidad de usuario

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; }

Tipo de usuario

->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'', ] ))