エンティティ:
ユーザー:
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->__toString()という関数に「Role」の値ではなくオブジェクトが渡されているため、このエラーが発生していると思います。どうすればこの問題を解決できますか?