0

I would like to know how to access to a html twig form field value through javascript in Symfony2. The explanation is as below:

This is the screen shot of the form that I have:

enter image description here

This is the form code:

    <html>
    <head>
        <title> Wkayet </title>
         <link rel="shortcut icon" href="{{asset('bundles/ikprojhome/images/icon-WKAYET.png')}}">
        <link rel="stylesheet" type="text/css" href="{{asset('bundles/ikprojhome/css2/css.css')}}"/>
        <script src='{{asset('bundles/ikprojhome/lib/jquery.min.js')}}'></script> 

        <script>
            function f1(){
                if(form_widget(form.start)>form_widget(form.end)){
                    alert("no");
                }
            }
        </script>
    </head>
    <body>
    <center>
        <div id="container">
            <div id="header">

            </div>
            <div id="content">
                <table width="100%" height="100%" align="center">
                    <tr>
                        <td>
                            {% for x in groupe%}
   <form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:x['id']})}}' method="POST" {{ form_enctype(form) }} onsubmit="f1();">
   <!--<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:x['id']})}}' method="POST" {{ form_enctype(form) }} >-->
                                {% endfor %}
                                 {{ form_errors(form) }}
                                <table align="center">
                                    <tr>
                                        <td class="separation"><label for="groupname">Titre</label></td>
                                        <td>
                                     <!--<input id="titre" name="titre" required="required" type="text" size="50"/> -->
                                         <div>
                                            {{ form_errors(form.title) }}

                                            {{ form_widget(form.title) }}
                                           </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="separation"><label for="debut">Début</label></td>
                                        <td><!--<select id="debut" name="debut" class="select"></select>-->
                                            <div>
                                             {{ form_errors(form.start ) }}

                                             {{ form_widget(form.start ) }}
                                            </div>


                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="separation"><label for="fin">Fin</label></td>
                                        <td><!--<select id="fin" name="fin" class="select"></select>-->
                                            <div>
                                             {{ form_errors(form.end ) }}

                                             {{ form_widget(form.end ) }}
                                          </div> 

                                        </td>
                                    </tr>

                                    <tr>
                                        <td class="separation"><label for="lieu">Lieu</label></td>
                                        <td> 

                                         <div>
                                           {{ form_errors(form.location) }}

                                           {{ form_widget(form.location) }}
                                          </div>

                                        </td>
                                    </tr>
                                    <tr>
                                        <td id="description" valign="top" class="separation"><label for="description">Description</label></td>
                                        <td><textarea id="ikproj_groupebundle_eventsgroupe_description" name="ikproj_groupebundle_eventsgroupe[description]" rows="5" cols="40"></textarea> 



                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" align="center" id="button" valign="bottom"><input class="button" type="submit" value=""/></td>
                                    </tr>
                                </table>
                                         {{form_widget(form._token)}} 
                            </form>
                        </td>
                    </tr>
                </table> 
            </div>
        </div>
    </center>
</body>
</html>

And this is the form class code:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder

        ->add('title','text')
        ->add('start','datetime',array(
         'input' => 'datetime',

         'format' => 'dd/MM/yyyy H:i',
         'minutes' => array(
            0,
            30
           )
         ))
        ->add('end','datetime',array(
         'input' => 'datetime',

         'format' => 'dd/MM/yyyy H:i',
         'minutes' => array(
            0,
            30
          ) 
        ))

        ->add('location','text')
        ->add('description','text')

    ;
}

Actually, what I would like to do is to compare the values of the two datetime fields "start" and "end". Therefore I need to access to the value of each of that fields. By the way, please focus on this part of JavaScript code (which is at the top of the html form code):

<script>
        function f1(){
            if(form_widget(form.start)>form_widget(form.end)){
                alert("no");
            }
        }
    </script>

So, my question is: what will be the correct code to do that?

2 Answers 2

1

Why you don't access directly to properties of the HTML generated elements at Javascript? Like for example ID or class or name or something else.

Anyway if you'll like to access any var that comes from controller to Twig view you can do it as follow:

