CakephpAjax从POST数据中进行分页搜索


Cakephp Ajax search with Pagination from POST data

我正试图在cakehp2.x项目中创建一个搜索选项。

这是我的控制器代码-

    public function admin_index() {
    $this->Customer->recursive = 0;
    $this->Paginator->settings = array('order' => 'Customer.id DESC');
    $this->set('customers', $this->Paginator->paginate());
    // search form data
    $clients = $this->Customer->Client->find('list');
    $this->set(compact('clients'));     
}
public function admin_search() {
    $this->layout = 'ajax';
    if ( $this->request->is(array('post', 'ajax')) ) {
        $conditions = array();
        foreach ($this->request->data['Customer'] as $key => $value) {
            if (!empty($value))
            $conditions[$key . ' LIKE'] = '%' . $value . '%';
        }
        $this->Customer->recursive = 0;
        $this->Paginator->settings = array('order' => 'Customer.id DESC', 'conditions' => $conditions);
        $this->set('customers', $this->Paginator->paginate());          
    }
}

这是我的视图代码-

index.ctp

            <?php
        echo $this->Form->create('Customer', array(
            'action'    => 'search',
            'class'     => 'form-inline',
            //'novalidate' => true,
            'inputDefaults' => array(
                'label' => false,
                'div'   => 'form-group',
                'class' => 'form-control',
                'required' => false,
            )
        ));
        echo $this->Form->input('client_id', array(
            'empty'         => '--Select Client--'
        ));
        echo $this->Form->input('uid', array(
            'placeholder'   => 'UID'
        ));
        echo $this->Form->input('device', array(
            'placeholder'   => 'Device'
        ));
        echo $this->Form->input('debug', array(
            'placeholder'   => 'Debug',
            'options'       => array(1 => 'Yes', 0 => 'No'),
            'empty'         => '--Please Select--'
        ));         
        echo $this->Form->end();        
        ?>
<div id="result">   </div>

$("form").on('change keyup',function(e) {
    e.preventDefault(); //STOP default action
    $.ajax({
        type    : "POST",
        data    : $(this).serialize(),
        url     : "<?php echo Router::url(array('controller' => 'customers', 'action' => 'search', 'admin')); ?>",
        success : function(data) {
            $("#result").html(data);
        }
    });
    return false; //stop the actual form post !important!
}) ;

search.ctp

<?php if(!empty($customers)): ?>            
<table class="table table-striped table-condensed">
<thead>
<tr>
        <th><?php echo $this->Paginator->sort('id'); ?></th>
        <th><?php echo $this->Paginator->sort('client_id'); ?></th>
        <th><?php echo $this->Paginator->sort('uid'); ?></th>
        <th><?php echo $this->Paginator->sort('device'); ?></th>
        <th><?php echo $this->Paginator->sort('created'); ?></th>
        <th class="text-center"><?php echo $this->Paginator->sort('debug'); ?></th>
        <th class="actions"><?php echo __('Actions'); ?></th>
</tr>
</thead>
<tbody>
<?php
$index = 0;
$paginatorParams = $this->Paginator->params();
?>      
<?php foreach ($customers as $customer): ?>
<tr>
    <td><?php $index++; echo $index + ( ((int)$this->Paginator->counter('{:page}') - 1) * $paginatorParams['limit'] ); ?>&nbsp;</td>
    <td>
        <?php echo $this->Html->link($customer['Client']['name'], array('controller' => 'clients', 'action' => 'view', $customer['Client']['id'])); ?>
    </td>
    <td><?php echo h($customer['Customer']['uid']); ?>&nbsp;</td>
    <td><?php echo h($customer['Customer']['device']) . ' ' . h($customer['Customer']['version']); ?>&nbsp;</td>
    <td><?php echo h($customer['Customer']['created']); ?>&nbsp;</td>
    <td class="text-center"><span class="label label-sm <?php echo h($customer['Customer']['debug']) ? 'label-danger' : 'label-success' ?>"><?php echo $debug[h($customer['Customer']['debug'])]; ?></span></td>
    <td class="actions">
        <?php echo $this->Html->link(__('View'), array('action' => 'view', $customer['Customer']['id']), array('class' => 'btn btn-xs btn-primary')); ?>
        <?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $customer['Customer']['id']), array('class' => 'btn btn-xs btn-warning')); ?>
        <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $customer['Customer']['id']), array('class' => 'btn btn-xs btn-danger'), __('Are you sure you want to delete # %s?', $customer['Customer']['id'])); ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php echo $this->element('paginate'); ?>
