Javascript – How to convert an object to a string (Twig & Symfony)

datatablesjavascriptloopssymfonytwig

I have a jquery function that is mixed with twig data:

$(document).on('change', '.item-select', function() {

var optionValue = $(this).val();
{% for key, value in columns_arr %}
{% for k,v in group %}
if (optionValue == "{{ v.id }}") {
  {% set output = v %}
  {% for method in value|split('.') if method != '' %}
  {% set output = attribute(output, method) | default('') %}
  {% endfor %}
  var {{ value | split('.') | first }} = "{{ output }}";
}
{% endfor %}
{% endfor %}


if (optionValue) {
  var entity = $(this).find(':selected').attr('data-parent');
  var relation = $(this).find(':selected').attr('data-slug');
  var uuid= $(this).find(':selected').attr('data-id');


  table.row.add({
    {% for key, value in columns_arr %}
    {% for k,v in group %}
    "{{ value | split('.') | first }}": {{ value | split('.') | first }},
    {% endfor %}
    {% endfor %}
  }).draw();
  $('option', this).first().prop('selected', true);
  fetch(`/row/${entity}/${relation}/${uuid}/${optionValue}`,{
    method: 'POST'
  }).then(res => window.location.reload());
}

});

I get the error message:

An exception has been thrown during the rendering of a template
("Catchable Fatal Error: Object of class
Proxies__CG__\App\Entity\Productgroup could not be converted to
string").

And the error should be in this line:

var {{ value | split('.') | first }} = "{{ output }}";

Best Answer

If you give Twig an object, it implicitly calls the __toString() method on that object. That is how you get the error message.

Are you looking for a variable value on that object? In such case, use the field name (e.g. output.something).

What you are apparently trying to do is use the object as an object and handle it with javascript functions. The easiest way to do that is typically to use the json_encode filter, which will produce a JSON object with proper encoding and everything, provided your underlying Symfony/Doctrine object is clean.

var {{ value | split('.') | first }} = "{{ output | json_encode }}";

should do the trick.

But honestly, I think that style of code is asking for trouble. You should assign your variables explicitly and not iterate over field names the way you seem to be doing.