简体   繁体   中英

How to create a confirm box with Twig and Symfony2 to redirect the user to page

When pushing a delete button, i'd like an alert to pop up to make sure the user didn't make any mistake.

So, In codeIgniter I had this that worked well:

Button:

<td><a class='Right btn btn-danger' onClick="ConfirmMessage('news', <?php echo $new->id ?>,'news')">
                        <i class="icon-remove-sign icon-white"></i>
                    </a></td>

Javascript:

function ConfirmMessage(type, id, types) {
    if (confirm("Are you sure you want to delete this "+type+" ?")) { // Clic sur OK
     document.location.href='<?php echo site_url(); ?>/'+types+'/delete/'+id;
    }
  }

But now, with Symfony2, I can't do this:

Button

<td><a class='Right btn btn-danger' onClick="ConfirmMessage('artist', {{ artist.id }},'news')">
                            <i class="icon-remove-sign icon-white"></i>
                        </a></td>

Javascript

function ConfirmMessage(type, id, types) {
    if (confirm("Are you sure you want to delete this "+type+" ?")) { // Clic OK
        document.location.href="{{ path('ymtest_Delete'"+types+", {'id': "+id+"}) }}";
    }
}

Since I get an error when Symfony wants to generate a url.

What could be a solution ? Thanks

you can't write

 document.location.href="{{ path('ymtest_Delete'"+types+", {'id': "+id+"}) }}";

you are mixing twig functions and javascript functions. Twig will be parsed and compiled on backend Javascript will be executed on your client side after the html page is received

You will have to generate and assign each url type to a javascript variable.

a more elegant way to do that would be to store your url and messages in data attributes

<a class="Right btn btn-danger" data-url="{{ path('ymtest_EditMusician', {'id': artist.id}) }}" data-message="Are you sure you want to delete this type ?" ></a>

you can now bind your event click with javscript and retrieve your data attributes values. No more javascript tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM