How to save data and to add new tag and its data from select 2 multiple select tag

♀尐吖头ヾ 提交于 2019-12-25 09:14:19

问题


I followed a tutorial on making a multiple select tag mode in this link http://jsfiddle.net/dplanella/N6bQE/36/.

PROBLEM:

  1. If I choose some value from the multiple select, how can I check if the I already select the data from the multiple select to be not shown once I open the multiple select again just like the link performed above?

  2. How can I update the values to the database once I finish chose value/s from the multiple select just like the link performed above? DONE

  3. Add new tag/s even the tag/s text are not in the source data (i.e: http://jsfiddle.net/dplanella/N6bQE/36/)

CONCEPT/GOAL:

  • To make a trello-like labels assigned at the selected tickets/tasks
  • make it updated at the once performed edit/choice of selection in the multiple select field DONE!
  • Can delete labels and update the db DONE!: Store the data via data ID when update or delete in this form: "1,2"

Javascript

       var items = [];
    $.each(CACHE_ITEMS['cache_components'], function(i, item) {
        items.push({value: item.id, text: item.name});
    });
    var cache_components = items;

    $('.components').editable({
        url: function(params) {
            var d = new $.Deferred();
            var url = $(this).attr('data-custom-url');
            if (url) {
                $.post(API_URL + url, params, function(response) {
                    if (response.success) {
                        d.resolve();
                    } else {
                        return d.fail('error message');
                    }
                }).done(function() {
                    return d.promise();
                });
            } else {
                return d.reject('error message');
            }
        },
        source: function() {
            return cache_components;
        },
        // showbuttons: true,
        emptytext: 'None',
        autotext: 'always',
        select2: {
            width: '150px',
            multiple: true,
            placeholder: 'Component/s',
            // separator: ','
            tokenSeparators: [" ", ","]
        },
        display: function(value) {
            var val1 = [value].toString().split(",");
            var val2 = val1.filter(function(val) {
                if (val) return val }).join(",");
            var val3 = val2.split(",");
            // console.log(val4);
            $.each(val3, function(i) {
                $.each(cache_components, function(i2, varr) {
                    if (varr.id == val3[i]) {
                        val3[i] = "<span class='label label-primary'>" + $('<p>' + varr.text + '</p>').text() + "</span>";
                    }
                });
            });
            $(this).html(val3.join(" "));
        },
        params: function(params) {
            params.modified_by = USER_LOGGED_ID;
            return params;
        }
    });

    $('.components').on('shown', function() {
        var editable = $(this).data('editable');
        var value = editable.value;
        var val1 = [value].toString().split(",");
        var val2 = val1.filter(function(val) {
            if (val) return val }).join(",");
        var val3 = val2.split(",");
        // console.log(val4);
        $.each(val3, function(i) {
            $.each(cache_components, function(i2, varr) {
                if (varr.id == val3[i]) {
                    val3[i] = "<span class='label label-primary'>" + $('<p>' + varr.text + '</p>').text() + "</span>";
                }
            });
        });
    });

    $('[id^="components-edit-"]').click(function(e) {
        e.stopPropagation();
        e.preventDefault();
        $('#' + $(this).data('editable')).editable('toggle');
    });

Ticket.php: Model functions from API to display 'Components' content

public function getTicket($request) {

    $param = $request->getParams();
    $ticket = array();
    $ticket_info = array();

    if ($param) {

        $id = $param['id'];

        $cols = 't.*,s.name as status_name,s.color as status_color,tc.icon as category_icon,tc.name as category_name,tsc.name as subcategory_name,ts.name as severity_name,tsrc.name as source_name,a.dba, pa.id as `parent_account_id`,pa.dba as `parent_account`, c.name as `components_name`';

        $this->db->join('ticket_categories tc', 'tc.id = t.category_id', 'LEFT');
        $this->db->join('ticket_subcategories tsc', 'tsc.id = t.subcategory_id', 'LEFT');
        $this->db->join('ticket_severities ts', 'ts.id = t.ticket_severity_id', 'LEFT');
        $this->db->join('ticket_sources tsrc', 'tsrc.id = t.ticket_source_id', 'LEFT');
        $this->db->join('ticket_status s', 's.id = t.ticket_status_id', 'INNER');
        $this->db->join('ticket_components tcomp', 'tcomp.components_id = t.components_id', 'LEFT');
        $this->db->join('components c', 'c.id = tcomp.components_id', 'LEFT');

        // Include parent_id of account
        $this->db->join('accounts a', 't.account_id = a.id', 'INNER');
        $this->db->join('(SELECT mgx.`id`,mgx.`dba`,mgx.`left`, mgx.`right` FROM`accounts` mgx ORDER BY mgx.`left` DESC) pa '
            , 'pa.`left` < a.`left`AND pa.`right` > a.`right` ', 'LEFT');

        $this->db->where('t.id', $id);
        $this->db->where('t.is_deleted', 0);
        $ticket = $this->db->getOne('tickets t', $cols);

        //getting components name from db table 'components'
        if ($ticket['components_id']) {
            $component = $this->getTicketComponents($ticket['id']);
            foreach ($component as $value) {
                $components_id[] = $value['id'];
                $components_name[] = $value['name'];
                $components_project_id[] = $value['project_id'];
                $components_components_id[] = $value['components_id'];
            }
        } else {
            $ticket_info['Components'] = 'None';
        }

        $components_ids = implode(',', $components_id);
        $components_names = implode(',', $components_name);
        $components_project_ids = implode(',', $components_project_id);
        $components_components_ids = implode(',', $components_components_id);

        $ticket_info['Components'] = '<span class="components" id="components-editable-' . $ticket['id'] . '"
        data-toggle="manual" data-type="select2" data-custom-url="ticket/update" data-pk="' . $ticket['id'] . '"
        data-value="' . $components_components_ids . '" data-original-title="Enter components"></span><a href="javscript:void(0);" id="components-edit-' . $ticket['id'] . '" data-editable="components-editable-' . $ticket['id'] . '" class="">  <i class="fa fa-plus"></i></a>';

        $ticket['ticket_info'] = $ticket_info; // where the label 'Components' and its contents are store to display at the view
  }
  echo json_encode($ticket);
}

public function getTicketComponents($request) {
    if (is_object($request)) {
        $param = $request->getParams();
        $ticket_id = $param['ticket-id'];
    } else {
        $ticket_id = $request;
    }

    if ($ticket_id) {
        $cols = array('c.*');

        $this->db->join('components c', 'c.id = tc.components_id', 'LEFT');
        $this->db->where('tc.ticket_id', $ticket_id);

        if (is_object($request)) {
            echo json_encode($this->db->get('ticket_components tc'));
        } else {
            return $this->db->get('ticket_components tc');
        }
    }
}

public function getComponents() {
    $component = $this->db->get('components');
    return json_encode($component);
}

View to display the label 'Components' and its content from the API Model

<table class="horizontal-list">
            <?php 
              if($ticket->ticket_info){
                foreach ($ticket->ticket_info as $label => $value) {
                  echo '<tr><td>'.$label.':</td><td>'.$value.'</td></tr>';
                }
              }
            ?>
          </table>

Route to retrieve data from API

$app->group('/ticket', function () use ($app) {
    $app->get('/test2', 'Ticket:getComponents');
});

Cached components data code (used at the javascript to get data from the API)

var CACHE_ITEMS = {};
CACHE_ITEMS['cache_components'] = <?php echo (Application::getCacheItem('cache_components', 'ticket/test2')) ?>;

Data returned in json format in getTicketComponents() function(code above)

// http://localhost/crm-api/public/v1/ticket/components?ticket-id=22081

[
   {
       "id": 1,
        "ticket_id": 22081,
        "components_id": 1,
        "status": null,
        "date_created": "2016-05-12",
        "date_modified": "2016-05-12",
        "created_by": 53,
        "modified_by": 53,
        "name": "back-office",
        "project_id": 2
    }
]

Data returned in json format in getComponents() function(code above)

// http://localhost/crm-api/public/v1/ticket/test2

[
    {
        "id": 1,
        "name": "back-office",
        "project_id": 2,
        "status": null,
        "date_created": "2016-05-12",
        "date_modified": "2016-05-12",
        "created_by": 53,
        "modified_by": 53
    },
    {
        "id": 2,
        "name": "front-office",
        "project_id": 2,
        "status": null,
        "date_created": "2016-05-12",
        "date_modified": "2016-05-12",
        "created_by": 53,
        "modified_by": 53
    }
]

I've implemented those codes with CodeIgniter 3.0 HMVC, jQuery, and a Slim Framework API for getting data. Apologies for the arrangements of codes and the grammar.

**[UPDATE]: ** I tried to implement this in jsfiddle and I apply my codes and the link I based above. And the result at this jsfiddle is the output what I am trying to achieve. More of my concern/problem are stated below and i update the javascript code:

Any help will heavenly appreciated. Thanks!

来源:https://stackoverflow.com/questions/38978140/how-to-save-data-and-to-add-new-tag-and-its-data-from-select-2-multiple-select-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!