<?php else: ?>
Customer not found
<?php endif; ?>

这完美地返回了结果。但问题是,当我想转到搜索结果的下一页时,它会返回错误。因为这次我没有把参数发送到控制器。我不知道该怎么做。

你能帮帮我吗?

 public function admin_index() {
        $this->User->recursive = 0;
        $this->set('title_for_layout', 'Admins Manager');
        $countries = $this->Country->find('list', array('fields' => array('id', 'country_name'), 'order' => array('country_name' => 'asc')));
        $this->set(compact('countries'));
        $this->set('total_users', $this->User->find('count', array('condition' => array('User.role_id' => 2))));
    }
    public function admin_list() {
        $this->layout = false;
        if (isset($this->request->data['customActionType']) && $this->request->data['customActionType'] == 'group_action') {
            $this->User->updateAll(array('User.status' => $this->request->data['customActionName']), array('User.id' => $this->request->data['id']));
        }
        $phone_con = $shop_name_con = $con = $email_con = $name_con = $country_con = $status_con = array();
        if (isset($this->request->data['name']) && $this->request->data['name'] != '') {
            $name_con = array('User.name LIKE' => '%' . $this->request->data['name'] . '%');
        }
        if (isset($this->request->data['email']) && $this->request->data['email'] != '') {
            $email_con = array('User.email LIKE' => '%' . $this->request->data['email'] . '%');
        }
        if (isset($this->request->data['shop_name']) && $this->request->data['shop_name'] != '') {
            $shop_name_con = array('User.shop_name LIKE' => '%' . $this->request->data['shop_name'] . '%');
        }
        if (isset($this->request->data['phone']) && $this->request->data['phone'] != '') {
            $phone_con = array('User.phone' => $this->request->data['phone']);
        }
        if (isset($this->request->data['country_id']) && $this->request->data['country_id'] != '') {
            $country_con = array('User.country_id' => $this->request->data['country_id']);
        }
        if (isset($this->request->data['status']) && $this->request->data['status'] != '') {
            $status_con = array('User.status' => $this->request->data['status']);
        }
        switch ($this->request->data['order'][0]['column']) {
            case 1:
                $order = array('User.name' => $this->request->data['order'][0]['dir']);
                break;
            case 2:
                $order = array('User.email' => $this->request->data['order'][0]['dir']);
                break;
            case 3:
                $order = array('User.shop_name' => $this->request->data['order'][0]['dir']);
                break;
            case 4:
                $order = array('Country.country_name' => $this->request->data['order'][0]['dir']);
                break;
            case 5:
                $order = array('User.phone' => $this->request->data['order'][0]['dir']);
                break;
            case 7:
                $order = array('User.status' => $this->request->data['order'][0]['dir']);
                break;
            default:
                break;
        }
        if (isset($this->request->data['start']) && $this->request->data['start'] != $this->request->data['length']) {
            $page = ($this->request->data['start'] / $this->request->data['length']) + 1;
        } elseif ($this->request->data['start'] == $this->request->data['length']) {
            $page = 2;
        } else {
            $page = 1;
        }
        $con = array_merge($phone_con, $shop_name_con, $email_con, $name_con, $country_con, $status_con, array('User.role_id' => 2));
        $this->paginate = array('conditions' => $con, 'limit' => $this->request->data['length'], 'order' => $order, 'page' => $page);
        $this->User->recursive = 1;
        $this->set('users', $this->paginate('User'));
        //pr($this->paginate('User'));die;
    }

查看文件

 <script src="<?php echo ASSETS_URL; ?>js/admin.js"></script>
    <script>
        jQuery(document).ready(function() {
            Metronic.init(); // init metronic core componets
            Layout.init(); // init layout
            TableAjax.init();               
        });
    </script>        
    <?php echo $this->fetch('script'); ?>

