Прохождение пользователя через параметр formFactory

Я следил за этой темой: FOS UserBundle - переопределить FormFactory

Потому что я хочу добавить поле в свой ProfileFormType, которое зависит от значения атрибута пользователя. Поскольку вы не можете получить пользователя из FormType, я хотел переопределить formFactory, чтобы передать текущего пользователя через массив параметров. Итак, именно это и было сделано в предыдущей теме.

Но я получаю сообщение об ошибке: «Опция «пользователь» не существует. Известные опции: «действие», «атрибут», «auto_initialize», «block_name», «by_reference», «cascade_validation» и т. д. ..." Итак Я предполагаю, что я мог ошибиться или это могла быть опечатка в именах сервисов в предыдущем посте. Поэтому я бы хотел, чтобы вы проверили, не найдете ли вы что-нибудь подозрительное в моем коде (ИМО, я не уверен в сборке формы/buildUserForm). Вот мои исходники, спасибо!

ПрофильКонтроллер:

    class ProfileController extends ContainerAware
{
    public function showAction()
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container->getParameter('fos_user.template.engine'), array('user' => $user));
    }

    public function editAction(Request $request)
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('cua_user.profile.form.factory');
        $formFactory->setUser($user);
        $form = $formFactory->createForm();
        $form->setData($user);

Услуги:

cua_user.profile.form.factory:
    class: Cua\UserBundle\Form\Factory\FormFactory
    arguments: ["@form.factory", "%fos_user.profile.form.name%", "%fos_user.profile.form.type%", "%fos_user.profile.form.validation_groups%"]

Тип формы профиля:

namespace Cua\UserBundle\Form\Type;

use Cua\UserBundle\Entity;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\Validator\Constraint\UserPassword as OldUserPassword;
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;


class ProfileFormType extends BaseType
{

    private $class;

    /**
     * @param string $class The User class name
     */
    public function __construct($class)
    {
        $this->class = $class;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (class_exists('Symfony\Component\Security\Core\Validator\Constraints\UserPassword')) {
            $constraint = new UserPassword();
        } else {
            // Symfony 2.1 support with the old constraint class
            $constraint = new OldUserPassword();
        }

        $this->buildUserForm($builder, $options);

        $builder->add('current_password', 'password', array(
                'label' => 'form.current_password',
                'translation_domain' => 'FOSUserBundle',
                'mapped' => false,
                'constraints' => $constraint,
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                'data_class' => $this->class,
                'intention'  => 'profile',
        ));
    }

    protected function buildUserForm(FormBuilderInterface $builder, array $options)
    {

        parent::buildUserForm($builder, $options);
        $builder
            ->remove('email')
            ->add('email', 'repeated', array(
                    'type' => 'email',
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => ' '),
                    'second_options' => array('label' => ' '),
                    'invalid_message' => 'Les deux adresses mail ne correspondent pas',
            ))
            ->add('pubEmail', 'checkbox', array('label' => ' ', 'required'=>false))
            ->add('nom', 'text', array('label' => 'Nom'))
            ->add('pnom', 'text', array('label' => 'Prénom'))
            ->add('annee')
            ->remove('username')
            ->add('fixe', 'text', array('label' => 'Tel. fixe', 'required'=>false))
            ->add('pubFixe', 'checkbox', array('label' => ' ', 'required'=>false))
            ->add('mobile', 'text', array('label' => 'Tel. mobile', 'required'=>false))
            ->add('pubMobile', 'checkbox', array('label' => ' ', 'required'=>false))
            ->add('facebook', 'url', array('label' => 'Adresse du profil facebook', 'required'=>false))
            ->add('pubFacebook', 'checkbox', array('label' => ' ', 'required'=>false))
            ->add('twitter', 'text', array('label' => 'Compte Twitter', 'required'=>false))
            ->add('pubTwitter', 'checkbox', array('label' => ' ', 'required'=>false))
            ->add('linkedin','url', array('label' => 'Adresse du profil Linkedin', 'required'=>false))
            ->add('pubLinkedin', 'checkbox', array('label' => ' ', 'required'=>false))
            ->add('site', 'url', array('label' => 'Site perso', 'required'=>false));
            if (!$options['user']->getStatut()==1)
            {
                $builder->add('antenne', 'entity', array('class'=>'CuaAnnuaireBundle:Groupe', 'property' => 'nom', 'multiple'=>false));
            }
    }

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


}

Фабрика форм:

    namespace Cua\UserBundle\Form\Factory;

use Symfony\Component\Form\FormFactoryInterface;
use FOS\UserBundle\Form\Factory\FactoryInterface;

class FormFactory implements FactoryInterface
{
    private $formFactory;
    private $name;
    private $type;
    private $validationGroups;
    private $user;

    public function __construct(FormFactoryInterface $formFactory, $name, $type, array $validationGroups = null)
    {
        $this->formFactory = $formFactory;
        $this->name = $name;
        $this->type = $type;
        $this->validationGroups = $validationGroups;
    }

    public function createForm()
    {
        return $this->formFactory->createNamed($this->name, $this->type, null, array('validation_groups' => $this->validationGroups, 'user'=>$this->user));
    }

    public function setUser($user)
    {
        $this->user = $user;
    }
}

person amougel    schedule 08.09.2014    source источник


Ответы (1)


Вам нужно указать эту опцию по мере необходимости, вы также можете назначить ей значение по умолчанию:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{

    $resolver->setRequired(array(
        'user'
    ));

    $resolver->setDefaults(array(
        'user'  => null,
    ));
}

Узнайте больше о Resolver здесь:

person b.b3rn4rd    schedule 08.09.2014
comment
Спасибо, похоже хорошее решение, я еще не слышал об этом резолвере, но сейчас попробую! Надеюсь, это сработает - person amougel; 09.09.2014