2

I am using symfony v2.3 and was trying to validate if a field in my twig form is null or undefined. Here is my twig form:

{{form_start(form)}}
    <p>
         Date 
         {{form_widget(form.date)}}
    </p>
    <p>
        School 
        {{form_widget(form.school)}}
    </p>
    <p>
        City 
        {{form_widget(form.city)}}
    </p>
    <p>
        Name
        {{form_widget(form.name)}}
    </p> 
    <p>
        {{ form_widget(form.save)}}
    </p> 
{{form_end(form)}}

I tried researching about it and found something interesting but i dont know how to do it when i am using a twig for my form. How to determine if variable is 'undefined' or 'null'? I want to do something like this but i dont know how.

if(typeof variable_here === 'undefined'){
// your code here.
};
Community
  • 1
  • 1
Uc.IT_samuel
  • 213
  • 2
  • 12

1 Answers1

3

I'm not sure to understand what you want to do excatly, but did you try to use twig defined test ?

{% if my_var is defined%}
    {# Do smething #}
{% endif %}

Twig also provide the same as test, the equivalent of === in php :

{% if my_var is not same as(null) %}
    {# Do smething #}
{% endif %}

In your template you could do :

{{form_start(form)}}
{# Check if date field is defined #}
{% if form.date is defined %}
<p>
     Date 
     {{form_widget(form.date)}}
</p>
{% endif %}

{# Check if school field is defined and is not null #}
{% if form.date is defined and form.date is not same as(null) %}
<p>
    School 
    {{form_widget(form.school)}}
</p>
{% endif %}
<p>
    City 
    {{form_widget(form.city)}}
</p>
<p>
    Name
    {{form_widget(form.size)}}
</p> 
<p>
    {{ form_widget(form.save)}}
</p> 

{{form_end(form)}}

Hope this helps

Picoss
  • 2,047
  • 13
  • 14
  • sir, if i entered nothing on my form and click the button _save_ , what will happen? will it stay on the same page and/or prompt the user? TIA :) – Uc.IT_samuel Feb 11 '16 at 08:08
  • If you need to validate the user data, take a look at this http://symfony.com/doc/current/book/validation.html – Picoss Feb 11 '16 at 08:45
  • ok sir thanks... i am just new here so i really need to read and research a lot :) – Uc.IT_samuel Feb 11 '16 at 09:13