69

1.概要

1.1目標

私が達成しようとしているのは、ユーザーの作成/編集ツールです。編集可能なフィールドは次のとおりです。

  • ユーザー名(タイプ:テキスト)
  • plainPassword(タイプ:パスワード)
  • メール(タイプ:メール)
  • グループ(タイプ:コレクション)
  • avoRoles(タイプ:コレクション)

注:私のUserクラスがFOSUserBundleのUserクラスを拡張していて、ロールを上書きするとさらに問題が発生するため、最後のプロパティは$rolesという名前ではありません。それらを回避するために、ロールのコレクションを$avoRolesの下に保存することにしました。

1.2ユーザーインターフェース

私のテンプレートは2つのセクションで構成されています。

  1. ユーザーフォーム
  2. $ userRepository-> findAllRolesExceptOwnedByUser($ user);を表示するテーブル

注:findAllRolesExceptOwnedByUser()はカスタムリポジトリ関数であり、すべてのロール($ userにまだ割り当てられていないロール)のサブセットを返します。

1.3必要な機能

1.3.1役割の追加:

    ユーザーがロールテーブルの[+](追加)ボタンをクリック  
    する、jqueryはその行をロールテーブルから削除し、  
     jqueryは新しいリストアイテムをユーザーフォーム( avoRoles  リスト)に追加します

1.3.2役割の削除:

    ユーザーがユーザーフォーム( avoRolesリスト)の[x](削除)ボタンをクリック  
    する、jqueryはそのリストアイテムをユーザーフォーム(avoRolesリスト)から削除し、  
     jquery  は新しい行をロールテーブルに追加します

1.3.3変更を保存します。

    ユーザーが[ Zapisz ](保存)ボタンをクリック  
    すると、ユーザーフォームはすべてのフィールド(ユーザー名、パスワード、電子メール、avoRoles、グループ)を送信  
    し、 avoRoles  をロールエンティティのArrayCollectionとして保存し(ManyToManyリレーション)  
     、グループをロールエンティティのArrayCollection  として保存します( ManyToMany関係)  

注:ユーザーに割り当てることができるのは、既存の役割とグループのみです。何らかの理由でそれらが見つからない場合、フォームは検証されません。


2.コード

このセクションでは、このアクションの背後にあるコードを紹介します。説明が不十分で、コードを確認する必要がある場合は、教えてください。貼り付けます。不要なコードでスパムを送信することを避けるために、そもそもすべてを貼り付けるわけではありません。

2.1ユーザークラス

My Userクラスは、FOSUserBundleユーザークラスを拡張します。

namespace Avocode\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Avocode\CommonBundle\Collections\ArrayCollection;
use Symfony\Component\Validator\ExecutionContext;

/**
 * @ORM\Entity(repositoryClass="Avocode\UserBundle\Repository\UserRepository")
 * @ORM\Table(name="avo_user")
 */
class User extends BaseUser
{
    const ROLE_DEFAULT = 'ROLE_USER';
    const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN';

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\generatedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Group")
     * @ORM\JoinTable(name="avo_user_avo_group",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
     * )
     */
    protected $groups;

    /**
     * @ORM\ManyToMany(targetEntity="Role")
     * @ORM\JoinTable(name="avo_user_avo_role",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     * )
     */
    protected $avoRoles;

    /**
     * @ORM\Column(type="datetime", name="created_at")
     */
    protected $createdAt;

