vimuth vimuth - 6 months ago 129
PHP Question

Use dropdown for Fos User bundle roles field in sonata admin

I'm using sonata admin to create an admin panel for FOS USER bundle users. And I need to use a drop down for 'roles' filed.

This is my admin class,

<?php

namespace AdminBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;

class UserAdmin extends Admin {

protected function configureFormFields(FormMapper $formMapper) {
$formMapper->add('name', 'text');
$formMapper->add('surname', 'text');
$formMapper->add('username', 'text');
$formMapper->add('email', 'text');
$formMapper->add('telephone', 'text');
$formMapper->add('password', 'text');
$formMapper->add('roles', 'choice', array(
'choices' => array(
'Admin' => 'a:1:{i:0;s:10:"ROLE_ADMIN";}',
'User' => 'a:0:{}',
),
'choices_as_values' => true,
));
}


But I'm getting this error,


Notice: Array to string conversion 500 Internal Server Error -
ContextErrorException


I think this is the part witch gives an error,

$formMapper->add('roles', 'choice', array(
'choices' => array(
'Admin' => 'a:1:{i:0;s:10:"ROLE_ADMIN";}',
'User' => 'a:0:{}',
),
'choices_as_values' => true,
));

Answer

This a:1:{i:0;s:10:"ROLE_ADMIN";} is indeed an array (serialized). So you have to give a string representation of that, changing it in

$formMapper->add('roles', 'choice', array(
    'choices' => array(
        'Admin' => 'ROLE_ADMIN',
        'User' => '',
        ),
    'choices_as_values' => true,
));

or something like that.

BTW as soon as you'll post that, you may need to manipulate your data manually as I'm not aware here how that field mapping is going to be tackle by the framework.

What I can suggest, if no auto-magic happens, is to write your custom FormType to handle that situation.

Comments