简体   繁体   中英

jquery jtable multi-select dropdown

I've been working on creating a multi-select drop-down with jquery jtable . So far this issue has been helpful. The drop-down lets the user select multiple options and sends the form data to the server. The problem is: only the last selected option from the drop-down gets saved even though all of them are being sent. The last comment on that issue mentions this problem but the suggested fix doesn't work for me and I get a server error.

//js
LessonsLearnedFields = {
//Other fields left out for brevity
risk_id: {
    key: true,
    list: false
},
cause: {
    title: "Cause",
    type: "multiselectddl",
    width: '70%',
    options: {
         empty: 'empty',
         yes: 'Yes',
         no: 'No'
     }
}
};

function loadViewLessonsLearnedTable(ContainerID, project_id, modify) {
var fields = $.extend(true, fields, LessonsLearnedFields); //copy, don't reference
fields.Responses = getLessonsLearnedResponseChildTable(ContainerID);
$('#' + ContainerID).jtable({
    title: 'Lessons Learned',
    paging: true,
    pageSize: 100,
    sorting: true,
    defaultSorting: 'WBS ASC',
    actions: {
        listAction: config.base_url + 'data_fetch/risks_cause_by_project/' + project_id,
        deleteAction: config.base_url + 'data_fetch/delete_risk/',
        updateAction: config.base_url + 'data_fetch/update_lessons_learned_risk/' + project_id 
    },
    messages: defaultRiskMessages,
    fields: LessonsLearnedFields
    // ,
    // formSubmitting: function(event,data){
    //     $('select[name=cause]', data.form).attr('name','cause[]');
    //         return data;
    //     }
});
$('#' + ContainerID).jtable('load');
}

//Data_Fetch - php
public function update_lessons_learned_risk($project_id, $offset = 0, $limit = 100, $order_by = 'risk_id', $direction = 'ASC') {
    $confirm_member = $this->User_model->confirm_member(true, false);
    if (!$confirm_member['success']) {
        $this->print_jtable_error(self::ERROR_NOT_LOGGED_IN);
        return;
    }
    $risk_id = $this->input->post('risk_id');
    $user_id = $_SESSION['user_id'];
    $this->load->model('Risk_model');
    $permission = $this->Risk_model->initialize($risk_id, $user_id);
    if ($permission != "Admin" && $permission != "Owner" && $permission != "Write") {
        $this->print_jtable_error(self::ERROR_NO_EDIT_PERMISSION);
        return;
    }
    $data['event'] = $this->input->post('event');
    $data['date_closed'] = $this->input->post('date_closed');
    $data['probability'] = $this->input->post('probability');
    $data['cause'] = $this->input->post('cause');
    $data['occurred'] = $this->input->post('occurred');
    $this->load->helper('security');
    foreach ($data as &$val) {
        xss_clean($val);
    }
    if ($this->Risk_model->update_lessons_learned($data) == false) {
        $this->print_jtable_error(self::ERROR_UNKNOWN);
        return;
    } else {
        print json_encode(array('Result' => "OK"));
        return true;
    }
}

//Risk Model - php
public function update_lessons_learned(array $data) {
    if (!$this->initialized)
        return false;
    if (!$this->Project_model->modify($this->user_id, $this->project_id))
        return false;
    //remove excess data from array
    $keys = array('event', 'date_closed',
        'probability', 'cause', 'occurred');
    foreach ($data as $key => $val)
        if (!in_array($key, $keys))
            unset($data[$key]);
    $data['date_of_update'] = date('Y-m-d');
    if (isset($data['date_closed']) && $data['date_closed'] == "0000-00-00")
        unset($data['date_closed']);
    //probablity is set to 100 if risk occurred  
    if (isset($data['occurred']) && $data['occurred'] === 'yes')
        $data['probability'] = 100;
    //probablity is set to 100 if risk occurred
    if (isset($data['occurred']) && $data['occurred'] === 'no')
        $data['probability'] = 0;

    if (!$this->db->where('risk_id', $this->risk_id)->update('risks', $data))
        return false;
    $this->update_priority_effect();
    $this->update_priority_monetary();
    return true;
}

