我正在尝试在symfony 2中实现具有一对多关系的Country-> State-> City。我刚刚开始使用symfony,我在此找到了一些链接,但无法使其工作,因为这些是旧版本symfony。
我已经生成了3个实体作为国家,州和城市。
注意:城市与国家没有直接关系,而是通过国家间接关系。
我为所有这些实体生成了CRUD。
州和国家的工作很好,但我需要选择国家然后说明并在城市创建表格上输入城市。
的symfony cookbook的教程我的CityType如下所示。
namespace Aceonics\SystemBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Aceonics\SystemBundle\Entity\Country;
use Aceonics\SystemBundle\Entity\State;
class CityType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('country', 'entity', array(
'class' => 'AceonicsSystemBundle:Country',
'property' => 'name',
//This line is added as City and Country do not have direct relation
'mapped' => false,
'empty_value' => 'Choose an option'
))
->add('name')
;
$formModifier = function (FormInterface $form, Country $country = null) {
$states = null === $country ? array() : $country->getStates();
$form->add('state', 'entity', array(
'class' => 'AceonicsSystemBundle:State',
'choices' => $states,
'empty_value' => 'Choose an option'
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
//Error Occurs here.
//As per tutorial it should be $data->getCountry()
//But as I do not have direct relation I have used $data->getState()->getCountry
$formModifier($event->getForm(), $data->getState()->getCountry());
}
);
$builder->get('country')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$country = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $country);
}
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Aceonics\SystemBundle\Entity\City'
));
}
/**
* @return string
*/
public function getName()
{
return 'aceonics_systembundle_city';
}
}
如果我使用$data->getCountry()
,则会出现以下错误:
Attempted to call method "getCountry" on class "Aceonics\SystemBundle\Entity\City" in E:\localhost\Aceonics_Apps\PHP_Frameworks\symfony\src\Aceonics\SystemBundle\Form\CityType.php line 49
如果我使用$data->getState()->getCountry()
,则会出现以下错误:
Error: Call to a member function getCountry() on a non-object in E:\localhost\Aceonics_Apps\PHP_Frameworks\symfony\src\Aceonics\SystemBundle\Form\CityType.php line 49
我试图把它放入isInstance的if语句中,但它没有帮助。
请帮助我理解并解决问题。