dousao2186 2014-05-18 19:53
浏览 34
已采纳

在Symfony2.4表单上设置类(或任何属性)

I'm trying to figure out how to set the class (or any attribute really) on a Symfony2 form created via FormBuilder. I am aware that you can do this via the template for the form itself, but I would still like to know how to do it via $this->createFormBuilder() in the controller.

My code is below. I've tried the setAttribute() method as you can see in my code, but it has no effect. I initially thought I messed up as I overwrote the default twig form_div_layout.html.twig file, but this was not the case.

private function createResolvedForm($id) {
    return $this->createFormBuilder()
                ->setAction($this->generateUrl('system_announcement_resolve', array('id' => $id)))
                ->setMethod('PUT')
                ->setAttribute('class', 'resolved-form exempt-from-default-ajax')
                ->add('submit', 'submit', array(
                    'label' => 'Mark As Resolved',
                    'attr' => array(
                        'class' => 'btn btn-success btn-xs',
                        'data-toggle' => 'tooltip',
                        'data-placement' => 'top',
                        'title' => 'Resolve Issue #' . $id,
                    )
                ))
                ->getForm();
}

To be clear, I'm not having an issue setting the class on the submit button I'm passing in, but rather the actual form itself.

Thanks for any help!

  • 写回答

1条回答 默认 最新

  • dongsu3664 2014-05-18 20:02
    关注

    The createFormBuilder method has two input parameters

    public FormBuilder createFormBuilder(mixed $data = null, array $options = array())
    

    So in your example you could use the second parameter to set the class on the whole form

    private function createResolvedForm($id) {
    return $this->createFormBuilder(null, array('attr' => array('class' => 'resolved-form exempt-from-default-ajax')))
                ->setAction($this->generateUrl('system_announcement_resolve', array('id' => $id)))
                ->setMethod('PUT')
                ->setAttribute('class', 'resolved-form exempt-from-default-ajax')
                ->add('submit', 'submit', array(
                    'label' => 'Mark As Resolved',
                    'attr' => array(
                        'class' => 'btn btn-success btn-xs',
                        'data-toggle' => 'tooltip',
                        'data-placement' => 'top',
                        'title' => 'Resolve Issue #' . $id,
                    )
                ))
                ->getForm();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