2017-02-20 11 views
3

User.phpGroup.phpという2つのクラスがfosuserbundleに定義されたクラスから拡張されています。EntityTypeフィールドのデフォルト選択オプション

これ以外にも、私はManyToManyの関係を持っています。

アプリケーションのアイデアは、新しいユーザーを追加するときに、ユーザーに1つまたは複数のグループを割り当てます(私はマテリアルデザインのマルチ選択オプションを使用しています)。ユーザーにグループが割り当てられていない場合(グループオプションが空の場合など)に問題が発生します。

name = 'user [groups] []'の無効なフォームコントロールにはフォーカスが当てられません。

この問題を解決するには、グループフィールドのデフォルト値を指定する必要があります。グループが選択されていない場合のデフォルトユーザーグループの設定方法私のクラスは以下のように定義されています。

UserType.php

public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add(
       'username', 
       null, 
       array(
       'attr' => array(
        'placeholder' => 'username' 
       ), 
      )) 
      ->add(
       'email', 
       null, 
       array(
       'attr' => array(
        'placeholder' => 'email' 
       ), 
      )) 
      /*->add('groups', EntityType::class, array(
       'class' => 'AppBundle\Entity\Group', 
       'choice_label' => 'name', 
       'expanded' => false, 
       'multiple' => false 
      )) */ 
      ->add('groups', EntityType::class, array(
       'class' => 'AppBundle\Entity\Group', 
       'choice_label' => 'name', 
       'attr'=>array(
        'class' => 'mdb-select' 
       ), 
       'multiple' => true, 
      )) 
      ->add('plainPassword', RepeatedType::class, array(
       'invalid_message' => 'Les mots de passe doivent être identiques.', 
       'first_options' => array('label' => 'Mot de passe'), 
       'second_options' => array('label' => 'Répétez le mot de passe'), 
      )) 
      //<input id="input-id" type="file" class="file" multiple data-show-upload="false" data-show-caption="true"> 
      ->add('enabled', null, array(
       'required' => false, 
      )) 
      ->add('imageFile',VichFileType::class, [ 
       'required' => false, 
       'download_link' => true, 
       'attr'=>array(
       'type' => 'file', 
       'onchange' => 'loadFile(event)'), // not mandatory, default is true 
      ]) 
     ; 
    } 

GroupEntity.php

public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name') 
      ->add('roles', CollectionType::class, array(
       'entry_type' => ChoiceType::class, 
       'entry_options' => array(
        'attr' => array(
         'class'=>'mdb-select colorful-select dropdown-default' 
        ), 
        'choices' => array(
         'Admin' => 'ROLE_ADMIN', 
         'USER'  => 'ROLE_USER', 
        ), 
       ) 
      )) 
     ; 
    } 

User.php

<?php 


    namespace AppBundle\Entity; 

    use FOS\UserBundle\Model\User as BaseUser; 
    use Doctrine\ORM\Mapping as ORM; 
    use Doctrine\Common\Collections\ArrayCollection; 
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; 
    use Symfony\Component\HttpFoundation\File\File; 
    use Vich\UploaderBundle\Mapping\Annotation as Vich; 

    /** 
    * @Vich\Uploadable 
    * @ORM\Entity 
    * @ORM\Table(name="fos_user") 
    * @UniqueEntity(fields="usernameCanonical", errorPath="username", message="fos_user.username.already_used", groups={"Default", "Registration", "Profile"}) 
    * @UniqueEntity(fields="emailCanonical", errorPath="email", message="fos_user.email.already_used", groups={"Default", "Registration", "Profile"}) 
    */ 
    class User extends BaseUser { 

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

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

     /** 
     * @ORM\Column(type="integer", length=6, options={"default":0}) 
     */ 
     protected $loginCount = 0; 

     /** 
     * @var \DateTime 
     * 
     * @ORM\Column(type="datetime", nullable=true) 
     */ 
     protected $firstLogin; 
     /** 
     * NOTE: This is not a mapped field of entity metadata, just a simple property. 
     * 
     * @Vich\UploadableField(mapping="user_image", fileNameProperty="imageName") 
     * 
     * @var File 
     */ 
     private $imageFile; 

     /** 
     * @ORM\Column(type="string", length=255,nullable=true) 
     * 
     * @var string 
     */ 
     private $imageName; 

     /** 
     * @ORM\Column(type="datetime",nullable=true) 
     * 
     * @var \DateTime 
     */ 
     private $updatedAt; 


     public function __construct() { 
      parent::__construct(); 
      $this->enabled = true; 
      $this->groups = new ArrayCollection(); 
     } 
    } 

