Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17253 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
$acl            = $this->viewModel()->getRoot()->getVariable('acl');
$currentUser    = $this->currentUserHelper();

$roleName = $currentUser->getUserTypeId();

$routeAdd       = $this->url('media/categories/add');
$routeDatatable = $this->url('media/categories');
$routeDashboard = $this->url('dashboard');

$allowAdd               = $acl->isAllowed($roleName, 'media/categories/add') ? 1 : 0;
$allowEdit              = $acl->isAllowed($roleName, 'media/categories/edit') ? 1 : 0;
$allowDelete            = $acl->isAllowed($roleName, 'media/categories/delete') ? 1 : 0;

// NProgress
$this->headLink()->appendStylesheet($this->basePath('assets/vendors/nprogress/nprogress.css'));
$this->inlineScript()->appendFile($this->basePath('assets/vendors/nprogress/nprogress.js'));

// Datatables
$this->inlineScript()->appendFile($this->basePath('assets/vendors/datatables.net/jquery.dataTables.js'));
$this->headLink()->appendStylesheet($this->basePath('assets/vendors/datatables.net-bs5/dataTables.bootstrap5.css'));
$this->headLink()->appendStylesheet($this->basePath('assets/vendors/datatables.net-bs5-responsive/responsive.bootstrap5.css'));
$this->inlineScript()->appendFile($this->basePath('assets/vendors/datatables.net/jquery.dataTables.js'));
$this->inlineScript()->appendFile($this->basePath('assets/vendors/datatables.net-bs5/dataTables.bootstrap5.js'));
$this->inlineScript()->appendFile($this->basePath('assets/vendors/datatables.net-bs5-responsive/dataTables.responsive.min.js'));
$this->inlineScript()->appendFile($this->basePath('assets/vendors/datatables.net-bs5-responsive/responsive.bootstrap5.min.js'));

