2
votes

I've got a problem when I want to override the FOSUserBundle registration Form.

The deal is, in the User entity, some of the users can have a "Sponsor" (a sponsor is a ManyToOne to the same entity), to be more explicit, this is the User Entity :

<?php

namespace Diz\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

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


    /**
     * create FK "sponsor_id" referenced to the id field on the same table 
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(name="sponsor_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $sponsor;


    public function __construct()
    {
        // import FOSUserBundle properities ->
        parent::__construct();

    }

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

    /**
     * Set sponsor
     *
     * @param Dizsurf\UserBundle\Entity\User $sponsor
     */
    public function setSponsor(\Dizsurf\UserBundle\Entity\User $sponsor)
    {
        $this->sponsor = $sponsor;
    }

    /**
     * Get sponsor
     *
     * @return Dizsurf\UserBundle\Entity\User 
     */
    public function getSponsor()
    {
        return $this->sponsor;
    }

}

You see ?

Then, to override the RegistrationFormType, I've created one with the official help :

<?php

namespace Diz\UserBundle\Form\Type;

use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilder $builder, array $options)
    {

        parent::buildForm($builder, $options);

        // add your custom field
        $builder->add('sponsor', 'fos_user_username');

    }

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

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Diz\UserBundle\Entity\User', // Ni de modifier la classe ici.
        );
    }
}

And that's all ! Look like to be pretty simple ! But...

To simply convert the username into a User Entity, FOS advice to use "fos_user_username" in the builder.

Ok for me, but when I test this form :

  • With a sponsor who does exist, I've got this error "Please enter a password". (of course I've entered the password twice..).

  • But when I submit a form with an user whose does not exist, the registration form was submitted with success !

Have I done something wrong ? Thank you for your help ! ;-)

Dizda.

1
You can saw the form with the error here link. Thank you ^^dizda

1 Answers

2
votes

Fixed.

I've just upgraded symfony from 2.0.10 to 2.1 and the problem is not present anymore !