php - EntityType 字段的默认选择选项

标签 php doctrine-orm symfony symfony-forms

我有两个类 User.phpGroup.php,它们是从 fosuserbundle 中定义的类扩展而来的。

除此之外,我在它们之间有一个 ManyToMany 关系。

该应用程序的想法是,当我添加新用户时,我会为用户分配一个或多个组(我正在使用 Material 设计多选选项)。当用户没有分配任何组时(例如,当组选项为空时),就会出现问题。我在控制台中收到此 javascript 错误:

An invalid form control with name='user[groups][]' is not focusable.

所以要解决这个问题,我需要为组字段提供一个默认值。如果未选择组,如何设置默认用户组?我的类(class)定义如下。

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;
    }

}

最佳答案

创建表单时需要传入默认数据。例如,在您的 Controller 中,您将拥有:

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

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

关于php - EntityType 字段的默认选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42340269/

相关文章:

php - Twig 不更新 symfony 中的更改

symfony - 从服务获取 Symfony 基本 URL?

PHP 启动 : Unable to load dynamic library php_curl. dll

php - 不考虑 PHP 顺序的字符串比较

javascript - 复选框值无法使用 AJAX 正确发送到 PHP

php - 尝试使用 Doctrine2 访问 PostgreSQL 时出现错误 : undefined table,

php - 在数据库中搜索字符串

doctrine-orm - 交响乐与学说 : Optional foreign key

database - 在没有任何过滤器的情况下搜索实体的原则

php - 如何自定义 FOS UserBundle URL