【问题标题】:Symfony2 : set default value from database in radio buttons choice form?Symfony2:以单选按钮选择形式从数据库中设置默认值?
【发布时间】:2023-04-11 05:06:03
【问题描述】:

symfony2 新手,我有一个包含 2 个字段的简单表格。

由于alert 字段是一个布尔值,我这样声明表单:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder                                
        ->add('message', 'text', array('label' => "Message"))                
        ->add('alert', 'choice', array(
              'choices'   => array(1 => 'Yes', 0 => 'No'),
              'expanded'  => true,
              'multiple'  => false,
              'label'     => "Are you agree?",
              'attr'      => array('class' => 'well')
        ));
}

当我创建一个新条目时它正在工作,但是当我尝试编辑该条目时,存储在数据库中的“警报”选项未在表单中设置(单选按钮)。

如何设置表单中字段的数据库状态?

【问题讨论】:

  • 是实体形式吗?

标签: php forms symfony


【解决方案1】:

这里有 2 个选项。

尝试在表单构建器中使用数据属性。

$builder                                
        ->add('message', 'text', array('label' => "Message"))                
        ->add('alert', 'choice', array(
              'choices'   => array(1 => 'Yes', 0 => 'No'),
              'expanded'  => true,
              'multiple'  => false,
              'label'     => "Are you agree?",
              'data'      => $entity->getAlert(),
              'attr'      => array('class' => 'well')
        ));

或者: 在 symfony 中创建表单时,您通常将数据实体传递给该表单。此自动填充所有值。

$this->createForm(new FormType(), $entity);

【讨论】:

  • 好的,Symfony 没有办法自动将数据库值设置为“数据”吗?
  • @sdespont 它是自动完成的......您只需要获取实体并将其设置为createForm 的第二个参数,如上所示
  • @Rico Humme 我理解,但是例如编辑“实体”字段不需要指定现有的数据库值,Symfony 只需设置它。在这种情况下,我必须先检索值(如果实体存在),然后将值赋给“数据”字段。在我看来,这不是自动完成的。
【解决方案2】:

要完成 Rico Humme 的回答,您可以这样做。

public function myFunc() {
    ....
    $entity = $this->getDoctrine()
        ->getRepository('AcmeFooBundle:Entity')
        ->find($id);
    if ($entity) {
        $form = $this->createForm(new EntityType(), $entity);
        ...
    }
}

编辑

为了完成我的回答,EntityType 可能如下所示:

class EntityType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        //This is just soe
        $builder->add('alert', 'choice', array(
          'choices'   => array(1 => 'Yes', 0 => 'No'),
          'expanded'  => true,
          'multiple'  => false,
          'label'     => "Are you agree?",
          'attr'      => array('class' => 'well')
        ));
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\FooBundle\Entity\Entity',
        ));
    }

}

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 2013-03-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 2014-04-23
    • 2014-05-10
    相关资源
    最近更新 更多