Symfony2 - Sonata Admin - add javascript before field

Working for me:

In admin class src\PP\TestBundle\TestAdmin.php

public function configure() {
    $this->setTemplate('edit', 'PPTestBundle:CRUD:edit_javascript.html.twig');
}

In src\PP\TestBundle\Resources\views\edit_javascript.html.twig

{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('bundles/pptest/admin/js/myscripts.js') }}" type="text/javascript"></script>
{% endblock %}

When you do all this stuff and you have upload myscripts.js you should send this in command line:

app/console assets:install web

(possible that I forgot something)

Sorry for my bad English :<>


Starting from sonata admin 3.x you can add/remove js/css to/from the page without extending it.

sonata_admin:
    ....
    assets:
        # javascript paths to add to the page in addition to the list above
        extra_javascripts:
            - 'your js file path'
        # javascript paths to remove from the page
        remove_javascripts: 
            - 'your js file path'

you can find more information here https://github.com/sonata-project/SonataAdminBundle/pull/4836/files?short_path=e252be0#diff-e252be027e26148c11d971dc969f4be0


EDITED

You need to create a custom TWIG template for it (where you could place your javascript code just before the widget code).

Then you write inside ap/config/config.yml where your custom template is to allow Symfony and SonataAdmin to recognize it.

You have some info here Sonata Admin - Custom template

More info here customize field types

An example could be something like this:

Admin class

protected function configureFormFields(FormMapper $formMapper) {
    $formMapper
            ->add('name', 'ajax_autocomplete')
            ->add('description', 'text')
    ;
}

And, in the TWIG template you need to extend from the Sonata Admin field template that better fits your necessities. In this case maybe base_edit.html.twig or edit_text.html.twig

You have a list of templates to extend from, inside this Sonata Admin dir: vendor\sonata-project\admin-bundle\Sonata\AdminBundle\Resources\views\CRUD

Customization

Imagine you have placed your custom template inside XXXBundle:YYY:ajax_autocomplete.html.twig

I think it should work if you write a line here:

sonata_doctrine_orm_admin:
    templates:
        types:
            list:
                ajax_autocomplete: XXXBundle:YYY:ajax_autocomplete.html.twig