    /**
     * User class constructor
     */
    public function __construct()
    {
        parent::__construct();

        $this->groups = new ArrayCollection();        
        $this->avoRoles = new ArrayCollection();
        $this->createdAt = new \DateTime();
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set user roles
     * 
     * @return User
     */
    public function setAvoRoles($avoRoles)
    {
        $this->getAvoRoles()->clear();

        foreach($avoRoles as $role) {
            $this->addAvoRole($role);
        }

        return $this;
    }

    /**
     * Add avoRole
     *
     * @param Role $avoRole
     * @return User
     */
    public function addAvoRole(Role $avoRole)
    {
        if(!$this->getAvoRoles()->contains($avoRole)) {
          $this->getAvoRoles()->add($avoRole);
        }

        return $this;
    }

    /**
     * Get avoRoles
     *
     * @return ArrayCollection
     */
    public function getAvoRoles()
    {
        return $this->avoRoles;
    }

    /**
     * Set user groups
     * 
     * @return User
     */
    public function setGroups($groups)
    {
        $this->getGroups()->clear();

        foreach($groups as $group) {
            $this->addGroup($group);
        }

        return $this;
    }

    /**
     * Get groups granted to the user.
     *
     * @return Collection
     */
    public function getGroups()
    {
        return $this->groups ?: $this->groups = new ArrayCollection();
    }

    /**
     * Get user creation date
     *
     * @return DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }
}

2.2ロールクラス

私のロールクラスはSymfonyセキュリティコンポーネントのコアロールクラスを拡張します。

namespace Avocode\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Avocode\CommonBundle\Collections\ArrayCollection;
use Symfony\Component\Security\Core\Role\Role as BaseRole;

/**
 * @ORM\Entity(repositoryClass="Avocode\UserBundle\Repository\RoleRepository")
 * @ORM\Table(name="avo_role")
 */
class Role extends BaseRole
{    
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\generatedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", unique="TRUE", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $module;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * Role class constructor
     */
    public function __construct()
    {
    }

    /**
     * Returns role name.
     * 
     * @return string
     */    
    public function __toString()
    {
        return (string) $this->getName();
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Role
     */
    public function setName($name)
    {      
        $name = strtoupper($name);
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set module
     *
     * @param string $module
     * @return Role
     */
    public function setModule($module)
    {
        $this->module = $module;

        return $this;
    }

    /**
     * Get module
     *
     * @return string 
     */
    public function getModule()
    {
        return $this->module;
    }

    /**
     * Set description
     *
     * @param text $description
     * @return Role
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return text 
     */
    public function getDescription()
    {
        return $this->description;
    }
}

2.3グループクラス

グループでも役割と同じ問題があるので、ここではスキップします。役割が機能するようになれば、グループでも同じことができることがわかります。

2.4コントローラー

namespace Avocode\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContext;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Avocode\UserBundle\Entity\User;
use Avocode\UserBundle\Form\Type\UserType;

class UserManagementController extends Controller
{
    /**
     * User create
     * @Secure(roles="ROLE_USER_ADMIN")
     */
    public function createAction(Request $request)
    {      
        $em = $this->getDoctrine()->getEntityManager();

        $user = new User();
        $form = $this->createForm(new UserType(array('password' => true)), $user);

        $roles = $em->getRepository('AvocodeUserBundle:User')
                    ->findAllRolesExceptOwned($user);
        $groups = $em->getRepository('AvocodeUserBundle:User')
                    ->findAllGroupsExceptOwned($user);

        if($request->getMethod() == 'POST' && $request->request->has('save')) {
            $form->bindRequest($request);

            if($form->isValid()) {
                /* Persist, flush and redirect */
                $em->persist($user);
                $em->flush();
                $this->setFlash('avocode_user_success', 'user.flash.user_created');
                $url = $this->container->get('router')->generate('avocode_user_show', array('id' => $user->getId()));

                return new RedirectResponse($url);
            }
        }

        return $this->render('AvocodeUserBundle:UserManagement:create.html.twig', array(
          'form' => $form->createView(),
          'user' => $user,
          'roles' => $roles,
          'groups' => $groups,
        ));
    }
}

2.5カスタムリポジトリ

これらは正常に機能するため、これを投稿する必要はありません。すべてのロール/グループ(ユーザーに割り当てられていないもの)のサブセットを返します。

2.6 UserType

ユーザータイプ:

namespace Avocode\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UserType extends AbstractType
{    
    private $options; 

    public function __construct(array $options = null) 
    { 
        $this->options = $options; 
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('username', 'text');

        // password field should be rendered only for CREATE action
        // the same form type will be used for EDIT action
        // thats why its optional

        if($this->options['password'])
        {
          $builder->add('plainpassword', 'repeated', array(
                        'type' => 'text',
                        'options' => array(
                          'attr' => array(
                            'autocomplete' => 'off'
                          ),
                        ),
                        'first_name' => 'input',
                        'second_name' => 'confirm', 
                        'invalid_message' => 'repeated.invalid.password',
                     ));
        }

        $builder->add('email', 'email', array(
                        'trim' => true,
                     ))

        // collection_list is a custom field type
        // extending collection field type
        //
        // the only change is diffrent form name
        // (and a custom collection_list_widget)
        // 
        // in short: it's a collection field with custom form_theme
        // 
                ->add('groups', 'collection_list', array(
                        'type' => new GroupNameType(),
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => true,
                        'error_bubbling' => false,
                        'prototype' => true,
                     ))
                ->add('avoRoles', 'collection_list', array(
                        'type' => new RoleNameType(),
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => true,
                        'error_bubbling' => false,
                        'prototype' => true,
                     ));
    }

    public function getName()
    {
        return 'avo_user';
    }

    public function getDefaultOptions(array $options){

        $options = array(
          'data_class' => 'Avocode\UserBundle\Entity\User',
        );

        // adding password validation if password field was rendered

        if($this->options['password'])
          $options['validation_groups'][] = 'password';

        return $options;
    }
}

2.7 RoleNameType

このフォームは次のようにレンダリングすることになっています。

  • 非表示の役割ID
  • ロール名(読み取り専用)
  • 非表示のモジュール(読み取り専用)
  • 非表示の説明(読み取り専用)
  • (x)ボタンを削除

モジュールと説明は非表示フィールドとしてレンダリングされます。これは、管理者がユーザーからロールを削除するときに、そのロールをjQueryによってロールテーブルに追加する必要があるためです。このテーブルにはモジュールと説明の列があります。

namespace Avocode\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class RoleNameType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder            
            ->add('', 'button', array(
              'required' => false,
            ))  // custom field type rendering the "x" button

            ->add('id', 'hidden')

            ->add('name', 'label', array(
              'required' => false,
            )) // custom field type rendering <span> item instead of <input> item

            ->add('module', 'hidden', array('read_only' => true))
            ->add('description', 'hidden', array('read_only' => true))
        ;        
    }

    public function getName()
    {
        // no_label is a custom widget that renders field_row without the label

        return 'no_label';
    }

    public function getDefaultOptions(array $options){
        return array('data_class' => 'Avocode\UserBundle\Entity\Role');
    }
}

3.現在/既知の問題

3.1ケース1:上記で引用した構成

上記の構成はエラーを返します:

Property "id" is not public in class "Avocode\UserBundle\Entity\Role". Maybe you should create the method "setId()"?

ただし、IDのセッターは必要ありません。

  1. まず、新しい役割を作成したくないからです。既存のロールエンティティとユーザーエンティティの間に関係を作成したいだけです。
  2. 新しいロールを作成したい場合でも、そのIDは自動生成される必要があります。

    / **

    • @ ORM \ Id
    • @ORM \ Column(type = "integer")
    • @ORM \generatedValue(strategy = "AUTO")*/保護された$id;

3.2ケース2:ロールエンティティにIDプロパティのセッターを追加

間違っていると思いますが、念のためにやりました。このコードをロールエンティティに追加した後:

public function setId($id)
{
    $this->id = $id;
    return $this;
}

新しいユーザーを作成して役割を追加すると、保存...どうなりますか?

  1. 新しいユーザーが作成されます
  2. 新しいユーザーには、目的のIDが割り当てられた役割があります(イェーイ!)
  3. しかし、その役割の名前は空の文字列で上書きされます(残念!)

明らかに、それは私が望んでいることではありません。役割を編集/上書きしたくありません。それらとユーザーの間に関係を追加したいだけです。

3.3ケース3:Jeppeによって提案された回避策

この問題に最初に遭遇したとき、Jeppeが提案したのと同じ回避策に行き着きました。今日(他の理由で)フォーム/ビューを作り直す必要があり、回避策が機能しなくなりました。

Case3 UserManagementController-> createActionの変更点:

  // in createAction
  // instead of $user = new User
  $user = $this->updateUser($request, new User());

  //and below updateUser function


    /**
     * Creates mew iser and sets its properties
     * based on request
     * 
     * @return User Returns configured user
     */
    protected function updateUser($request, $user)
    {
        if($request->getMethod() == 'POST')
        {
          $avo_user = $request->request->get('avo_user');

          /**
           * Setting and adding/removeing groups for user
           */
          $owned_groups = (array_key_exists('groups', $avo_user)) ? $avo_user['groups'] : array();
          foreach($owned_groups as $key => $group) {
            $owned_groups[$key] = $group['id'];
          }

          if(count($owned_groups) > 0)
          {
            $em = $this->getDoctrine()->getEntityManager();
            $groups = $em->getRepository('AvocodeUserBundle:Group')->findById($owned_groups);
            $user->setGroups($groups);
          }

          /**
           * Setting and adding/removeing roles for user
           */
          $owned_roles = (array_key_exists('avoRoles', $avo_user)) ? $avo_user['avoRoles'] : array();
          foreach($owned_roles as $key => $role) {
            $owned_roles[$key] = $role['id'];
          }

          if(count($owned_roles) > 0)
          {
            $em = $this->getDoctrine()->getEntityManager();
            $roles = $em->getRepository('AvocodeUserBundle:Role')->findById($owned_roles);
            $user->setAvoRoles($roles);
          }

          /**
           * Setting other properties
           */
          $user->setUsername($avo_user['username']);
          $user->setEmail($avo_user['email']);

          if($request->request->has('generate_password'))
            $user->setPlainPassword($user->generateRandomPassword());  
        }

        return $user;
    }

残念ながら、これによって何も変更されません。結果は、CASE1(IDセッターなし)またはCASE2(IDセッターあり)のいずれかになります。

3.4ケース4:ユーザーフレンドリーによって提案されたように

マッピングにcascade={"persist"、"remove"}を追加します。

/**
 * @ORM\ManyToMany(targetEntity="Group", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="avo_user_avo_group",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
 * )
 */
protected $groups;

/**
 * @ORM\ManyToMany(targetEntity="Role", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="avo_user_avo_role",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
 * )
 */
protected $avoRoles;

そして、FormTypeでby_referencefalseに変更します。

// ...

                ->add('avoRoles', 'collection_list', array(
                        'type' => new RoleNameType(),
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => false,
                        'error_bubbling' => false,
                        'prototype' => true,
                     ));

// ...

そして、3.3で提案された回避策コードを維持することは何かを変えました:

  1. ユーザーとロールの関連付けは作成されませんでした
  2. ..しかし、ロールエンティティの名前は空の文字列で上書きされました(3.2のように)

だから..それは何かを変えましたが、間違った方向に。

4.バージョン

4.1 Symfony2 v2.0.15

4.2 Doctrine2 v2.1.7

4.3 FOSUserBundleバージョン:6fb81861d84d460f1d070ceb8ec180aac841f7fa

5.まとめ

私は多くの異なるアプローチを試しましたが(上記は最新のもののみです)、コードの研究、グーグル、答えの検索に何時間も費やした後、これを機能させることができませんでした。

どんな助けでも大歓迎です。あなたが何かを知る必要があるなら、私はあなたが必要とするコードのどんな部分でも投稿します。

4

5 に答える 5

8

1. 回避策

Jeppe Marianger-Lam によって提案された回避策は、現時点で私が知っている唯一のものです。

1.1 私の場合、なぜ動かなくなったのですか?

RoleNameType を(他の理由で)次のように変更しました。

  • ID(非表示)
  • 名前 (カスタム タイプ - ラベル)
  • モジュールと説明 (非表示、読み取り専用)

問題は、カスタム タイプ ラベルが NAME プロパティを次のようにレンダリングしたことでした。

    <span> 役割名 </span>

また、「読み取り専用」ではないため、FORM コンポーネントは POST で NAME を取得することを期待していました。

代わりに ID のみが POST されたため、FORM コンポーネントは NAME が NULL であると想定していました。

これにより、ケース 2 (3.2) -> 関連付けが作成されますが、ROLE NAME が空の文字列で上書きされます。

2. では、この回避策とは正確には何ですか?

2.1 コントローラー

この回避策は非常に簡単です。

コントローラーでは、フォームを検証する前に、投稿されたエンティティ識別子をフェッチし、一致するエンティティを取得してから、それらをオブジェクトに設定する必要があります。

// example action
public function createAction(Request $request)
{      
    $em = $this->getDoctrine()->getEntityManager();

    // the workaround code is in updateUser function
    $user = $this->updateUser($request, new User());

    $form = $this->createForm(new UserType(), $user);

    if($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if($form->isValid()) {
            /* Persist, flush and redirect */
            $em->persist($user);
            $em->flush();
            $this->setFlash('avocode_user_success', 'user.flash.user_created');
            $url = $this->container->get('router')->generate('avocode_user_show', array('id' => $user->getId()));

            return new RedirectResponse($url);
        }
    }

    return $this->render('AvocodeUserBundle:UserManagement:create.html.twig', array(
      'form' => $form->createView(),
      'user' => $user,
    ));
}

そして、updateUser 関数の回避策コードの下:

protected function updateUser($request, $user)
{
    if($request->getMethod() == 'POST')
    {
      // getting POSTed values
      $avo_user = $request->request->get('avo_user');

      // if no roles are posted, then $owned_roles should be an empty array (to avoid errors)
      $owned_roles = (array_key_exists('avoRoles', $avo_user)) ? $avo_user['avoRoles'] : array();

      // foreach posted ROLE, get it's ID
      foreach($owned_roles as $key => $role) {
        $owned_roles[$key] = $role['id'];
      }

      // FIND all roles with matching ID's
      if(count($owned_roles) > 0)
      {
        $em = $this->getDoctrine()->getEntityManager();
        $roles = $em->getRepository('AvocodeUserBundle:Role')->findById($owned_roles);

        // and create association
        $user->setAvoRoles($roles);
      }

    return $user;
}

これが機能するには、SETTER (この場合は User.php エンティティ) が次のようになっている必要があります。

public function setAvoRoles($avoRoles)
{
    // first - clearing all associations
    // this way if entity was not found in POST
    // then association will be removed

    $this->getAvoRoles()->clear();

    // adding association only for POSTed entities
    foreach($avoRoles as $role) {
        $this->addAvoRole($role);
    }

    return $this;
}

3. 最終的な考え

それでも、この回避策はその仕事をしていると思います

$form->bindRequest($request);

するべきです!私が何か間違ったことをしているのか、symfony の Collection フォームタイプが完全ではありません。

symfony 2.1 ではForm コンポーネントに大きな変更がいくつかありますが、これが修正されることを願っています。

PS。私が悪いことをしているのなら...

...それが行われるべき方法を投稿してください! 迅速で簡単で「クリーンな」ソリューションを見つけていただければ幸いです。

PS2。特別な感謝:

Jeppe Marianger-Lam とユーザーフレンドリー (IRC の #symfony2 から)。大変お世話になりました。乾杯!

于 2012-06-19T09:03:47.597 に答える
6

これは私が以前に行ったことです - それが「正しい」方法であるかどうかはわかりませんが、うまくいきます。

送信されたフォームから結果を取得したら (つまり、直前または直後if($form->isValid()))、ロールのリストを確認し、エンティティからロールをすべて削除します (リストを変数として保存します)。このリストを使用して、それらすべてをループし、ID に一致するロール エンティティをリポジトリに問い合わせて、これらをユーザー エンティティに追加してpersistからflush.

prototypeフォームコレクションについて何かを思い出したので、Symfony2 のドキュメントを検索したところ、これが見つかりました: http://symfony.com/doc/current/cookbook/form/form_collections.htmlフォーム内のコレクション タイプの JavaScript の追加と削除。おそらく最初にこのアプローチを試してから、うまくいかない場合は後で上で述べたことを試してください:)

于 2012-06-18T20:04:09.177 に答える
0

さらにいくつかのエンティティが必要です:
USER
id_user (タイプ: 整数)
ユーザー名 (タイプ: テキスト)
plainPassword (タイプ: パスワード)
電子メール (タイプ: 電子メール)


GROUPS
id_group (型: 整数)
説明 (型: テキスト)


AVOROLES
id_avorole (型: 整数) descripcion (
型: テキスト)


* USER_GROUP*
id_user_group (type:integer)
id_user (type:integer) (これはユーザー エンティティの ID)
id_group (type:integer) (これはグループ エンティティの ID)


* USER_AVOROLES*
id_user_avorole (type:integer)
id_user (type:integer) (これはユーザー エンティティの ID)
id_avorole (type:integer) (これは avorole エンティティの ID)


たとえば、次のようなものを使用できます:
user:
id: 3
username: john
plainPassword: johnpw
email: john@email.com


グループ:
id_group: 5 説明
: グループ 5


user_group:
id_user_group: 1
id_user: 3
id_group: 5
*このユーザーは複数のグループを持つことができるため、別の行に*

于 2013-11-21T13:26:12.570 に答える