简体   繁体   中英

JS button event with redirect (Sonata Admin)

I'm using Sonata Admin for my project and I have a SweetAlert 2 on $('button[type="submit"]') event.

The problem is that initially I'm using preventDefault() to keep form alive, then I'm trying to submit form with $(form).submit() but I'm redirected to the same EDIT page even if I click on "Update & Close" page.

FYI: Sonata has 2 possibilities:'Update' & 'Update and close'. First one is updating entity and redirect you to the same page, the other one, is updating entity and redirecting you to listing page.

$('button[type="submit"]').click(function (e) {
    var currentStatus = $('#' + adminUniqueId + '_status option:selected').val();
    var exitDate = $('#' + adminUniqueId + '_exitDate').val().trim();
    var form = $(this).parents('form');
    var nextPage = $(this).attr('name');

    loanId = parseInt(loanId);

    // Modal operations
    if((currentStatus === closedStatus || exitDate !== '') && loanId !== 0) {
        if (outstandingBalance > 0) {
            e.preventDefault(); // Stop action until we find a response.

            swal({
                title: 'Current outstanding principal balance is $' + numberFormatter.format(outstandingBalance) + '. How much do you want to write off ?',
                input: 'text',
                width: '600px',
                inputClass: 'money-mask',
                showCancelButton: true,
                confirmButtonText: 'Close this loan',
                showLoaderOnConfirm: true,
                preConfirm: function (amount) {
                    return new Promise(function (resolve, reject) {
                        var convertedAmount = getValueFromFormattedNumber(amount);

                        if (isNaN(convertedAmount)) {
                            reject('Please write an amount.')
                        } else if (convertedAmount < 0 || convertedAmount > outstandingBalance) {
                            reject('The write-off amount is greater than the outstanding principal balance.')
                        } else {
                            $.ajax({
                                type: "POST",
                                url: setLoanTransactionRoute,
                                data: {
                                    loanId: loanId,
                                    outstandingBalance: outstandingBalance,
                                    amountToWriteOff: convertedAmount
                                },
                                success: function (data) {
                                    if (true === data.success) {
                                        $('#' + adminUniqueId + '_status').val(closedStatus).change();
                                        setTimeout($(form).submit(), 500);

                                        resolve();

                                    } else {
                                        reject('We found an error: ' + data.message + '.')
                                    }
                                },
                                error: function (response, textStatus, jqXHR) {
                                    reject("Something went wrong and we couldn't add this transaction. Please check if you have a write-off and/or repayment loan category.")
                                }
                            });
                        }
                    })
                }
            });
        }
    }
});

When user click the [Update] button, It will redirect to the same edit page and when user click the [Update and close button] will redirect to the listing page instead

As documented by swal plugin, You can call the deferred callback then by the time swal preConfirm function callback:

https://limonte.github.io/sweetalert2/

Here's a given reference code:

Note: I've place a [id] attribute for this given form and some additional conditions as well

 $('#frm-submit input[type="submit"]').click(function(event) { event.preventDefault(); var aValidSubmitValues = ['Update', 'Update and Close']; var sButtonValue = $(this).val(); if ($.inArray(sButtonValue, aValidSubmitValues) < 0) { return false; } var convertedAmount = '123.00'; var outstandingBalance = '200.00'; swal({ title: 'Current outstanding principal balance is $100.00 How much do you want to write off ?', input: 'text', width: '600px', inputClass: 'money-mask', showCancelButton: true, confirmButtonText: 'Close this loan', showLoaderOnConfirm: true, preConfirm: function(amount) { return new Promise(function(resolve, reject) { if (isNaN(convertedAmount)) { reject('Please write an amount.') } else if (convertedAmount < 0 || convertedAmount > outstandingBalance) { reject('The write-off amount is greater than the outstanding principal balance.') } else { // Your given ajax code up until the resolve callback parameter // Your $.ajax() here until resolve resolve(); } }); } }).then(function(response) { console.log('You have click the ' + sButtonValue + ' button'); if (sButtonValue === 'Update') { console.log('Reload the page'); // location.reload() } else { console.log('Go to a certain listing page'); // location.href = '/list-of-transaction-page'; } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.5/sweetalert2.all.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <form id="frm-submit"> <input type="submit" value="Update" /> <input type="submit" value="Update and Close" /> </form> </div> 

Hope this will guide you well

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