dongmacheng3222 2016-07-28 14:43
浏览 48
已采纳

如何检测表单是否还有要呈现的元素?

Let's say I am using the Symfony Form Component to render a simple form with only two fields (username and email)

I am rendering both fields with form_row() to add custom css around, then call form_widget() to render the rest of the elements (another option would be form_rest()) What I am looking for is a way to check beforehand whether form_widget() will print any objects or not, in order to add custom html in case there are extra fields. The way I did it is like this:

//app/form/index.html.twig
{# Other template code #}
...
{# Rendering form: #}
{{ form_start(form) }}

{{ form_row(form.username) }}
{{ form_row(form.email) }}

{% set form_rendered = form_widget(form) %}
{% if form_rendered %}
    <h3>Other fields</h3>
    {{ form_rendered | raw }}
{% endif %}

{{ form_end(form) }}
{# End form #}
...
{# Other template code #}

However, I am not satisfied with it. Is there any better way?

Edit: When using CSRF Protection (activated by default), the previous code would ALWAYS print <h3>Other fields</h3>, since the form has an extra hidden field for the token that we didn't print. We would need to render it somewhere with {{ form_row(form._token) }}.

  • 写回答

1条回答 默认 最新

  • dprfe04886 2016-07-28 14:43
    关注

    By checking the code in src/Symfony/Component/Form/FormView.php, I found a function that does exactly what I wanted.

    //src/Symfony/Component/Form/FormView.php
    
        /**                                                                  
         * Returns whether the view was already rendered. 
         * 
         * @return bool Whether this view's widget is rendered 
         */
         public function isRendered()
         {
            $hasChildren = 0 < count($this->children);
    
            if (true === $this->rendered || !$hasChildren) {
                return $this->rendered;
            }
    
            if ($hasChildren) {
                foreach ($this->children as $child) {
                    if (!$child->isRendered()) {
                        return false;
                    }
                }
    
                return $this->rendered = true;
            }
    
            return false;
        }
    

    Now the function can be used in the template as such:

    {% if not form.isRendered() %}
        <h3>Other fields</h3>
        {{ form_widget(form) }}
    {% endif %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!