admin_index文件

    <script>
        var total_users =<?php echo $total_users; ?>;
        var total_data =<?php echo $total_users; ?>;
        var aTargets = [0, 7];
        var tOrder = [1, "asc"];
        var ajaxUrl = path + prefix + "/users/list";
    </script>
    <div class="page-content-wrapper">
        <div class="page-content">
            <!-- BEGIN PAGE HEADER-->
            <h3 class="page-title">
                <?php echo $title_for_layout; ?>
            </h3>
            <?php echo $this->Common->sessionFlash(); ?>
            <div class="page-bar">
                <ul class="page-breadcrumb">                            
                    <li>
                        <i class="fa fa-users"></i>
                        <a href="javascript:void(0);">Admins</a>
                    </li>
                </ul>
            </div>
            <!-- END PAGE HEADER-->
            <div class="row">
                <div class="col-md-12">
                    <!-- Begin: life time stats -->
                    <div class="portlet">
                        <div class="portlet-title">
                            <div class="caption">
                                <i class="fa fa-users"></i>Admins Listing
                            </div>
                            <div class="actions">
                                <a href="<?php echo Router::url(array('admin' => true, 'controller' => 'users', 'action' => 'add')); ?>" class="btn green yellow-stripe">
                                    <i class="fa fa-plus"></i>
                                    <span class="hidden-480">
                                        New Admin </span>
                                </a>
                            </div>
                        </div>
                        <div class="portlet-body">
                            <div class="table-container">
                                <div class="table-actions-wrapper">
                                    <span>
                                    </span>
                                    <select class="table-group-action-input form-control input-inline input-small input-sm">
                                        <option value="">Select...</option>
                                        <option value="1">Enabled</option>
                                        <option value="0">Disabled</option>
                                    </select>
                                    <button class="btn btn-sm yellow table-group-action-submit"><i class="fa fa-check"></i><span class="hidden-480">Submit</span> </button>
                                </div>
                                <table class="table table-striped table-bordered table-hover" id="datatable_ajax">
                                    <thead>
                                        <tr role="row" class="heading">
                                            <th width="2%">
                                                <input type="checkbox" class="group-checkable">
                                            </th>
                                            <th width="15%">
                                                Name
                                            </th>                                       
                                            <th width="12%">
                                                Email
                                            </th>
                                            <th width="15%">
                                                Shop Name
                                            </th>                                                                             
                                            <th width="10%">
                                                Country
                                            </th>                                                                             
                                            <th width="10%">
                                                Phone
                                            </th>                                                                      
                                            <th width="10%">
                                                Status
                                            </th>
                                            <th width="18%">
                                                Actions
                                            </th>
                                        </tr>
                                        <tr role="row" class="filter">
                                            <td></td>
                                            <td>
                                                <?php echo $this->Form->input('name', array('label' => false, 'div' => false, 'type' => 'text', 'class' => 'form-control form-filter input-sm')); ?>  
                                            </td>
                                            <td>
                                                <?php echo $this->Form->input('email', array('label' => false, 'div' => false, 'type' => 'text', 'class' => 'form-control form-filter input-sm')); ?>   
                                            </td>
                                            <td> <?php echo $this->Form->input('shop_name', array('label' => false, 'div' => false, 'type' => 'text', 'class' => 'form-control form-filter input-sm')); ?>   </td>
                                            <td>
                                                <?php echo $this->Form->input('country_id', array('label' => false, 'div' => false, 'class' => 'form-control form-filter input-sm', 'empty' => 'Select')); ?>   
                                            </td>
                                            <td><?php echo $this->Form->input('phone', array('label' => false, 'div' => false, 'type' => 'text', 'class' => 'form-control form-filter input-sm')); ?> </td>                                      
                                            <td><?php echo $this->Form->input('status', array('options' => array(1 => 'Enabled', 0 => 'Disabled'), 'label' => false, 'div' => false, 'class' => 'form-control form-filter input-sm', 'empty' => 'Select')); ?></td>                                       
                                            <td>
                                                <div class="pull-left margin-bottom-5">
                                                    <button class="btn btn-sm yellow filter-submit margin-bottom"><i class="fa fa-search"></i> <span class="hidden-480">Search</span></button>
                                                </div>
                                                <button class="btn btn-sm red filter-cancel"><i class="fa fa-times"></i> <span class="hidden-480">Reset</span></button>
                                            </td>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <!-- End: life time stats -->
                </div>
            </div>
        </div>
    </div>
    <div aria-hidden="true" role="basic" id="ajax-version-view" class="modal fade" data-keyboard="false" data-backdrop="static">
        <div class="page-loading page-loading-boxed">
            <img class="loading" alt="" src="<?php echo ASSETS_URL; ?>assets/global/img/loading-spinner-grey.gif">
            <span>
                &nbsp;&nbsp;Loading... </span>
        </div>
        <div class="modal-dialog">
            <div class="modal-content">
            </div>
        </div>
    </div>
