在Symfony中动态设置表单字段

时间:2015-06-09 21:14:10

标签: php forms symfony symfony-forms

我已经尝试了docs,正如您在我的代码中看到的那样,我得到了一个国家/州示例。但是我想在国内设置另一个领域(国家代码),而不仅仅是国家。

这是我的代码,从实体开始:

地址:

<?php

namespace Costo\AddressBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* Address
*
* @ORM\Table()
* @ORM\Entity
*/
class Address
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="address", type="string", length=255)
 */
private $address;

/**
 * @ORM\ManyToOne(targetEntity="Country", inversedBy="addresses")
 */
private $country;

/**
 * @var string
 *
 * @ORM\Column(name="countryCode", type="string", length=255)
 */
private $countryCode;

/**
 * @ORM\ManyToOne(targetEntity="State", inversedBy="addresses")
 */
private $state;

国家:

<?php

namespace Costo\AddressBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* Pais
*
* @ORM\Table()
* @ORM\Entity
*/
class Country
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @var string
 *
 * @ORM\Column(name="code", type="string", length=255)
 */
private $code;

/**
 * @ORM\OneToMany(targetEntity="State", mappedBy="country")
 */
private $states;

/**
 * @ORM\OneToMany(targetEntity="Address", mappedBy="country")
 */
private $addresses;

状态:

<?php

namespace Costo\AddressBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* Estado
*
* @ORM\Table()
* @ORM\Entity
*/
class State
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="Country", inversedBy="states")
 */
private $country;

/**
 * @ORM\OneToMany(targetEntity="Address", mappedBy="state")
 */
private $addresses;

表格:

<?php

namespace Costo\AddressBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormInterface;
use Costo\AddressBundle\Entity\Country;

class AddressType extends AbstractType
{
    /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('address')
        ->add('country');

    $formModifier = function (FormInterface $form, Country $country = NULL) {
        $states = NULL === $country ? array() : $country->getStates();
        $code   = NULL === $country ? '' : $country->getCode();

        $form->add('state', 'entity', array(
            'class' => 'AddressBundle:State',
            'choices' => $states
        ));

        $form->add('countryCode', 'text', array(
            'data' => $code
        ));
    };


    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier){
        //entity
        $data = $event->getData();

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

    $builder->get('country')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier){
       $data = $event->getForm()->getData();

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

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

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

}

最后我的模板:

{% extends '::base.html.twig' %}

{% form_theme form 'bootstrap_3_horizontal_layout.html.twig' %}

{% block body -%}
<h3>Add Address</h3>

{{ form_start(form) }}

    {{ form_widget(form) }}

    <div class="form-group">
        <div class="col-sm-2"></div>
        <div class="col-sm-10">
            <input type="submit" class="btn btn-primary btn" value="Aceptar">

            <a href="{{ path('address') }}" class="btn btn-info" role="button">
                <span class="glyphicon glyphicon-list"></span> List</a>
        </div>
    </div>


{{ form_end(form) }}
 {% endblock %}

{% block javascripts %}
{{ parent() }}
<script>
    var $country = $('#costo_addressbundle_address_country');
    // When country gets selected ...
    $country.change(function() {
        // ... retrieve the corresponding form.
        var $form = $(this).closest('form');
        // Simulate form data, but only include the selected country value.
        var data = {};
        data[$country.attr('name')] = $country.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 state field ...
                $('#costo_addressbundle_address_state').replaceWith(
                        // ... with the returned one from the AJAX response.
                        $(html).find('#costo_addressbundle_address_state')
                        );
            }
        });
    });

</script>

{% endblock %}

我想在我的地址实体中设置国家/地区代码,我不知道问题是在表单类中,还是在ajax的模板中存在问题

0 个答案:

没有答案