Symfony 2: многошаговая форма с CraueFormFlowBundle и FOSUserBundle

Для моего приложения мне нужно создать многошаговую форму для регистрации новых пользователей, поэтому я установил CraueFormFlowBundle. , и я тоже использую FOSUserBundle.

На первом этапе моей регистрационной формы я хочу зарегистрировать информацию о пользователе (логин, пароль...) с помощью FOSUserBundle, и после этого пользователь будет перенаправлен на следующий шаг формы.

Итак, я встраиваю коллекцию типа формы в один тип под названием «RegistrationEtablissementForm».

Но когда я пытаюсь отобразить представление моей многошаговой формы, у меня возникает эта ошибка:

Предупреждение: отсутствует аргумент 1 для FOS\UserBundle\Form\Type\RegistrationFormType::__construct(), вызываемый в C:\wamp\www\likabee_3\src\AppBundle\Form\RegistrationEtablissementForm.php в строке 14 и определяемый

Тип RegistrationEtablissementForm:

namespace AppBundle\Form;


// AppBundle/Form/RegistrationEtablissementForm.php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationEtablissementForm extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        switch ($options['flow_step']) {
            case 1:
                $builder->add('registration', array('type' => new RegistrationFormType()));
                break;

            case 2:
                $builder->add('etablissement', array('type' => new EtablissementType()));
                break;

            case 3:
                $builder->add('chambres', 'collection', array(
                            'type'         => new ChambreType(),
                            'allow_add'    => true,
                            'allow_delete' => true
                          ));
                break;
        }
    }

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

}

И первые типы формы:

namespace AppBundle\Form;

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('nom', 'text')
            ->add('prenom', 'text')
            ->add('telephonePortable', 'text')
            ->add('telephoneFixe', 'text', array('required' => false))
            ->add('fax', 'text', array('required' => false))
            ->add('Civilite', 'text')
        ;
    }

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

второй :

class EtablissementType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nombre_place_total','choice', array('choices' => array('1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', '13' => '13', '14' => '14', '15' => '15')))
            ->add('tarif_min', 'text')
            ->add('tarif_max', 'text')
            ->add('description', 'textarea')
            ->add('nom_etablissement', 'text')

        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Etablissement'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_etablissement';
    }
}

и третий:

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ChambreType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom_chambre', 'text')
            ->add('nombre_place','choice', array('choices' => array('1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10')))
            ->add('nombre_lit','choice', array('choices' => array('1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6')))
            ->add('superficie', 'text')
            ->add('tarif_1', 'text')
            ->add('tarif_2', 'text')
            ->add('tarif_3', 'text')
            ->add('tarif_4', 'text')
            ->add('tarif_5', 'text')
            ->add('tarif_6', 'text')
            //->add('etablissement')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Chambre'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_chambre';
    }
}

В моем файле services.yml форма для регистрации в FOSUserBundle И включена многоэтапная форма, которая имеет службу:

services:
#    service_name:
#        class: AppBundle\Directory\ClassName
#        arguments: ["@another_service_name", "plain_value", "%parameter_name%"]

    homes_user.registration.form.type:
        class: AppBundle\Form\RegistrationFormType
        arguments: [%fos_user.model.user.class%]
        tags:
            - { name: form.type, alias: homes_user_registration }

    likabee.form.registrationEtablissement:
        class: AppBundle\Form\RegistrationEtablissementForm
        tags:
            - { name: form.type, alias: registrationEtablissement }

    likabee.form.flow.registrationEtablissement:
        class: AppBundle\Form\RegistrationEtablissementFlow
        parent: craue.form.flow
        scope: request
        calls:
            - [ setFormType, [ "@likabee.form.registrationEtablissement" ] ]

В моем контроллере я создал эту функцию для рендеринга формы в представлении:

/**
     * @Route("/registration-etablissement", name="registrationEtablissement")
     */
    public function registrtationEtablissementAction() {
        $formData = new RegistrationEtablissementForm(); // Your form data class. Has to be an object, won't work properly with an array.

        $flow = $this->get('likabee.form.flow.registrationEtablissement'); // must match the flow's service id
        $flow->bind($formData);

        // form of the current step
        $form = $flow->createForm();
        if ($flow->isValid($form))
        {
            $flow->saveCurrentStepData($form);

            if ($flow->nextStep()) {
                // form for the next step
                $form = $flow->createForm();
            } else {
                // flow finished
                $em = $this->getDoctrine()->getManager();
                $em->persist($formData);
                $em->flush();

                $flow->reset(); // remove step data from the session

                return $this->redirect($this->generateUrl('index')); // redirect when done
            }
        }

        return $this->render('registrationEtablissement.html.twig', array(
                'form' => $form->createView(),
                'flow' => $flow,
        ));
    }

Я ищу решение в течение нескольких дней, но я не нахожу его...

Спасибо за вашу помощь, и извините за мой английский;)


person Thomas    schedule 12.10.2015    source источник
comment
пожалуйста, опубликуйте конкретную часть, с которой у вас возникла проблема, так что это не служба отладки @Thomas   -  person Maksud Mansuri    schedule 12.10.2015


Ответы (1)


В вашем классе RegistrationEtablissementForm в строке 14 вы вызываете конструктор FOS\UserBundle\Form\Type\RegistrationFormType. Если вы проверите код класса в FOSUserBundle, вы увидите, что конструктору требуется имя пользовательского класса в качестве атрибута:

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

    // ...
}

Добавление вашего пользовательского класса при вызове конструктора должно решить эту проблему.

person jahller    schedule 12.10.2015
comment
Я добавил $builder->add('utilisateur', array('type' => new RegistrationFormType('homes_user_registration'))); в строку 14 (ошибка), потому что это псевдоним для регистрации формы в моем файле services.yml, но у меня есть ошибка Ожидаемый аргумент типа string или Symfony\Component\Form\FormTypeInterface, указанный массив. То же самое, когда я заменяю имя класса формы регистрации моего типа. Я что-то не так? - person Thomas; 13.10.2015