dongqin1861 2017-12-27 19:14
浏览 55
已采纳

使用具有动态生成的字段的表单测试控制器

I have a form which has a dynamic field :

<?php

namespace AppBundle\Form;

//uses ...
class AnnonceType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('titre')
        ->add('description')
        ->add('groupeCompetence', EntityType::class, [
            'class'       => 'AppBundle\Entity\GroupeCompetences',
            'choice_label' => 'nom',
            'placeholder' => 'Sélectionnez votre type de service',
            ])
        ->add('prix')
        ->add('serviceADistance')
        ->add('ajouter', SubmitType::class);


        $formModifier = function (FormInterface $form, GroupeCompetences $groupeCompetences=null){
            $competences = null === $groupeCompetences ? array() : $groupeCompetences->getCompetences();

            $form->add('competence', EntityType::class, array(
                'class' => 'AppBundle\Entity\Competence',
                'choice_label' => 'nom',
                'placeholder' => 'Choisir une compétence',
                'choices' => $competences,
                ));
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {

                // this would be your entity, i.e. CompetenceChoisie
                $data = $event->getData();

                //var_dump($data);
                //die();

                $formModifier($event->getForm(), $data->getGroupeCompetence());
            }
            );

         $builder->get('groupeCompetence')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {

                $groupeCompetences = $event->getForm()->getData();

                $formModifier($event->getForm()->getParent(), $groupeCompetences);

            }
            );

    } 
}

I have this code in ajax :

<script>
  var $groupeCompetence = $('#requete_prestataire_groupeCompetence');
// When sport gets selected ...
$groupeCompetence.change(function() {
  // ... retrieve the corresponding form.
  var $form = $(this).closest('form');
  // Simulate form data, but only include the selected sport value.
  var data = {};
  data[$groupeCompetence.attr('name')] = $groupeCompetence.val();
  // Submit data via AJAX to the form's action path.
  $.ajax({
    url : $form.attr('action'),
    type: $form.attr('method'),
    data : data,
    success: function(html) {
      // Replace current position field ...
      $('#requete_prestataire_competence').replaceWith(
        // ... with the returned one from the AJAX response.
        $(html).find('#requete_prestataire_competence')
        );
      // Position field now displays the appropriate positions.
    }
  });
});
</script>

In fact, competences is generated dynamicly depending on GroupeCompetence.

And I want to test this in PHPUnit.

I tried this :

public function testIndexRechercheUtilisateurNonConnecte()
    {
        $crawler = $this->client->request('GET', '/');

        $form = $crawler->selectButton('requete_prestataire_Rechercher')->form();
        $form['requete_prestataire[groupeCompetence]'] = 2;
        $form['requete_prestataire[competence]'] = "";

        $crawler = $this->client->submit($form);
        $this->assertTrue($this->client->getResponse()->isRedirect());
        $client->followRedirect();

        /*$this->assertEquals(3, $crawler->filter('a [class = "btn-sm btn-primary"]')->count());*/


    }

The problem is that : $form['requete_prestataire[competence]'] is generated dynamicly as I said.

I want to be able to do the ajax request in the test, and then test the output.

How can I proceed ?

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongzhun4898 2017-12-28 18:19
    关注

    I found the solution :

    you have to disable validation, and send the form as it was generated :

    $crawler = $this->client->request('GET', '/');
    
            $form = $crawler->selectButton('requete_prestataire_Rechercher')->form();
            $form['requete_prestataire[groupeCompetence]'] = 2;
            $form['requete_prestataire[competence]']->disableValidation()->select(50);
    
            $crawler = $this->client->submit($form);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值