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 #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系统的硬盘