实体:
用户:
class User implements AdvancedUserInterface, \Serializable
{
...
/**
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* @ORM\JoinTable(name="users_roles")
*
*/
private $roles;
...
}
角色:
class Role implements RoleInterface
{
...
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function __toString()
{
return $this->getName();
}
...
}
管理类:
用户管理员:
<?php
namespace Lan\ConsoleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
class UsersAdmin extends Admin
{
protected function configureShowField(ShowMapper $showMapper)
{
$showMapper
->add('id', null, array('label' => 'ID'))
->add('username', null, array('label' => 'Name'))
->add('password', null, array('label' => 'Password'))
->add('email', null, array('label' => 'Mail'))
->add('is_active', null, array('label' => 'Active', 'required' => false))
->add('roles');
}
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('username', null, array('label' => 'Name'))
->add('password', null, array('label' => 'Password'))
->add('email', null, array('label' => 'Mail'))
->add('is_active', 'checkbox', array('label' => 'Active', 'required' => false))
->end()
->with('Roles')
->add('roles', 'sonata_type_model',array('expanded' => true, 'compound' => true, 'multiple' => true))
->end();
}
}
角色管理员:
<?php
namespace Lan\ConsoleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
class RolesAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', null, array('label' => 'Заголовок'))
->add('role', null, array('label' => 'Роль'));
}
}
截图:http: //img577.imageshack.us/img577/3565/jyte.png
更新用户后,我收到此错误消息:
FatalErrorException:错误:在 \vendor\sonata-project\doctrine-orm-admin-bundle\Sonata\DoctrineORMAdminBundle\Model\ModelManager.php 行 560 中的非对象上调用成员函数 add()
我认为发生此错误是因为将对象而不是'Role'值传递给了函数Role-> __toString()。我怎么解决这个问题?