admin_list
    <?php
    //pr($rooms);die;
    /*
     * Paging
     */
    $iTotalRecords = $this->params['paging']['User']['count'];
    //  $iDisplayLength = intval($_REQUEST['length']);
    //  $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength; 
    //  $iDisplayStart = intval($_REQUEST['start']);
    $sEcho = intval($_REQUEST['draw']);
    $records = array();
    $records["data"] = array();
    //  $end = $iDisplayStart + $iDisplayLength;
    //  $end = $end > $iTotalRecords ? $iTotalRecords : $end; '<a href="'.Router::url(array('admin'=>true,'controller' => 'rooms', 'action' => 'view')).'" class="btn btn-xs blue"><i class="fa fa-search"></i> View</a>'.
    //pr($users);
    foreach ($users as $user) {
        $id = $user['User']['id'];
        $status = $user['User']['status'];
        $label = ($status == 1) ? 'success' : 'danger';
        $label_text = ($status == 1) ? 'Enabled' : 'Disabled';
        $delete = $this->BootForm->postLink('<i class="fa fa-trash-o"></i> <span class="hidden-480">Delete</span>', array('action' => 'delete', $id), array('confirm' => __('Are you sure you want to delete %s?', $user['User']['name']), 'class' => 'btn default btn-xs red', 'escape' => false));
        $records["data"][] = array(
            '<input type="checkbox" name="id[]" value="' . $id . '">',
            $user['User']['name'],
            $user['User']['email'],
            $user['User']['shop_name'],        
            $user['Country']['country_name'],
            $user['User']['phone'],
            '<span class="label label-sm label-' . ($label) . '">' . $label_text . '</span>',
            '<a class="btn default btn-xs purple" href="' . Router::url(array('admin' => true, 'controller' => 'users', 'action' => 'edit', $id)) . '"><i class="fa fa-edit"></i> <span class="hidden-480">Edit</span> </a>' . $delete,
        );
    }
    if (isset($_REQUEST["customActionType"]) && $_REQUEST["customActionType"] == "group_action") {
        $records["customActionStatus"] = "OK"; // pass custom message(useful for getting status of group actions)
        $records["customActionMessage"] = "Group action successfully has been completed. Well done!"; // pass custom message(useful for getting status of group actions)
    }
    $records["draw"] = $sEcho;
    $records["recordsTotal"] = $iTotalRecords;
    $records["recordsFiltered"] = $iTotalRecords;
    echo json_encode($records);
    ?>
jQuery.validator.addMethod("pattern", function (value, element, param) {
    if (this.optional(element)) {
        return true;
    }
    if (typeof param === 'string') {
        param = new RegExp('^(?:' + param + ')$');
    }
    return param.test(value);
}, "Invalid format.");
/*
 * Account Setting Class
 */
