Ami*_*mit 3 symfony-forms symfony
如果我在控制器内,我可以使用以下方法轻松读取配置参数:
$this->container->getParameter('profession');
Run Code Online (Sandbox Code Playgroud)
但是当我在其他课程中,说一个Form类型时,我怎样才能获得配置参数?
$container = new Container();
$container->getParameter('profession');
Run Code Online (Sandbox Code Playgroud)
上面的代码不应该也不起作用.
另一个类似的解决方案是让您的表单类型为服务并注入所需的参数.然后你的控制器需要做的就是获取服务.使用百分号覆盖参数名称.
在services.xml中
<service
id = "zayso_area.account.create.formtype"
class = "Zayso\AreaBundle\Component\FormType\Account\AccountCreateFormType"
public = "true">
<argument type="service" id="doctrine.orm.accounts_entity_manager" />
<argument type="string">%zayso_core.user.new%</argument>
</service>
Run Code Online (Sandbox Code Playgroud)
如果你真的想那么你可以注入完整的容器,尽管这是不鼓励的.
小智 5
现在您可以使用ContainerAwareInterface:
class ContactType extends AbstractType implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('choice_field', ChoiceType::class, [
'choices' => $this->container->get('yourservice')->getChoices()
]);
}
}
Run Code Online (Sandbox Code Playgroud)
在services.yml中:
app.contact_type:
class: AppBundle\Form\ContactType
calls:
- [setContainer, ['@service_container']]
tags:
- { name: form.type, alias: 'container_aware' }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11151 次 |
最近记录: |