doufu9145 2016-06-09 13:16 采纳率: 0%
浏览 52
已采纳

如何在Symfony 3中自动检查变量是否为空?

(Sorry for this bad english)

I would like to know if it's possible to automatically check if variables from MySQL request are not empty in Symfony 3. I know that I can put {% if foo is defined %} in Twig or something like this but I didn't find if there's a way to do it automatically. I can test the request in the controller too. But with those solutions I have to do it for every request.

All my website uses "if not empty then show it" that's why I'm trying to find it.

Edit : I know how to check every fields of every request in Twig or in php (Controller) one by one but there is a lot of duplication code, which is "boring". Thats why I am asking you if something automatic exists to check my data. (parameter in Symfony, ...)

Thank you <3

  • 写回答

2条回答 默认 最新

  • 普通网友 2016-06-09 16:23
    关注

    If I understand, your problem :

    You want to iterate on each property in an entity. But you can't, then you are searching for a solution to not write :

    {% if entity.property1 %}
        {{ entity.property1 }}
    {% endif %}
    {% if entity.property2 %}
        {{ entity.property2 }}
    {% endif %}
    {% if entity.property3 %}
        {{ entity.property3 }}
    {% endif %}
    

    You have two solutions to make your properties traversable :

    So you can iterate on each property, and do something like that :

    {# Where you get your entity as an array #}
    {% for property in entity %}
       {% if not property  is null %}
            {{ property }}
       {% endif %}
    {% endfor %}
    
    {# where fields comes from the ReflectionClass #}
    {% for field in fields %}
       {% if not attribute(entity,field) is null %}
            {{ attribute(entity,field)}}
       {% endif %}
    {% endfor %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?