<script>
    alert('{{ myvar }}');
</script>

Notice you are tying to access form_widget and that returns the complete HTML element, for example:

<input type="text" name="form[title]" id="form[title]" /> 

and not the value of that input, take care of that.

Second solution based on your comments

Following your comments and your needs try this code instead:

<script>
    $(document).ready(function(){
        // I've to do it in this way since your button 
        // has none class or id to use in jQuery selector  
        // you should take care of that too

        $('input [type=submit]).on('click', function() {
            alert($('#ikproj_groupebundle_eventsgroupe_start').val());
        })
    }); 
</script>

A few things more:

  • I made a typo, yes, but remember I'm trying to help you with some ideas, I'm not doing your work so the best you can do is try to understand my code and apply to yours
  • As image shows you have Symfony datetime field so maybe my code won't work at all but give it a try
8
  • Well, for example how can I access to the value of the input {{ form_widget(form.start ) }}??...do you have any idea about how to do that??
    – Nadim
    Sep 1, 2014 at 15:19
  • As I said before, try to render your page and use a tool like Firebug for example, explore the code of your page and in somewhere should be the result of {{ form_widget(form.start ) }} but rendered as plain HTML, after that check for the ID, name or class and access it from Javascript, for example if the result HTML code is <input type="text" name="form[start]" id="form[start]" /> then from Javascript you could do something like $('#form[start]').val() and you'll have the value on that field. Notice I use jQuery for the example
    – ReynierPM
    Sep 1, 2014 at 15:30
  • In order to know the id of the form field "start" I tried this code: alert('{{ form.start.vars.id|e('js') }}'); and I obtained as an alert message this one: ikproj_groupebundle_eventsgroupe_start ... Then I tried this code: alert($('#ikproj_groupebundle_eventsgroupe_start').val()); but what I obtained is an empty alert message!...So what is wrong in that code??...what is the correct code??...do you have any idea??
    – Nadim
    Sep 1, 2014 at 16:30
  • Of course it will return and empty alert since you're not setting any value to that input by default, check your own code and you will see what I'm talking about. You can try this instead $(document).ready(function(){ $('#ikproj_groupebundle_eventsgroupe_start').on('change, function() { alert$(this).val() } }); and you should see the new value write on the input text and try to leave here the HTML generated after you load the page, I'm talking as a wizard since I don't get what you're doing
    – ReynierPM
    Sep 1, 2014 at 17:04
  • What I am trying to do is that when I click on the button to submit the form, an alert message displays containing the value of the field "start". By the way, I tried: $(document).ready(function(){ $('#ikproj_groupebundle_eventsgroupe_start').on('change, function() { alert$(this).val() } }); but it didn't work!!
    – Nadim
    Sep 2, 2014 at 8:29
0

You can retrieve the id of the form fields in your javascript like this :

"{{ form.start.vars.id|e('js') }}"

Then, using this id, retrieve your javascript/jQuery/... element and get its value.

If you are planing to use this form field on different forms, it may be a good idea to create a custom FormType that will add classes to the html output of your to date fields and base your javascript selector on this classes.

4
  • Well, I tried that, Actually I put this code: alert({{ form.start.vars.id|e('js') }}); and once the form is submitted I see this alert message: [object HTMLDivElement] ...As you can notice in my code there is no id for any form fields as they are all in twig.
    – Nadim
    Sep 1, 2014 at 15:37
  • don't forget the quotes : alert('{{ form.start.vars.id|e('js') }}');
    – rolebi
    Sep 1, 2014 at 15:44
  • Do you use jQuery or an other javcascript framework ?
    – rolebi
    Sep 1, 2014 at 15:45
  • Yes, I am using jQuery. By the way, I tried alert('{{ form.start.vars.id|e('js') }}'); and this is what I obtained as an alert message: ikproj_groupebundle_eventsgroupe_start ...so how can I exploit this data??...what shall I put as a code?
    – Nadim
    Sep 1, 2014 at 15:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.