gpt4 book ai didi

php - symfony2 - 从数据库中添加选项

转载 作者:可可西里 更新时间:2023-11-01 12:23:49 26 4
gpt4 key购买 nike

我希望用来自自定义查询的值填充 symfony2 中的选择框。我尽量简化了。

Controller

class PageController extends Controller
{

public function indexAction()
{
$fields = $this->get('fields');
$countries = $fields->getCountries(); // returns a array of countries e.g. array('UK', 'France', 'etc')
$routeSetup = new RouteSetup(); // this is the entity
$routeSetup->setCountries($countries); // sets the array of countries

$chooseRouteForm = $this->createForm(new ChooseRouteForm(), $routeSetup);


return $this->render('ExampleBundle:Page:index.html.twig', array(
'form' => $chooseRouteForm->createView()
));

}
}

选择路由表

class ChooseRouteForm extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{

// errors... ideally I want this to fetch the items from the $routeSetup object
$builder->add('countries', 'choice', array(
'choices' => $this->routeSetup->getCountries()
));

}

public function getName()
{
return 'choose_route';
}
}

最佳答案

您可以使用..将选项传递给您的表单

$chooseRouteForm = $this->createForm(new ChooseRouteForm($routeSetup), $routeSetup);

然后在你的表单中..

private $countries;

public function __construct(RouteSetup $routeSetup)
{
$this->countries = $routeSetup->getCountries();
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('countries', 'choice', array(
'choices' => $this->countries,
));
}

针对 2.8+ 更新(和改进)

首先,您真的不需要将国家/地区作为路由对象的一部分传递,除非它们将存储在数据库中。

如果将可用的国家/地区存储在数据库中,那么您可以使用事件监听器。如果没有(或者如果您不想使用监听器),您可以在选项区域中添加国家/地区。

使用选项

在 Controller 中..

$chooseRouteForm = $this->createForm(
ChooseRouteForm::class,
// Or the full class name if using < php 5.5
$routeSetup,
array('countries' => $fields->getCountries())
);

在你的表单中..

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('countries', 'choice', array(
'choices' => $options['countries'],
));
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefault('countries', null)
->setRequired('countries')
->setAllowedTypes('countries', array('array'))
;
}

使用监听器(如果国家/地区数组在模型中可用)

在 Controller 中..

$chooseRouteForm = $this->createForm(
ChooseRouteForm::class,
// Or the full class name if using < php 5.5
$routeSetup
);

在你的表单中..

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
$form = $event->getForm();
/** @var RouteSetup $routeSetup */
$routeSetup = $event->getData();

if (null === $routeSetup) {
throw new \Exception('RouteSetup must be injected into form');
}

$form
->add('countries', 'choice', array(
'choices' => $routeSetup->getCountries(),
))
;
})
;
}

关于php - symfony2 - 从数据库中添加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15836875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com