phptwigtwig-filter

Twig Extended Function error when inside the loop


I have a twig code like this:

{% for row in faq_categories|batch(2, 'No item') %}
             <div class="row">
                {% for faq_category in row %}
                    <div class="col-lg-6">
                        <h3>{{ faq_category.name }}</h3>
                        <p>{{ faq_category.description }}</p>
                        {% set faqs = getFaqs( faq_category.id ) %}
                        <div class="accordion toggle fancy radius clean">
                            {% for faq in faqs %}
                                <div class="ac-item">
                                    <h5 class="ac-title"><i class="fa fa-question-circle"></i>{{ faq.question}}?</h5>
                                    <div style="" class="ac-content">{{ faq.answer }}</div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                {% endfor %}

Everything is normal, but when i have just 1 record for faq_categories it give me an error like this:

Message: 'Argument 1 passed to App\Models\Faq::byCategory() must be of the type int, null given, called in D:\laragon\www\compro\Core\View.php on line 86'

it was caused by this line of code:

{% set faqs = getFaqs( faq_category.id ) %}

It seems faq_category.id become null. I don't know what makes this happen is it because of the batch filter? or I have done something here?


Solution

  • This is because Batch filter. it will repeat twice since you set it into batch(2). so the second record which is empty will make faq_category.id became null. to fix the problem you can try this:

    {% set faqs = faq_category.id ? getFaqs( faq_category.id ) : null %}