Как я могу расширить шаблон с помощью пользовательского javascript для модального окна в Sonata Admin (Symfony 3.3, PHP 7)? - PullRequest
0 голосов
/ 02 мая 2018

У меня есть структура сущности:

Deal -->       DealCondition <-- Product
id             id                id
dealConditons  product           name   

У меня есть разделы администратора:

DealAdmin:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('dealConditions', 
        'sonata_type_collection',
        [
            'by_reference' => false,
            'required' => false,
        ],
        [
            'edit'     => 'inline',
            'inline'   => 'table',
            'sortable' => 'position',
        ]);
...}

ProductConditionAdmin:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('product','sonata_type_model');
}

ProductAdmin:

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

На странице ProductAdmin мне нужен некоторый javascript для моих целей, поэтому я сделал это:

    application.admin.product:
    class: ...\ProductAdmin
    tags:
      - { name: sonata.admin, manager_type: orm, label_translator_strategy: "sonata.admin.label.strategy.underscore"}
    arguments:
      - ~
      - ...\Product
      - ~
    calls:
      - [setTemplates, [{
        edit: ApplicationDealBundle:ProductAdmin:edit.html.twig}]]

И в edit.html.twig:

{% block javascripts %}
    {{ parent() }}<script type="text/javascript">MyScript();</script>
{% endblock %}

Все работает, когда я открываю ProductAdmin в качестве главной страницы, но когда я нажимаю кнопку «Добавить новый продукт» рядом с полем «Продукт» во вложенной форме DealConditions, сценарий не существует. Как это выглядит

Как я могу добавить скрипт? Спасибо.

1 Ответ

0 голосов
/ 24 августа 2018

Возможно, вы уже решили эту проблему, но у меня вчера была такая же проблема, поэтому я расскажу, как поступил, если сюда придут другие.

Возможно, есть лучшие / более элегантные решения, но пока это работает просто отлично. Что я сделал, так это переопределил базу edit_many_script.html.twig, которая manages the many-to-[one|many] association field popup

Скопируйте, вставьте файл из vendor и поместите его в каталог app/Resources/SonataAdminBundle/views/CRUD/Association (или создайте его).

Внутри файла вы найдете этот ajax-вызов для получения формы администратора для вашей сущности:

// retrieve the form element from the related admin generator
jQuery.ajax({
    url: a.attr('href'),
    dataType: 'html',
    success: function(html) {
         Admin.log('[{{ id }}|field_dialog_form_edit] ajax success', field_dialog_{{ id }});
         // populate the popup container
         field_dialog_content_{{ id }}.html(html);
         field_dialog_title_{{ id }}.html("{{ associationadmin.label|trans({}, associationadmin.translationdomain) }}");

         Admin.shared_setup(field_dialog_{{ id }});

         // capture the submit event to make an ajax call, ie : POST data to the
         // related create admin
         jQuery(document).on('click','#field_dialog_{{ id }} a', field_dialog_form_action_{{ id }});
         jQuery('form', field_dialog_{{ id }}).on('submit', field_dialog_form_action_{{ id }});

         // open the dialog in modal mode
         field_dialog_{{ id }}.modal();

         Admin.setup_list_modal(field_dialog_{{ id }});
    }
});

Вы можете добавить свой сценарий туда. Обратите внимание, что он будет использоваться по умолчанию для каждого отношения многие к X, поэтому, если вы хотите, чтобы ваш скрипт загружался только в определенных ситуациях, вы можете проверить {{ associationadmin.label|trans({}, associationadmin.translationdomain) }}, как показано ниже:

// retrieve the form element from the related admin generator
jQuery.ajax({
    url: a.attr('href'),
    dataType: 'html',
    success: function(html) {
         Admin.log('[{{ id }}|field_dialog_form_edit] ajax success', field_dialog_{{ id }});
         // populate the popup container
         field_dialog_content_{{ id }}.html(html);
         field_dialog_title_{{ id }}.html("{{ associationadmin.label|trans({}, associationadmin.translationdomain) }}");

         Admin.shared_setup(field_dialog_{{ id }});

         // capture the submit event to make an ajax call, ie : POST data to the
         // related create admin
         jQuery(document).on('click','#field_dialog_{{ id }} a', field_dialog_form_action_{{ id }});
         jQuery('form', field_dialog_{{ id }}).on('submit', field_dialog_form_action_{{ id }});

         // Custom JS for PopUpWidget Entity
         if("{{ associationadmin.label|trans({}, associationadmin.translationdomain) }}" === "PopUpWidget"){
             //your script
         }

         // open the dialog in modal mode
         field_dialog_{{ id }}.modal();

         Admin.setup_list_modal(field_dialog_{{ id }});
    }
});
...