0

On an application I created a form with a field (select) in EntityType, I then passed it to select2, no problem there.

The twig view looks like an array of all saved helpers and you can modify a helper by opening a modal, I correctly pass my value twig to js with dataset and all the fields are filled in correctly.

To better have a little visual, my button that opens my modal and sends it all the info looks like this :

    <a href="javascript:;" class="menu-link px-3" {{ stimulus_action('deal--handle', 'editHelp') }} data-url2="{{ path('help_request_edit', {'id':help.id}) }}" data-organisme="{{ help.organization.value }}" data-date="{{ help.date|date('Y-m-d') }}" data-state="{{ help.state }}" data-amount-requested="{{ help.amountRequested }}" data-amount-to-deduct="{{ help.amountToDeduct }}" data-subrogation="{{ help.subrogation }}" data-quotations="{{ quotationInHelp|json_encode }}">
       Modify
    </a> 

data-quotations="{{ quotationInHelp|json_encode }}" send the data to js and I get it like this:

var quotations = JSON.parse(event.currentTarget.dataset.quotations);

in my console.log(quotations) everything is ok.

but I can't find how to use the data of my "quotations" variable to pass them into values ​​of my select2, for example the other fields of my modal are filled like this:

        this.subrogationTarget.value = event.currentTarget.dataset.subrogation;

if you have any ideas/solutions for this problem, thank you!

3
  • The filter json_encode doesn't mark the output as safe, as seen here. You need to add the filter raw as well Commented Aug 28, 2023 at 13:58
  • Does this answer your question? Pass variable from twig to js Commented Aug 28, 2023 at 13:59
  • It does not work because my button to edit the modal is specific to an element.the entity that I have to display in the select2 is finally a ManyToMany relationship. #[ORM\ManyToMany(targetEntity: Quotation::class, inversedBy: 'helpRequests')] private Collection $quotations; ` {% set quotationInHelp = [] %} quotationsInHelp contains an array of my entity(ies) linked to a helpRequest and it is this "quotationsInHelp" that I want to pass to js, ​​an array with one/several entities Commented Aug 29, 2023 at 9:48

1 Answer 1

0

I finally found the solution with a few lines of javascript

var quotations = JSON.parse(event.currentTarget.dataset.quotations);
var i = 0;
    var idQuotations = [];
    for (let i = 0; i < quotations.length; ++i) {
        idQuotations.push(
            quotations[i]['quotation']
        );
    }
    $(this.quotationTarget).val(idQuotations).trigger("change");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.