Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traverse twig array in javascript block

Using Symfony2.3.4 and PHP5.6.3.

I need to THE TITLE.

See, I have this template

{#new.html.twig#}

{% extends 'GCBundle::layout.html.twig' %}

{% block title %}{{parent()}} | Create chart {%endblock title %}

{% block content -%}
    {% if errors is defined %}
        {#not sure if I need this#}    
    {% endif %}

    <FORM class="form-horizontal" action="{{path('chart_create', { 'id' : entity.id })}}"
          method="post" {{ form_enctype(form) }}>
        <center><h3>Create chart</h3></center>

        {{ form_widget(form) }}
        <DIV class="form-actions">
            <BUTTON name="submit" type="submit"
                    class="btn btn-primary"><I class="glyphicon-check"></I>
                {{ 'Save'|trans }}</BUTTON>
            <a class="btn" href="{{ path('chart') }}">
                <I class="glyphicon-ban"></I> {{ 'Cancel'|trans }}</a>
        </DIV>
    </FORM>
{% endblock %}
{% block javascripts %}
    {{parent()}}
    {% if errors is defined %}
    <script type="text/javascript">
        alert({{errors}}); //THIS DOESN'T WORK, JUST SO U KNOW WHAT I NEED
    </script>
    {% endif %}
{% endblock %}

The variable errors is a simple array structured: $key --> <fieldname> and
$value --> <errormessage>, this varible comes from the controller,
so far so normal.

Now, I need to use that array in the js block to alert the error or tooltip it or what ever but I need to access its keys and values like, say, with the .each() function.

SAMPLE ERROR:

array (size=1)
  'CI' => 'CI must be unique'

EDIT:

array (size=2)
  'CI' => string 'CI must be unique' (length=53)
  'height' => string 'This value is not valid.' (length=24)

This is what an error looks like when I {{dump(errors)}} in the template.

Look, I could find a workaround for this (for example)splitting the array into two arrays(one with the keys and the other one with the values) with auto-generated integer indexes each so I could traverse it with a for loop instead of an .each() function as I want, but I thought this would be a good moment to add this one to the "knowledge bag", corny as it sounds...

if you could please show some code with the ideas in your comments...

EDIT2:

I tried the json_encode like this:

ChartController.php
$errors = array();
        foreach ($form as $field) {
            if ($field->getErrors()) {
                $errors [$field->getName()] = $field->getErrors();
                $errors[$field->getName()] = $errors[$field->getName()][0]->getMessage();
            }
        }

        return $this->render('GCBundle:Chart:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    'errors' => json_encode($errors),
        ));

Now when I {{dump(errors)}} in the template it outputs:

string '{"CI":"CI must be unique","height":"This value is not valid."}' (length=102)

and my actual javascript block:

new.html.twig
{% block javascripts %}
    {{parent()}}
    {{dump(errors)}}
    {% if errors is defined %}
    <script type="text/javascript">
        var temp = {{errors}};
        $.each(temp, function(k,v){
            alert(k);
        });

    </script>
    {% endif %}
{% endblock %}

I need to traverse it somehow but if I use the code above, the browser's console outputs this js error:

SyntaxError: invalid property id

EDIT3:

I checked your link but although it serializes the $errors OK, it doesn't say anything about outputing those errors in a javascript block which is what I actually need.

Take a look at all the ways I've tried and I hope you can come up with something from the errors I'm getting:

1-

//With the serializer
//ChartController.php
$errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);

        return $this->render('GCBundle:Chart:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    'errors' => $errors,
        ));

//new.html.twig
<script type="text/javascript">
var errors = {{errors}};
//WHETHER I USE A FOR LOOP
for(var err in errors){
    alert(err);
}
//OR AN $.EACH() FUNCTION
$.each(errors, function(k,v){
    alert(k);
});
</script>

ERROR:

An exception has been thrown during the rendering of a template  
("Notice: Array to string conversion in C:\xampp\htdocs\Projects\GC\app\cache  
\dev\twig\1a\00\0a022cd3a377dd20d520580dffea.php line 100") in  
GCBundle:Chart:new.html.twig at line 31.

2-

//Without the serializer
//ChartController.php
$errors = array();
foreach ($form as $field) {
    if ($field->getErrors()) {
        $errors [$field->getName()] = $field->getErrors();
        $errors[$field->getName()] = $errors[$field->getName()][0]->getMessage();
    }
}

return $this->render('GCBundle:Chart:new.html.twig', array(
    'entity' => $entity,
    'form' => $form->createView(),
    'errors' => json_encode($errors),
));

//new.html.twig
<script type="text/javascript">
var errors = {{errors}};
//WHETHER I USE A FOR LOOP
for(var err in errors){
    alert(err);
}
//OR AN **$.EACH()** FUNCTION
$.each(errors, function(k,v){
    alert(k);
});
</script>

ERROR:

SyntaxError: invalid property id
like image 544
Scaramouche Avatar asked Jun 09 '15 18:06

Scaramouche


2 Answers

Here I found my answer at last, when I could finally identify the source of the problem thanks to FireBug.

In the controller I did the same without the serializer:

        $errors = array();
        foreach ($form as $field) {
            if ($field->getErrors()) {
                $errors [$field->getName()] = $field->getErrors();
                $errors[$field->getName()] = $errors[$field->getName()][0]->getMessage();
            }
        }

        return $this->render('GCBundle:Chart:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    'errors' => $errors,
        ));

and in the template:

<script type="text/javascript">
    function getJSonObject(value) {
        return $.parseJSON(value.replace(/&quot;/ig, '"'));
    }

    var storeJSON = getJSonObject("{{errors|json_encode()}}");

    $.each(storeJSON, function(k,v){
        alert('Key = ' + k + '\n' + 'Value = ' + v);
    });
</script>

The problem was that each() was not dealing very well with &quot;, so as soon as I do this to errors:

getJSonObject("{{errors | json_encode()}}"),

VOILÀ!!! each() works OK.

like image 82
Scaramouche Avatar answered Sep 29 '22 13:09

Scaramouche


As mentioned in this SO answer, you could also use another filter that will do that you want:

{{ errors|json_encode|raw }}
like image 27
Jérémy Cornut Avatar answered Sep 29 '22 12:09

Jérémy Cornut