Symfony 2.8 - 使用来自会话和推进的数据设置默认值

Symfony 2.8 - Set default value with data from session and propel

我在一个项目中使用 Propel & 我尝试为我的表单设置默认值,它使用 ModelType 输入,我需要设置一个默认值存储在这个表单的会话中,并且这个会话的存储值不为空用于此功能。

这是我的表格:

   /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Fcl\VitrinellisBundle\Model\ProfileVariety',
            'name' => 'profile_variety_search',
            'locales' => ['fr'],
            'session' => null
        ));
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', ModelType::class, array(
                'class'       => 'Fcl\VitrinellisBundle\Model\ProfileVariety',
                'query'       => ProfileVarietyQuery::create()->orderById(),
                'property'    => 'name',
                'label'       => 'Profil recherché',
                'expanded'    => false,
                'multiple'    => false,
                'required'    => false,
                'placeholder' => '- Filtrer par profil -',
                'attr' => array(
                    'onchange' => 'submit()',
                    'class'    => 'col s3'
                )
            ))
        ;
    }

这是我的治疗方法:

    public function listAction(Request $request = null)
    {
        $pModelManager = $this->get('fcl_vitrinellis.p_model_manager');
        $profileVarietyManager = $this->get('fcl_vitrinellis.profile_variety_manager');
        $session = $request->getSession();
        $profileVariety = new ProfileVariety();
        $models = null;

        $form = $this->createForm(ProfileVarietySearchType::class, $profileVariety);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (null != $form['name']->getData()) {
                $models =  $pModelManager->getWebsiteByModel($form['name']->getData()->getName());
                $session->set('profileVarietySearch', $form['name']->getData()->getName());
            } else {
                $models = $pModelManager->getList();
            }
        } else {
            if ($session->has('profileVarietySearch') && null != $session->get('profileVarietySearch')) {
                $models = $pModelManager->getWebsiteByModel($session->get('profileVarietySearch'));
            } else {
                $models = $pModelManager->getList();
            }
        }

        return $this->render('console\p_model_list.html.twig', array(
            'objArray' => $models,
            'form' => $form->createView()
        ));
    }

我尝试使用 'data' 选项和表单中的 PRE_SET_DATA 事件设置默认数据,但我得到了令人满意的结果。

在 EntityType 中,传入的默认值 'data' 必须是正确类型的对象。我会首先尝试查看是否有传入的表单数据。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // Check form data
    $formDataEntity = $builder->getData();

    // Check if it has the field filled in
    if ($formDataEntity && $formDataEntity->getName()) {
         $objToSet = $formDataEntity->getName();
    } else {
         $objToSet = $options['incomingDefaultObject'];
    )

    $builder
        ->add('name', ModelType::class, array(
            class => 'Fcl\VitrinellisBundle\Model\ProfileVariety',
            data => $objToSet,
            ...

然后是解析器

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'incomingDefaultObject' => null,
    ));
}

并且您在控制器中使用默认选项调用表单

$form = $this->createForm(YourType::class, $yourObject, array('incomingDefaultObject' => $nameObject));

警告:如果用户决定将该字段留空,此代码将始终设置为默认值。

我有其他解决方案。

创建名为 ProfileVarietySearch 的新模型,如下所示:

class ProfileVarietySearch
{
    /** @var null|ProfileVariety $profileVariety */
    private $profileVariety;

    /**
     * @return bool
     */
    public function is_empty()
    {
        return is_null($this->profileVariety);
    }

    /**
     * @return null|ProfileVariety
     */
    public function getProfileVariety()
    {
        return $this->profileVariety;
    }

    /**
     * @param $profileVariety
     *
     * @return ProfileVarietySearch
     */
    public function setProfileVariety($profileVariety): self
    {
        $this->profileVariety = $profileVariety;

        return $this;
    }
}

在控制器中,这样写:

    public function listAction(Request $request = null)
    {
        $pModelManager = $this->get('fcl_vitrinellis.p_model_manager');
        $profileVarietyManager = $this->get('fcl_vitrinellis.profile_variety_manager');
        $session = $request->getSession();
        $profileVarietySearch = new ProfileVarietySearch();
        $models = null;

        if ($session->has('profileVarietySearch') && null != $session->get('profileVarietySearch')) {
           $profileVarietySearch->setProfileVariety(
               $profileVarietyManager->getByName($session->get('profileVarietySearch'))->getData()[0]
           );
        }



        $form = $this->createForm(ProfileVarietySearchType::class, $profileVarietySearch);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (null != $form->getData()->getProfileVariety()) {
                $models =  $pModelManager->getWebsiteByModel($form->getData()->getProfileVariety()->getName());
                $session->set('profileVarietySearch', $form->getData()->getProfileVariety()->getName());
            } else {
                $session->set('profileVarietySearch', null);
                $models = $pModelManager->getList();
            }
        } else {
            if ($session->has('profileVarietySearch') && null != $session->get('profileVarietySearch')) {
                $models = $pModelManager->getWebsiteByModel($session->get('profileVarietySearch'));
            } else {
                $models = $pModelManager->getList();
            }
        }

        return $this->render($this->view_list, array(
            'objArray' => $models,
            'form' => $form->createView()
        ));
    }

在 ProfileVarietySearchType 中,这样写:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Fcl\VitrinellisBundle\Form\Model\ProfileVarietySearch',
        'name' => 'profile_variety_search'
    ));
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('profileVariety', ModelType::class, array(
        'class'       => 'Fcl\VitrinellisBundle\Model\ProfileVariety',
        'query'       => ProfileVarietyQuery::create()->orderById(),
        'property'    => 'name',
        'label'       => 'Profil recherché',
        'expanded'    => false,
        'multiple'    => false,
        'required'    => false,
        'placeholder' => '- Filtrer par profil -',
        'attr' => array(
            'onchange' => 'submit()',
            'class'    => 'col s3'
        )
    ));
}