Images in comment.

All help is greatly appreciated.

I was missing [] in this line $data['cause'] = $this->input->post('cause'); After the addition of the missing braces like so: $data['cause'] = $this->input->post('cause[]'); I converted the value to string and then stored it.

 $cause_str = implode(",", $this->input->post('cause')); 
        $data['cause'] = $cause_str;

The formSubmitting hook told PHP back-end to expect an array and that is why it was necessary.

UPDATE -->

I wanted to improve the UX while using the multi select drop-down so I implemented a multi select drop-down with checkboxes next to items. I found a great example which helped me a great deal . Here's the updated updated method for creation of input according to item type for jquery jtable

_createDropDownListMultiForField: function (field, fieldName, value, record) {
            //Create a container div
                // var $containerDiv = $('<div class="jtable-input jtable-multi-dropdown-input"></div>');
            var $containerDiv = $('<div class="jtable-input jtable-multi-dropdown-input" width="20px;"></div>');

            var $script = $('<script src="/assets/js/prep.js"></script>').appendTo($containerDiv);
            var $style = $('<link rel="stylesheet" type="text/css" href="assets/css/prep.css">').appendTo($containerDiv);

            //Create multi-select element
                // var $select = 
                // $('<select multiple="multiple" class="' + field.inputClass + '" id="Edit-' + fieldName + '" name=' + fieldName + '></select>').appendTo($containerDiv);
            var $dl = $('<dl class="dropdown ' + field.inputClass + '" id="Edit-' + fieldName + '" name=' + fieldName + '></dl>').appendTo($containerDiv);

            var $dt = $('<dt></dt>').appendTo($dl);
            var $a = $('<a href="#"></a>').appendTo($dt);
            var $span = $('<span class="hida">Cause Selector</span>').appendTo($a);
            var $p = $('<p class="multiSel"></p>').appendTo($a);

            var $dd = $('<dd></dd>').appendTo($dl);
            var $multiSelectDiv = $('<div class="mutliSelect"></div>').appendTo($dd);
            var $ul = $('<ul class="dropdown ' + field.inputClass + '" id="Edit-' + fieldName + '" name=' + fieldName + '></ul>').appendTo($multiSelectDiv);

            //Multi
            var options = this._getOptionsForField(fieldName,{
                    record: record,
                    value: value,
                    source: 'list',
                    dependedValues: this._createDependedValuesUsingRecord(record, field.dependsOn)
            });
            //Multi
            if (value) {
                console.log("Value: " + value);
                if (typeof value === 'string') {
                    var values = value.split(',');
                } else { //(Object.prototype.toString.call(value) === '[object Array]') {
                    values = value;
                }

                //add options
                $.each(options, function(index, element) {
                    // $select.append('<option value="' + element.Value + '"' + (element.Value == element.Out ? ' selected="selected"' : '') + '>' + element.DisplayText + '</option>');
                        // $select.append('<option value="' + element.Value + '"' + '>' + element.DisplayText + '</option>');
                    $ul.append('<li><input class="' + field.inputClass + '" id="Edit-' + fieldName + '" name="' + fieldName + '[]" type="checkbox" value="' + element.Value + '"' + '>' + element.DisplayText + '</li>');
                });
                // $.each(values, function(index, element) {
                //     $select.children('option[value="' + element + '"]').attr("selected", "selected");
                // });
            } else {
                $.each(options, function (index, element) {
                        // $select.append('<option id="what?" value="' + element.Value + '">' + element.DisplayText + '</option>');
                    $ul.append('<li><input id="what?" class="' + field.inputClass + '" id="Edit-' + fieldName + '" name=' + fieldName + '[] type="checkbox" value="' + element.Value + '"' + '>' + element.DisplayText + '</li>');    

                });
            }

            return $containerDiv;
        }

perp.js and prep.css are modified versions of the files from that codepen exmaple.

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