var AccountSetting = function () {
    var resetFormValidate = function () {
        $('.user_reset_password').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            rules: {
                'data[User][password]': {
                    required: true,
                    minlength: 6
                },
                'data[User][confirm_password]': {
                    required: true,
                    equalTo: "#UserPassword"
                }
            }, messages: {
                'data[User][password]': {
                    required: 'Please enter new password.',
                    minlength: 'New password must be at least 6 characters long'
                },
                'data[User][confirm_password]': {
                    required: 'Please enter confirm password.',
                    equalTo: "New password and confirm password not match."
                }
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
            errorPlacement: function (error, element) {
                error.insertAfter(element.closest('.input-icon'));
            }
        });
    }
    var changeFormValidate = function () {
        $('.user_change_password_form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input 
            rules: {
                'data[User][password]': {
                    required: true,
                    minlength: 6
                },
                'data[User][confirm_password]': {
                    required: true,
                    equalTo: "#UserPassword"
                },
                'data[User][old_password]': {
                    required: true,
                    remote: {url: SITE_URL + 'ajax/check_password', type: 'POST', data: {field: 'old_password'}}
                }
            }, messages: {
                'data[User][password]': {
                    required: 'Please enter new password.',
                    minlength: 'Password must be at least 6 characters long.'
                },
                'data[User][confirm_password]': {
                    required: 'Please enter confirm password.',
                    equalTo: "Password and confirm password not match."
                },
                'data[User][old_password]': {
                    required: 'Please enter current password.',
                    remote: 'Current password is wrong.'
                }
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
        });
    }
    var editFormValidate = function () {
        $('.user_edit_profile_form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input 
            rules: {
                'data[User][first_name]': {
                    required: true
                },
                'data[User][last_name]': {
                    required: true
                },
            }, messages: {
                'data[User][first_name]': {
                    required: 'Please enter first name.'
                },
                'data[User][last_name]': {
                    required: 'Please enter last name.'
                }
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
        });
    }
    return {
        init: function () {
            editFormValidate();
            resetFormValidate();
            changeFormValidate();
        }
    };
}();
/*
 * User Class
 */