$this->inlineScript()->captureStart();
echo <<<JS
    jQuery(document).ready(function ($) {
        var allowEdit = $allowEdit
        var allowDelete = $allowDelete

        // Datatable
        var gridTable = $('#gridTable').dataTable({
            processing: true,
            serverSide: true,
            searching: true,
            order: [[0, 'asc']],
            ordering: true,
            ordenable: true,
            responsive: true,
            select: false,
            paging: true,
            pagingType: 'simple_numbers',
            ajax: {
                url: '$routeDatatable',
                type: 'get',
                beforeSend: function (request) {
                    NProgress.start()
                },
                dataFilter: function (response) {
                    try {
                        console.log(response); // Para depuración
                        var jsonResponse = JSON.parse(response);

                        var json = {};
                        json.recordsTotal = 0;
                        json.recordsFiltered = 0;
                        json.data = [];

                        if (jsonResponse.success) {
                            json.recordsTotal = jsonResponse.data.total;
                            json.recordsFiltered = jsonResponse.data.total;
                            json.data = jsonResponse.data.items;
                        } else {
                            $.fn.showError(jsonResponse.data);
                        }

                        return JSON.stringify(json);
                    } catch (e) {
                        console.error("Error parsing JSON response:", e);
                        $.fn.showError("Invalid JSON response from server.");
                        return JSON.stringify({ recordsTotal: 0, recordsFiltered: 0, data: [] });
                    }
                }
            },
            language: {
                sProcessing: 'LABEL_DATATABLE_SPROCESSING',
                sLengthMenu: 'LABEL_DATATABLE_SLENGTHMENU',
                sZeroRecords: 'LABEL_DATATABLE_SZERORECORDS',
                sEmptyTable: 'LABEL_DATATABLE_SEMPTYTABLE',
                sInfo: 'LABEL_DATATABLE_SINFO',
                sInfoEmpty: 'LABEL_DATATABLE_SINFOEMPTY',
                sInfoFiltered: 'LABEL_DATATABLE_SINFOFILTERED',
                sInfoPostFix: '',
                sSearch: 'LABEL_DATATABLE_SSEARCH',
                sUrl: '',
                sInfoThousands: ',',
                sLoadingRecords: 'LABEL_DATATABLE_SLOADINGRECORDS',
                oPaginate: {
                    sFirst: 'LABEL_DATATABLE_SFIRST',
                    sLast: 'LABEL_DATATABLE_SLAST',
                    sNext: 'LABEL_DATATABLE_SNEXT',
                    sPrevious: 'LABEL_DATATABLE_SPREVIOUS'
                },
                oAria: {
                    sSortAscending: ': LABEL_DATATABLE_SSORTASCENDING',
                    sSortDescending: ':LABEL_DATATABLE_SSORTDESCENDING'
                }
            },
            drawCallback: function (settings) {
                NProgress.done()
            },
            aoColumns: [{ mDataProp: 'name' }, { mDataProp: 'actions' }],
            columnDefs: [
                {
                    targets: 0,
                    className: 'text-vertical-middle'
                },
                {
                    targets: -1,
                    orderable: false,
                    render: function (data, type, row) {
                        s = ''

                        if (allowEdit) {
                            s =
                                s +
                                '<button class="btn btn-primary btn-edit" data-href="' +
                                data['link_edit'] +
                                '" data-toggle="tooltip" title="LABEL_EDIT"><i class="fa fa-pen"></i> LABEL_EDIT </button>&nbsp;'
                        }
                        if (allowDelete) {
                            s =
                                s +
                                '<button class="btn btn-danger btn-delete" data-href="' +
                                data['link_delete'] +
                                '" data-toggle="tooltip" title="LABEL_DELETE"><i class="fa fa-trash"></i> LABEL_DELETE </button>&nbsp;'
                        }
                        return s
                    }
                }
            ]
        })

        // Form Validator
        var validator = $('#form').validate({
            debug: true,
            onclick: false,
            onkeyup: false,
            ignore: [],
            rules: {
                name: {
                    required: true,
                    maxlength: 100
                }
            },
            submitHandler: function (form) {
                $.ajax({
                    dataType: 'json',
                    accept: 'application/json',
                    method: 'post',
                    url: $('#form').attr('action'),
                    data: $('#form').serialize()
                })
                    .done(function (response) {
                        NProgress.start()
                        if (response['success']) {
                            $.fn.showSuccess(response['data'])

                            $('#modal').modal('hide')

                            gridTable.api().ajax.reload(null, false)
                        } else {
                            validator.resetForm()
                            if (jQuery.type(response['data']) == 'string') {
                                $.fn.showError(response['data'])
                            } else {
                                $.each(response['data'], function (fieldname, errors) {
                                    $.fn.showFormErrorValidator('#form #' + fieldname, errors)
                                })
                            }
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        $.fn.showError(textStatus)
                    })
                    .always(function () {
                        NProgress.done()
                    })
                return false
            },
            invalidHandler: function (form, validator) { }
        })

        // Button Add
        $('body').on('click', 'button.btn-add', function (e) {
            e.preventDefault()

            $('#form').attr('action', '$routeAdd')
            $('#form #name').val('')

            validator.resetForm()
            $('#modal').modal('show')
        })

        // Button Edit
        $('body').on('click', 'button.btn-edit', function (e) {
            e.preventDefault()
            NProgress.start()
            var action = $(this).data('href')

            $.ajax({
                dataType: 'json',
                accept: 'application/json',
                method: 'get',
                url: action
            })
                .done(function (response) {
                    if (response['success']) {
                        $('#form').attr('action', action)
                        $('#form #name').val(response['data']['name'])

                        validator.resetForm()

                        $('#modal').modal('show')
                    } else {
                        $.fn.showError(response['data'])
                    }
                })
                .fail(function (jqXHR, textStatus, errorThrown) {
                    $.fn.showError(textStatus)
                })
                .always(function () {
                    NProgress.done()
                })
        })

        // Button Delete
        $('body').on('click', 'button.btn-delete', function (e) {
            e.preventDefault()
            var action = $(this).data('href')

            swal
                .fire({
                    title: 'LABEL_ARE_YOU_SURE',
                    icon: 'question',
                    cancelButtonText: 'LABEL_NO',
                    showCancelButton: true,
                    confirmButtonText: 'LABEL_YES'
                })
                .then((result) => {
                    if (result.isConfirmed) {
                        NProgress.start()
                        $.ajax({
                            dataType: 'json',
                            accept: 'application/json',
                            method: 'post',
                            url: action
                        })
                            .done(function (response) {
                                if (response['success']) {
                                    $.fn.showSuccess(response['data'])
                                    gridTable.api().ajax.reload(null, false)
                                } else {
                                    $.fn.showError(response['data'])
                                }
                            })
                            .fail(function (jqXHR, textStatus, errorThrown) {
                                $.fn.showError(textStatus)
                            })
                            .always(function () {
                                NProgress.done()
                            })
                    }
                })
        })

        // Button Refresh
        $('body').on('click', 'button.btn-refresh', function (e) {
            e.preventDefault()
            gridTable.api().ajax.reload(null, false)
        })

        // Button Cancel
        $('body').on('click', 'button.btn-cancel', function (e) {
            e.preventDefault()
            $('#modal').modal('hide')
        })
    })
JS;
$this->inlineScript()->captureEnd();
?>

<div class="container">
    <div class="row">
        <div class="col-12 mt-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="card-title">LABEL_MEDIA_CATEGORIES</h6>
                    <div class="row">
                        <div class="col-12  mt-3">
                            <table id="gridTable" class="table   table-bordered">
                                <thead>
                                    <tr>
                                        <th>LABEL_NAME</th>
                                        <th>LABEL_ACTIONS</th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="card-footer text-right">
                    <button type="button" class="btn btn-info btn-refresh">
                        <i class="fa fa-sync"></i> LABEL_REFRESH
                    </button>

                    <?php if ($allowAdd) : ?>
                        <button type="button" class="btn btn-primary btn-add">
                            <i class="fa fa-plus"></i> LABEL_ADD
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- The Modal -->
<div class="modal" id="modal">
    <div class="modal-dialog  modal-lg">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h6 class="modal-title">LABEL_CATEGORIES</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
            </div>

            <?php
            $form = $this->form;
            $form->setAttributes([
                'method'    => 'post',
                'name'      => 'form',
                'id'        => 'form'
            ]);

            $form->prepare();
            echo $this->form()->openTag($form);
            ?>

            <!-- Modal body -->
            <div class="modal-body">

                <div class="row">
                    <div class="col  mt-3">
                        <?php
                        $element = $form->get('name');
                        $element->setOptions(['label' => 'LABEL_NAME']);
                        $element->setAttributes(['class' => 'form-control']);

                        echo $this->formLabel($element);
                        echo $this->formText($element);
                        ?>
                    </div>
                </div>


            </div>

            <!-- Modal footer -->
            <div class="modal-footer text-right">
                <button type="submit" class="btn btn-primary">LABEL_SAVE</button>
                <button type="button" class="btn btn-light btn-cancel">LABEL_CANCEL</button>
            </div>
            <?php echo $this->form()->closeTag($form); ?>

        </div>
    </div>
</div>