我对Symfony2中的服务和表单有疑问,所以我创建了我的calss表单,我希望添加一个多选城市列表,然后我想从另一个类“city”获取城市列表,所以我怎么称呼我的班级“城市”在我的表格中使用“服务”来获取功能“getcities”来返回我的城市列表? (我不在这里使用Doctrine)......
修改
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CityType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'choices' => array( /**
* Here I will call function getcities(return list of cities)
*/
)
));
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'gender';
}
}
class City.php:
Class City {
/**
* here i will get list of cities
*/
public function getcities()
{
.....
return $Listcities;
}
}
所以我想用“Service”来调用函数“getcities”吗?
答案 0 :(得分:2)
表单对象不是容器感知的...至少,它们并不意味着。也就是说,您的控制器应该使用该服务来获取城市,然后它应该通过构造函数或方法将该列表传递给表单对象。
控制器:
class SomethingController
{
public function someAction()
{
...
$cities = $this->get("citiesService")->getCities();
$form = $this->createForm(new SomeType($cities), $someEntity);
...
}
}
形式:
class SomeType extends AbstractType
{
private $cities;
public function __construct($cities)
{
$this->cities = $cities;
}
public function buildForm(FormBuilder $builder, array $options)
{
// Now you have access to $this->cities, so you can use it to build the form
}
}
答案 1 :(得分:0)
您可以将City对象设置为表单数据对象吗?
所以它看起来像......
$form = $this->createForm(new SomeType(), new City());
class SomeType extends AbstractType
{
public buildForm(FormBuilderInterface $builder, array $options)
{
$formFactory = $builder->getFormFactory();
$builder->addEventListener(
FormsEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formFactory) {
$event->getForm()->add(
$formFactory->createNamed(
'gender',
'choice',
null,
array(
'choices' => $event->getData()->getCites()
)
)
);
}
);
}
}