Symfony2 服务阵列参数.如何根据键获取值


symfony2 service array parameters. How to get value based on key

我正在创建新的发票表单,其中包括具有一些常量值的选择输入。我通过服务做到了:

服务.yml

parameters:
    stawki_vat:
        0: 0%
        5: 5%
        8: 8%
        23: 23%
        zw: zw.
services:
    acme.form.type.stawki_vat:
        class: Acme'FakturyBundle'Form'Type'StawkiVatType
        arguments:
            - "%stawki_vat%"
        tags:
            - { name: form.type, alias: stawki_vat }

StawkiVatType.php

class StawkiVatType extends AbstractType
{
    private $stawkiVatChoices;
    public function __construct(array $stawkiVatChoices) {
        $this->stawkiVatChoices = $stawkiVatChoices;
    }
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'choices' => $this->stawkiVatChoices,
        ));
    }
    public function getParent()
    {
        return 'choice';
    }
    public function getName()
    {
        return 'stawki_vat';
    }
}

托瓦尔类型.php

class TowarType extends AbstractType
{
    /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('nazwa_towar', null, array('label' => 'Nazwa towaru/usługi'))
        ->add('cena_netto', null, array(
            'label' => 'Cena netto'
        ))
        ->add('vat', 'stawki_vat', array(
            'attr' => array('class' => 'styled'),
            'label' => 'Stawka VAT',
        ))
    ;
}

在形式上,一切都很完美。但是现在,我想获取存储在数据库中的值(stawki_vat键)并显示stawki_vat数组的值。

如何以简单的方式实现这一目标?

您需要将实体管理器传递给自定义表单类型服务。假设你正在使用教义:

服务.yml

services:
    acme.form.type.stawki_vat:
        class: Acme'FakturyBundle'Form'Type'StawkiVatType
        arguments: ["@doctrine.orm.entity_manager","%stawki_vat%"]

StawkiVatType.php

class StawkiVatType extends AbstractType
{
private $stawkiVatChoices;
private $em;
public function __construct(EntityManager $em, array $stawkiVatChoices) {
    $this->em = $em;
    $this->stawkiVatChoices = $stawkiVatChoices;
}
// ...