2

我以前有这个工作,但它停止使用 Symfony 2.7

我想要的是呈现一个扩展/多个实体选择列表,以便我显示多个自定义属性。目标是将选项列出为:

{name} - {description} 更多信息

所以我创建了一个以“实体”为父的自定义表单类型,这样我就可以自定义表单渲染

<?php
namespace Study\MainBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ScholarshipEntityType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('dataType', $options['dataType']);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'required' => false,
            'dataType' => 'entity'
        ));
    }

    public function getAllowedOptionValues(array $options)
    {
        return array('required' => array(false));
    }

    public function getParent()
    {
        return 'entity';
    }

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

}

我按如下方式呈现类型(它只是基于 Twitter Bootstrap 捆绑模板):

{% block scholarship_entity_widget %}
{% spaceless %}
    {% if expanded %}
        {% set label_attr = label_attr|merge({'class': (label_attr.class|default(''))}) %}
        {% set label_attr = label_attr|merge({'class': (label_attr.class ~ ' ' ~ (widget_type != '' ? (multiple ? 'checkbox' : 'radio') ~ '-' ~ widget_type : ''))}) %}
        {% if expanded %}
            {% set attr = attr|merge({'class': attr.class|default(horizontal_input_wrapper_class)}) %}
        {% endif %}
        {% for child in form %}
            {% if widget_type != 'inline' %}
            <div class="{{ multiple ? 'checkbox' : 'radio' }}">
            {% endif %}
                <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>
                    {{ form_widget(child, {'horizontal_label_class': horizontal_label_class, 'horizontal_input_wrapper_class': horizontal_input_wrapper_class, 'attr': {'class': attr.widget_class|default('')}}) }}
                    {{ child.vars.label.name|trans({}, translation_domain) }}
                    - {{ child.vars.label.description }}
                    <a href="{{ child.vars.label.link }}" target="_blank">More Information</a>
                </label>
            {% if widget_type != 'inline' %}
            </div>
            {% endif %}
        {% endfor %}
        {{ block('form_message') }}
        {% if expanded %}
        {% endif %}
    {% else %}
        {# not being used, just default #}
        {{ block('choice_widget_collapsed') }}
    {% endif %}
{% endspaceless %}
{% endblock %}

最后,我以另一种形式使用我的自定义类型:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // ...
        ->add('scholarships', new ScholarshipEntityType(), array(
            'class' => 'StudyMainBundle:Scholarship',
            'query_builder' => function(EntityRepository $er) use ($options) {
                return $er->findAllByOfferingQueryBuilder($options['offering']);
            },
            'choice_label' => 'entity',
            'multiple' => true,
            'expanded' => true,
            'label' => 'financial.scholarships'
        ))
    ;
}

我正在渲染的“属性”只是实体本身:

/**
 * Scholarship
 *
 * @ORM\Table(name="scholarship")
 * @ORM\Entity(repositoryClass="Study\MainBundle\Repository\ScholarshipRepository")
 */
class Scholarship
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    // ...

    /**
     * Get the Entity object for form rendering
     * 
     * @return \Study\MainBundle\Entity\Scholarship
     */
    public function getEntity()
    {
        return $this;
    }
}

不幸的是,看起来我将整个实体传递给 Twig 并让我访问属性的技巧不再有效。标签呈现为字符串的地方有一些变化(如果重要的话,我在 2.7 上将 'property' 更改为 'choice_label')。

错误:

可捕获的致命错误:Study\MainBundle\Entity\Scholarship 类的对象无法转换为字符串

堆栈跟踪:

1. in vendor/symfony/symfony/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php at line 251   + 
2. at ErrorHandler ->handleError ('4096', 'Object of class Study\MainBundle\Entity\Scholarship could not be converted to string', '/var/project/vendor/symfony/symfony/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php', '251', array('choice' => object(Scholarship), 'key' => '0', 'label' => object(Closure), 'values' => array('2'), 'index' => array('Symfony\Bridge\Doctrine\Form\Type\DoctrineType', 'createChoiceName'), 'attr' => null, 'isPreferred' => array(), 'preferredViews' => array(), 'otherViews' => array(), 'value' => '2', 'nextIndex' => '2')) 
in vendor/symfony/symfony/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php at line 251   + 
3. at DefaultChoiceListFactory ::addChoiceView (object(Scholarship), '0', object(Closure), array('2'), array('Symfony\Bridge\Doctrine\Form\Type\DoctrineType', 'createChoiceName'), null, array(), array(), array()) 
in vendor/symfony/symfony/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php at line 185

还有另一种方法可以实现这一目标吗?

我在考虑以下问题(但不知道具体该怎么做,或者是否值得研究其中的任何一个):

  • 变压器
  • 从 Choice 派生并执行我想要的操作的自定义类型(可能来自捆绑包)
  • 以某种方式使用选择列表工厂
  • 将实体作为一些附加字段而不是标签传递(也许是新的“choice_attr”?)
4

2 回答 2

2

如果我正确理解了这个问题,您应该__toString()在您的实体中实现该功能,这将格式化您想要在您的实体的选择列表中打印的字符串。

例如:

function __toString() {
  return sprintf("%s - %s", $this->type, $this->description);
}
于 2015-09-03T06:44:31.793 回答
0

尝试使用该方法AbstractType::buildView(FormView, FormInterface, array)。在那里,您可以访问传递给模板的变量。

我用它来DaterangeType为两个日期字段声明单独的 ID 和名称:

public function buildView(FormView $view, FormInterface $form, array $options)
{
    $view->vars['full_name_0'] = $view->vars['full_name'] . '[0]';
    $view->vars['full_name_1'] = $view->vars['full_name'] . '[1]';

    $view->vars['id_0'] = $view->vars['id'] . '_0';
    $view->vars['id_1'] = $view->vars['id'] . '_1';
}

然后,您可以将这些值作为标准 twig 变量访问。

于 2015-09-03T07:45:57.883 回答