【问题标题】:Symfony form default value from extended class来自扩展类的 Symfony 表单默认值
【发布时间】:2014-12-31 11:41:13
【问题描述】:

我正在尝试为 symfony 中的表单设置默认值,但它似乎不起作用。表单映射到实体。

我知道,如果您在实体中设置值,那么这将是默认值,但在我的情况下,实体扩展了另一个类(映射的超类),而我的字段位于该类上。

/** @ORM\MappedSuperclass */
abstract class BaseEntity implements CustomEntityInterface
{
  protected $choiceField = 30;

 [ getters, setters, ... ]
}

class MyEntity extends BaseEntity
{
  [other attributes, getters, setters, ...]
}

choiceField 应该默认为 30,但事实并非如此。 (这是一个分钟的选择字段,填充了从 5 到 60 的值,步长为 5)

我知道我可以在 MyEntity 中重新声明 $this->choiceField,但这对我来说似乎不合适。有没有其他解决办法?

谢谢, 史蒂夫

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    我想你的意思是:

    abstract class BaseEntity implements CustomEntityInterface
    {
        protected $choiceField = 30;
    }
    

    ?

    Symfony2 表单的默认值表单可以在表单创建过程中简单地设置:

    public function buildForm(FormBuilderInterface $builder, array $options) 
    {
        $builder
            ->add('choiceField', 'text', array(
                'label' => 'Field',
                'data' => 'Default value'
            ))
            // ...
        ;
    }
    

    还可以设置实体属性值。

    【讨论】:

    • 对不起,我从 IDE 复制粘贴错误:),
    • 如果我在 BaseEntity 中设置值,它不会在表单中使用它。我很好奇是否可以在一个地方设置这个值,最好是在 BaseEntity 中。
    猜你喜欢
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多