var Users = function () {
    var userFormValidate = function () {
        $('.user-form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input 
            rules: {
                'data[User][first_name]': {
                    required: true
                },
                'data[User][last_name]': {
                    required: true
                },
                'data[User][email]': {
                    required: true,
                    remote: {url: SITE_URL + 'ajax/check_field', type: 'POST', data: {field: 'email'}}
                },
                'data[User][shop_name]': {
                    required: true,
                    remote: {url: SITE_URL + 'ajax/check_field', type: 'POST', data: {field: 'shop_name'}}
                },
                'data[User][shop_description]': {
                    required: true
                },
                'data[User][specialty]': {
                    required: true
                },
                'data[User][country_id]': {
                    required: true
                },
                'data[User][phone]': {
                    required: true,
                    pattern: /^['d's]+$/,
                    maxlength: 15,
                },
                'data[User][address]': {
                    required: true
                },
                'data[User][image]': {
                    extension: "jpg|jpeg|png"
                },
            }, messages: {
                'data[User][first_name]': {
                    required: 'Please enter first name.'
                },
                'data[User][last_name]': {
                    required: 'Please enter last name.'
                },
                'data[User][email]': {
                    required: 'Please enter email address.',
                    remote: 'Email address already exist.'
                },
                'data[User][shop_name]': {
                    required: 'Please enter shop name.',
                    remote: 'Shop name already exist.'
                },
                'data[User][shop_description]': {
                    required: 'Please enter shop description.'
                },
                'data[User][specialty]': {
                    required: 'Please enter specialty.'
                },
                'data[User][country_id]': {
                    required: 'Please select country.'
                },
                'data[User][phone]': {
                    required: 'Please enter phone.',
                    pattern: 'Please enter valid phone.',
                    maxlength: 'Phone is no more than 15 digits.'
                },
                'data[User][address]': {
                    required: 'Please enter address.'
                },
                'data[User][image]': {
                    extension: 'Please select jpg, jpeg, png image.'
                },
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            errorPlacement: function (error, element) {
                if (element.is('input[type="file"]')) {
                    error.insertAfter(element.parents('.body-img'));
                } else {
                    error.insertAfter(element);
                }
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
        });
    }
    return {
        init: function () {
            userFormValidate();
        }
    };
}();
/*
 * Schedule  Class
 */
var Schedule = function () {
    var oTable;
    var table;
    var nEditing = null;
    var nNew = false;
    var setTimePicker = function () {
        $('.timepicker-no-seconds').timepicker({
            autoclose: true,
            minuteStep: 1
        });
    }
    var scheduleFormValidate = function () {
        $('.schedule-form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input 
            rules: {
                'data[Schedule][start_time]': {
                    required: true
                },
                'data[Schedule][end_time]': {
                    required: true
                },
                'data[Schedule][days][]': {
                    required: true,
                    minlength: 1
                }
            }, messages: {
                'data[Schedule][start_time]': {
                    required: 'Please enter start time.'
                },
                'data[Schedule][end_time]': {
                    required: 'Please enter end time.'
                },
                'data[Schedule][days][]': {
                    required: 'Please select days.'
                }
            },
            errorPlacement: function (error, element) {
                if (element.parents('.days-body').is('div')) {
                    error.attr('id', 'days-error')
                    error.insertAfter(element.parents('.days-body'));
                } else {
                    error.insertAfter(element);
                }
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
        });
    }
    var setSlotActive = function () {
        if ($('.slot-time-body input:checked').is('input')) {
            $('.slot-time-body input:checked').parent('label').addClass('active');
        } else {
            $('.slot-time-body input:first').click();
        }
    }
    var setStatus = function () {
        $('body').on('switchChange.bootstrapSwitch', '#working', function (event, state) {
            var userId = $(this).data('user');
            var scheduleId = $(this).data('schedule');
            var weekId = $(this).data('week');
            var data = {'user_id': userId, 'schedule_id': scheduleId, 'week_id': weekId, 'status': state};
            $.ajax({
                url: SITE_URL + 'ajax/set_working',
                type: 'POST',
                data: data,
                beforeSend: function () {
                    Metronic.blockUI({
                        message: 'Please wait..',
                        target: $('.table-container'),
                        overlayColor: 'grey',
                        cenrerY: true,
                        boxed: true
                    });
                },
                success: function (data) {
                    Metronic.unblockUI($('.table-container'));
                }
            })
        })
    }
    var reSchedule = function () {
        table = $('.table-schedule');
        oTable = table.dataTable({
            bSort: false,
            bFilter: false,
            bInfo: false,
            bPaginate: false,
            bLengthChange: false
        });
        $('body').on('click', '.reschedule-btn', function (e) {
            e.preventDefault();
            /* Get the row as a parent of the link that was clicked on */
            var nRow = $(this).parents('tr')[0];
            if (nEditing !== null && nEditing != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                restoreRow(nEditing);
                editRow(nRow);
                nEditing = nRow;
            } else {
                /* No edit in progress - let's start one */
                editRow(nRow);
                nEditing = nRow;
            }
        })
    }
    var cancelReSchedule = function () {
        $('body').on('click', '.cancel-schedule', function () {
            restoreRow(nEditing);
            nEditing = null;
        })
    }
    var saveSchedule = function () {
        $('body').on('click', '.save-schedule', function () {
            if ($('input[name="data[Schedule][start_time]"]').val() == '' || $('input[name="data[Schedule][end_time]"]').val() == '') {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'Please select valid time.',
                    container: $('#form_wizard_1'),
                    place: 'prepend'
                });
                return false;
            } else {
                $.ajax({
                    url: SITE_URL + 'ajax/change_schedule',
                    type: 'POST',
                    data: $('input,select', nEditing).serializeArray(),
                    beforeSend: function () {
                        Metronic.blockUI({
                            message: 'Please wait..',
                            target: $('.table-container'),
                            overlayColor: 'grey',
                            cenrerY: true,
                            boxed: true
                        });
                    },
                    success: function (data) {
                        var res = JSON.parse(data);
                        if (res.error == 1) {
                            Metronic.unblockUI($('.table-container'));
                            Metronic.alert({
                                type: 'danger',
                                icon: 'warning',
                                message: res.msg,
                                container: $('#form_wizard_1'),
                                place: 'prepend'
                            });
                        } else {
                            window.location.reload();
                        }
                    }
                })
            }
        })
    }
    var editRow = function (nRow) {
        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);
        if ($(nRow).find('input[name="data[working]"]').is('input')) {
            jqTds[1].innerHTML = '<input type="text" name="data[Schedule][start_time]" class="form-control timepicker-no-seconds" value="' + aData[1] + '">';
            jqTds[2].innerHTML = '<input type="text" name="data[Schedule][end_time]" class="form-control timepicker-no-seconds" value="' + aData[2] + '">';
            jqTds[3].innerHTML = '<select  name="data[Schedule][slot_time]" class="form-control"><option  value="30">30 Minute</option><option value="45">45 Minute</option><option value="60">1 Hour</option></select>';
            $('select[name="data[Schedule][slot_time]"] option[value="' + parseInt(aData[3]) + '"]').attr('selected', 'selected')
        } else {
            jqTds[1].innerHTML = '<input type="text" name="data[Schedule][start_time]" class="form-control timepicker-no-seconds" value="">';
            jqTds[2].innerHTML = '<input type="text" name="data[Schedule][end_time]" class="form-control timepicker-no-seconds" value="">';
            jqTds[3].innerHTML = '<select name="data[Schedule][slot_time]" class="form-control"><option value="30">30 Minute</option><option value="45">45 Minute</option><option value="60">1 Hour</option></select>';
            jqTds[4].innerHTML = '<select name="data[Schedule][working]" class="form-control"><option value="1">Yes</option><option value="0">No</option></select>';
        }
        jqTds[5].innerHTML = '<button class="btn  btn-sm blue save-schedule"><i class="fa fa-check"></i> Submit</button><button class="btn  btn-sm red cancel-schedule"> <i class="fa fa-close"></i> Cancel </button>';
        setTimePicker();
    }
    var restoreRow = function (nRow) {
        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);
        for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
            oTable.fnUpdate(aData[i], nRow, i, false);
        }
        oTable.fnDraw();
    }
    var checkBreak = function () {
        $('body').on('change', 'input[name="data[LunchBreak][slot_id][]"]', function () {
            if ($('input[name="data[LunchBreak][slot_id][]"]:checked').length) {
                $('.lunch-submit').removeClass('disabled');
            } else {
                $('.lunch-submit').addClass('disabled');
            }
        })
    }
    return {
        init: function () {
            setTimePicker();
            scheduleFormValidate();
            setSlotActive();
            setStatus();
            reSchedule();
            cancelReSchedule();
            saveSchedule();
            checkBreak();
        }
    };
}();
/*
 * Setting  Class
 */
