Symfony2,在Ajax查询中调用表单的一部分

时间:2016-05-06 08:47:06

标签: symfony

我在Symfony有一个表格。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('volume', IntegerType::class, array())
    ;

    $builder->add('product', ChoiceType::class, array(
        'data' => '1',
        'mapped' => false,
        'choices' => array(
                '1' => 'One',
                '2' => 'Two',
            ),
        )
    );

    $builder->add('deliveryType', ChoiceType::class, array(
        'expanded' => true,
        'data' => 1,
        'choices' => array(
            Command::STANDARD_DELIVERY => 'Standard',
            Command::EXPRESS_DELIVERY => 'Express',
        ),
    ));
}

但是字段deliveryType被加载到另一个使用ajax请求调用的模板中。 但是,我有这个错误: Variable "form" does not exist in ... at line 26

如何将表单的一部分放在另一个模板中?

这是我的主要模板:

<div class="panel-body">
  {{ form_start(form)}}
  {{ form_errors(form) }}

  <div class="row">
      <div class="col-sm-12">
          {{ form_row(form.product) }}
          {{ form_row(form.volume, {'attr': {'class': 'form-control'}}) }}
          {{ form_row(form.town) }}
      </div>
  </div>

  <div id="content-delivery-range"><!-- Block loaded by ajax --></div>

  <br>
  <button type="submit" class="btn btn-primary btn-block">Continuer </button>

  {{ form_end(form) }}

</div>

现在我的模板使用Ajax请求调用:

{{ deliveryRange|first|date('d M') }}
{{ deliveryRange|last|date('d M') }}

{% for d in deliveryRange %}
  {{ d|date('l') }} <br>
  <small>{{ d|intl_date('d') }} {{ d|date('M') }}</small>
{% endfor %}

{{ form_row(form.deliveryType) }}

2 个答案:

答案 0 :(得分:0)

将“deliveryType”表单元素作为初始表单呈现的一部分包含在内可能更容易。

然后,你的ajax调用可以返回你使用jquery / javascript / etc插入的必要值。

答案 1 :(得分:0)

找到它:

我在PRE_SUBMIT使用了事件监听器

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('volume', IntegerType::class, array())
    ;

    $builder->add('product', ChoiceType::class, array(
        'data' => '1',
        'mapped' => false,
        'choices' => array(
                '1' => 'One',
                '2' => 'Two',
            ),
        )
    );

    $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));

}

public function onPreSubmit(FormEvent $event)
{
    $form = $event->getForm();

    $form->add('deliveryType', ChoiceType::class, array(
        'expanded' => true,
        'data' => Command::STANDARD_DELIVERY,
        'choices' => array(
            Command::STANDARD_DELIVERY => 'Standard',
            Command::EXPRESS_DELIVERY => 'Express',
        ),
    ));
}