Group.php

namespace AppBundle\Entity; 

use FOS\UserBundle\Model\Group as BaseGroup; 
use Doctrine\ORM\Mapping as ORM; 

/** 
* @ORM\Entity 
* @ORM\Table(name="fos_group") 
*/ 
class Group extends BaseGroup 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User", mappedBy="groups") 
     * 
     * 
     */ 
    protected $users; 

    /** 
    * @var string 
    */ 
    protected $name; 

    /** 
    * @var array 
    */ 
    protected $roles; 

    /** 
    * Group constructor. 
    * 
    * @param string $name 
    * @param array $roles 
    */ 
    public function __construct($name, $roles = array()) 
    { 
     $this->name = $name; 
     $this->roles = $roles; 
    } 

} 

答えて

1

どのグループが存在しない場合は、ユーザーにグループを割り当てるために「POST_SET_DATA」または「PRE_SUBMIT」形式のイベントを追加することによって、それを達成することができますフォームデータに保存します。また、あなたのユーザエンティティ

http://symfony.com/doc/current/doctrine/lifecycle_callbacks.html

または直接あなたのコントローラ(@martinの答え)でオブジェクトを修正

ためのライフサイクルコールバックを使用することができ

$builder->addEventListener(FormEvents::POS_SET_DATA, function (FormEvent $event) { 
     $user = $event->getData(); 
     $form = $event->getForm(); 


     if (!$user->getGroups->count() > 0) { 
      //... 
     } 
    }); 

http://symfony.com/doc/current/form/dynamic_form_modification.html https://symfony.com/doc/current/form/events.html

+0

がu'rのREPONSEのためにあなたに感謝し、私はtは私は私のコンソール内のJavaScriptエラーがあることを言いたい名前を持つ1無効なフォームコントロールを= 'user [groups] []'はフォーカスできません。 – ahmedbhs

+0

奇妙なことに、エラーがどこから来るのかを見つけることができれば、関係するスクリプトを見てください。あなたのフォームリスナーに関連してはいけません。おそらく別の質問をするべきでしょう。他の人が恩恵を受けるように助けてくれたら、私の答えを受け入れるか、またはupvotingしてください。 – Mawcel

+0

お寄せいただきありがとうございます。本当にありがとうございます。 – ahmedbhs

2

フォームの作成時にデフォルトデータを渡す必要があります。お使いのコントローラで例えば、あなたが持っているでしょう: 新しい:

$user = new User(); 
// Add default groups to the $user 
// ... 
$form = $this->createForm(UserType::class, $user); 
$form->handleRequest($request); 

if ($form->isValid()) { 
    $data = $form->getData(); 
    // ... 
} 
+0

返信ありがとうございますので、私のユーザークラスでsetGroups関数が必要です: setGroups(Collection $ groups = null){ if($ groups!== null) $ this-> groups = $ groups;} 次に、あなたが言うように:$ user-> setGroups($ something)); ?? – ahmedbhs

+0

@safeはい、これはあなたが望むものでなければなりません。 '$ user'は' $ form-> submit() 'を呼び出すときに更新されたフォームのデフォルト値です。したがって、送信されたデータにグループが含まれていない場合、デフォルト値のままになります。 – martin

+0

コレクションを初期化する方法は? $ somethingを変更してデフォールトコレクションオブジェクトを設定する必要があります。 – ahmedbhs

関連する問題