var Setting = function () {
    var settingFormValidate = function () {
        $('.setting-form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input 
            rules: {
                'data[Setting][0][value]': {
                    required: true
                },
                'data[Setting][1][value]': {
                    required: true,
                    number: true,
                    min: 1,
                    pattern: '^[0-9]+$'
                }
            }, messages: {
                'data[Setting][0][value]': {
                    required: 'Please enter site title.'
                },
                'data[Setting][1][value]': {
                    required: 'Please enter schedule Hour.',
                    pattern: 'Please enter valid schedule Hour.'
                }
            },
            errorPlacement: function (error, element) {
                error.insertAfter(element);
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
        });
    }
    return {
        init: function () {
            settingFormValidate();
        }
    };
}();
/*
 * Barber  Class
 */
var Barber = function () {
    var addVacationFormValidate = function () {
        $('.vacation-form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input 
            rules: {
                'data[Vacation][date][]': {
                    required: true
                }
            }, messages: {
                'data[Vacation][date][]': {
                    required: 'Please enter date.'
                }
            },
            errorPlacement: function (error, element) {
                error.insertAfter(element);
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
        });
    }
    var addMoreDate = function () {
        $('body').on('click', '.add-more-date', function () {
            var parent = $(this).parents('.form-group');
            var clone = parent.clone();
            $('input', clone).val('');
            $('.help-block', clone).remove();
            $(clone).removeClass('has-error');
            $('.btn-body a.add-more-date', parent).remove();
            $('.btn-body', parent).html('<a href="javascript:;" class="btn btn-danger remove-more-date">Remove</a>');
            clone.insertAfter(parent);
            setDatePicker();
        })
    }
    var removeMoreDate = function () {
        $('body').on('click', '.remove-more-date', function () {
            $(this).parents('.form-group').remove();
        });
    }
    var setDatePicker = function () {
        $('.vacation-date').datepicker({
            "startDate": new Date(),
            todayHighlight: true,
            format: 'mm/dd/yyyy',
            autoclose: true,
        });
    }
    return {
        init: function () {
            addVacationFormValidate();
            setDatePicker();
            addMoreDate();
            removeMoreDate();
        }
    };
}();