Symfony2 FOSUserBundle重写Form

默认的form包含注册用户,修改用户信息,修改密码等等,如果想对User追加属性,或者追加追加一部分功能,那就需要重写form。

 

  •  创建如下的ORM User类,追加属性name
<?php
// src/Acme/UserBundle/Entity/User.php

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

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

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @Assert\NotBlank(message="Please enter your name.", groups={"Registration", "Profile"})
     * @Assert\MinLength(limit="3", message="The name is too short.", groups={"Registration", "Profile"})
     * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
     */
    protected $name;

    // ...
}

* 默认情况下,新用户注册时会调用注册验证配置文件,如果需要对name属性做验证,请确保验证文件已经加入name属性。

 

  • 例如追加name属性,可以进行下边修改
    <?php
    // src/Acme/UserBundle/Form/Type/RegistrationFormType.php
    
    namespace Acme\UserBundle\Form\Type;
    
    use Symfony\Component\Form\FormBuilderInterface;
    use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
    
    class RegistrationFormType extends BaseType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            parent::buildForm($builder, $options);
    
            // add your custom field
            $builder->add('name');
        }
    
        public function getName()
        {
            return 'acme_user_registration';
        }
    }
     
  • 修改service.yml配置文件
    # src/Acme/UserBundle/Resources/config/services.yml
    services:
        acme_user.registration.form.type:
            class: Acme\UserBundle\Form\Type\RegistrationFormType
            arguments: [%fos_user.model.user.class%]
            tags:
                - { name: form.type, alias: acme_user_registration }
     
  • 修改config.yml配置文件
    # app/config/config.yml
    fos_user:
        # ...
        registration:
            form:
                type: acme_user_registration
     

你可能感兴趣的:(Bundle)