0

In my model (Task) I have a function:

public function isTaskOverdue()
    {
        if ("now"|date('Y-m-d') > task.deadline|date('Y-m-d')){
            return false;

        } else{
            return true;
        }
    }

In twig (edit) I want to display form:

{% extends 'base.html.twig' %}

{% block title %}app:Resources:Task:edit{% endblock %}

{% block body %}

        {{ form(form) }}

{% endblock %}

I want to display form, if this function return true. How can I call this function in twig?

1
  • In php, you can compare 2 dates directly, no need to format them. It twig you need to apply the date filter to get the "now" date. Commented Jul 9, 2016 at 13:03

3 Answers 3

1

Pass the task entity to twig and call method from object task :

{% if task.isTaskOverdue %}
    {{ form(form) }}
{% endif %}
Sign up to request clarification or add additional context in comments.

2 Comments

I changed my code to look like that, but some error appeared: Variable "task" does not exist in Task/edit.html.twig at line 7
You need to pass object Task from controller. to twig. Here an example: code return $this->render( 'main/main_wrapper.html.twig', ['task' => $task] ); code
0

I think it should be your controller that receives the function result and display the form or not depending on it.

Also you can write your function like so :

public function isTaskOverdue()
    {
        return ("now"|date('Y-m-d') > task.deadline|date('Y-m-d'));
    }

Comments

0

Pass the task entity to twig and do :

{% extends 'base.html.twig' %}

{% block title %}app:Resources:Task:edit{% endblock %}

{% block body %}

    {% if "now"|date("Ymd") <= task.deadline|date("Ymd") %}

        {{ form(form) }}

     {% endif %}

{% endblock %}

But, caution :

If you just not display the form, there is a security issue, because if an attacker submit the form from an self rebuilded HTML page, your controller will receive the form data and apply it.

So I would do the check in the controller, and only create and pass the form to the twig template if the condition is true.

Then, in twig you can use :

{% if form is defined %}
    {{ form(form) }}
{% endif %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.