Search code examples
phparrayssymfonytwigvichuploaderbundle

Exception generated by PropertyMappingFactory class with trying to the first element of an array with twig


I have a Motors entity having an OneToMany relation with the File entity. Uploading files and linking them is done with VichUploaderBundle.

My objective is giving a simple overview of a Motors object by displaying just the first image of that object. Since, I am using twig for displaying my object, I used the first filter of twig as follows:

{{ vich_uploader_asset(motors.files|first, 'motors_files') }}

This was not successful. The error I got is:

An exception has been thrown during the rendering of a template ("Impossible to determine the class name. Either specify it explicitly or give an object") in MinnAdsBundle:Motors:index.html.twig at line 75

It seems that exception is generated by that class PropertyMappingFactory.php.

I also tried this:

{%for f in motors.files|first %}
    {{ vich_uploader_asset(f, 'motors_files') }}<br>
{%endfor%}

But, there is nothing rendered. There is also no error generated!!! This is strange since applying the filters first and 'length' returns the expected value (1 or 0):

{{motors.files|first|length}} {#always return the expected value#}

I did even more checks as seen below but without success! So, could you help with that issue?

Thanks!

{# the length of the array#}
{{motors.files|length}} {# tells me that there is 3 files! (worked perfectly)#}

{# Retrieving all the links of these file (worked perfectly)#}
{%for f in motors.files%}
    {{ vich_uploader_asset(f, 'motors_files') }}<br>
{%endfor%}

Solution

  • I ended the problem by an if condition in the loop:

    {%for f in motors.files%}
        {%if loop.index == 1%}
            src="{{ vich_uploader_asset(f, 'motors_files')}}"
       {% endif %}
    {%endfor%}
    

    There is a problem with the VichUploaderBundle when dealing with the filter first.