0

我对 Symfony2 中的服务和表单有疑问,所以我创建了我的 cals 表单,我希望添加一个多选城市列表,然后我想从另一个类“城市”中获取城市列表,所以我如何调用我的类“ 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';
}
}

类 City.php :

Class City {

  /**
   * here i will get list of cities 
   */


  public function getcities()
  {
     .....
    return $Listcities;
  }

  }

所以我想用“服务”在表单中调用函数“getcities”?

4

2 回答 2

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
    }
}
于 2012-10-02T17:01:17.940 回答
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()
                        )
                    )
                );
            }
        );
    }
}
于 2012-10-02T17:48:42.080 回答