Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if record exist in respons TWIG - data in table format

Tags:

php

twig

I have a multidimensional array where some objects exist and others don't. The whole data has used in page. Then I plan check it in TWIG. example data:

array:2[
  0 => Data1 {
    -id: 17
    -porodType: "1d"
    -name: "Dally promotion" 
  }
  1 => Data1 {
    -id: 34
    -porodType: "S"
    -name: "Special" 
  }    
]

How to check if record with porodType = "1d" exist in respons? How to display different message for this acction: exist(OK)/no-exist(ERROR)?

When check in TWIG:

{% for d in Data1 %}
    {% if d.porodType == '1d' %}
        <button class="btn">OK</button>
    {% else %}
        <button class="btn"">Error</button>
    {% endif %}
{% endfor %}

this code result is: <button class="btn">OK</button><button class="btn">Error</button>

but I expected <button class="btn">OK</button> or <button class="btn">ERROR</button>

like image 486
janek1 Avatar asked Nov 24 '25 19:11

janek1


1 Answers

If you only want to show one button, you'd need to keep track of an error with a flag as you can't break loops in Twig,

{% set error = false %}
{% for d in Data1 %}
    {% if d.porodType != '1d' %}
        {% set error = true %}
    {% endif %}
{% endfor %}
{% if error %}
    <button class="btn">Error</button>
{% else %}
    <button class="btn">OK</button>
{% endif %}
like image 73
DarkBee Avatar answered Nov 27 '25 13:11

DarkBee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!