讨论 使用交流 解决:怎么实现 表单 select多选

解决:怎么实现 表单 select多选

zqiqi 发表于    阅读:77    回复:1

问题描述:

https://modstart.com/thread/1332/1#post-1464

解决步骤:

1、后台原程序不支持select多选,曾尝试使用select2,但是不能成功。切换思路,既然不支持select多选,那么就只在页面上实现多选的样式

修改cms_content表,增加字段

增加 表

CREATE TABLE `cms_cat_content` (
  `id` bigint(20) NOT NULL,
  `contentId` bigint(20) NOT NULL,
  `catId` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


2、在后台文件 /module/Cms/Admin/Controller/ContentController.php 方法 edit() 

$form->select('catId', '栏目')->options($catOptions);

改为:

$form->hidden('catId', '主栏目');
$form->hidden('catIds');
$form->select('catIds', '栏目')->options($catOptions)->multiple(true);

;并在下面 

$recordValue = ArrayUtil::keepKeys($data, [...]

增加字段名 catIds;

在修改或者新增之前

$newCatIds = explode(',', $recordValue['catIds']);

;如果是修改表,下面增加

// 处理多栏目数据
                    // $oldCatIds = explode(',', $record['catIds']);
                    $oldCatIds = ModelUtil::all('cms_cat_content', ['contentId' => $record['id']], ['catId']);
                    $oldCatIds = array_column($oldCatIds, 'catId');
                    
                    // 比较 原catIds 比 现catIds 少哪些元素,则在表cms_cat_content中增加其
                    $addArr = array_diff($newCatIds, $oldCatIds);
                    if(!empty($addArr)) {
                        $addData = [];
                        foreach($addArr as $v) {
                            !empty($v) && $addData[] = [
                                'catId' => $v,
                                'contentId' => $record['id']
                            ];
                        }
                        !empty($addData) && ModelUtil::insertAll('cms_cat_content', $addData, false);
                    }
                    
                    // 比较 现catIds 比 原catIds 少哪些元素,则在表cms_cat_content中删除其
                    $delArr = array_diff($oldCatIds, $newCatIds);
                    if(!empty($delArr)) {
                        foreach($delArr as $v) {
                            !empty($v) && ModelUtil::delete('cms_cat_content', ['contentId' => $record['id'], 'catId' => $v]);
                        }
                    }

;如果是新增数据

// 处理多栏目数据
                    if(!empty($newCatIds)) {
                        $addData = [];
                        foreach($newCatIds as $v) {
                            !empty($v) && $addData[] = [
                                'catId' => $v,
                                'contentId' => $recordValue['id']
                            ];
                        }
                        !empty($addData) && ModelUtil::insertAll('cms_cat_content', $addData, false);
                    }

;修改批量移动方法batchMove()

return $page->body($form)
            ->pageTitle('批量移动')
            ->handleForm($form, function (Form $form) use ($ids) {
                AdminPermission::demoCheck();
                $data = $form->dataForming();
                ModelUtil::model($this->modelTable)->whereIn('id', $ids)->where('modelId', $this->modelId)->update([
                    'catId' => $data['catId'],
                ]);
                return Response::redirect(CRUDUtil::jsDialogCloseAndParentGridRefresh());
            });

改为

return $page->body($form)
            ->pageTitle('批量移动')
            ->handleForm($form, function (Form $form) use ($ids) {
                AdminPermission::demoCheck();
                $data = $form->dataForming();
                ModelUtil::model($this->modelTable)->whereIn('id', $ids)->where('modelId', $this->modelId)->update([
                    'catId' => $data['catId'], 'catIds' => $data['catId']
                ]);
                // 删除 cms_cat_content $ids,再重新插入关联数据
                $insertData = [];
                foreach($ids as $id) {
                    ModelUtil::delete('cms_cat_content', ['contentId' => $id]);
                    $insertData[] = [
                        'contentId' => $id,
                        'catId' => $data['catId']
                    ];
                }
                ModelUtil::insertAll('cms_cat_content', $insertData, false);
                return Response::redirect(CRUDUtil::jsDialogCloseAndParentGridRefresh());
            });

;在删除方法delete()增加语句:

ModelUtil::delete('cms_cat_content', ['contentId' => $record['id']]);

3、更改模板文件 vendor/modstart/modstart/views/core/field/select.blade.php

        <div class="layui-form tw-inline-block" lay-filter="{{$name}}">
            <select class="form" name="{{$name}}"
                    @if($selectSearch) lay-search @elseif($selectRemote) @else lay-ignore @endif
                    @if($selectRemote) lay-remote="{{$selectRemote}}" lay-init-value="{{null===$value?$defaultValue:$value}}" @endif
                    @if($readonly) disabled @endif
                    @if(!empty($onValueChangeJsFunction))
                        onchange="window.{{$id}}_change(this);"
                    @endif
            >
                @foreach($options as $k=>$v)
                    <option value="{{$k}}" @if((null===$value&&$k==$defaultValue)||(null!==$value&&$k==$value)) selected @endif>{{$v}}</option>
                @endforeach
            </select>
        </div>

改为:

            @if($multiple === false)
            <select class="form" name="{{$name}}"
                    @if($selectSearch) lay-search @elseif($selectRemote) @else lay-ignore @endif
                    @if($selectRemote) lay-remote="{{$selectRemote}}" lay-init-value="{{$value}}" @endif
                    @if($readonly) disabled @endif
                    @if(!empty($onValueChangeJsFunction))
                        onchange="window.{{$id}}_change(this);"
                    @endif
            >
                @foreach($options as $k=>$v)
                    <option value="{{$k}}" @if($k==$value) selected @endif>{{$v}}</option>
                @endforeach
            </select>
            @else
            <div class="catList"></div>
            <ul class="selectUl">
                @foreach($options as $k=>$v)
                    <li value="{{$k}}" @if($k==$value) selected @endif>{{$v}}</li>
                @endforeach
            </ul>
             <style>
                .catList {
                    width: 100%;
                    min-height: 1.6rem;
                    padding: 0.15rem 0.15rem;
                    padding-top: 0;
                    font-size: .65rem;
                    border: 0.05rem solid #ddd;
                    color: #444;
                }
                .catList span {
                    margin: 5px 5px 5px 0;
                    padding: 5px 5px 5px 0;
                    background:#ccc;
                    white-space: nowrap;
                }
                .catList span icon {
                    display: inline-block;
                    padding-left: 5px;
                    margin-right: 5px;
                    line-height: 1.2;
                    font-size: 10px;
                    color: yellow;
                    cursor: pointer;
                }
                .selected {
                    background: #1e90ff;
                }
                ul.selectUl {
                    border: 1px solid #ccc;
                    padding: 0 5px;
                    display: none;
                }
                ul.selectUl li{
                    white-space: nowrap;
                    display:block;
                }
             </style>
           
            <script>
                // 重置catList 内容标签
                function resetTag() {
                    var catIds= [];
                    $('.catList').empty();
                    $('ul.selectUl').find('li[class="selected"]').each(function() {
                        var currentValue = $(this).val(); // 获取当前选项的值
                        var currentText = $(this).text(); // 获取当前选项的文本
                        // 给catList 下追加tag span
                        appendCatlistSpan(currentValue, currentText);
                        catIds.push(currentValue);
                    });
                    // 如果catids 为空时,按初始值
                    if(catIds.length === 0) {
                        initValue();
                    } else {
                        $('input[name="catId"]').val([catIds[0]]);
                        // 把cat id 存到 input[name="catIds"]中 79,88,129
                        $('input[name="catIds"]').val(catIds.toString());
                    }
                    
                }

                // catList 下的span 点击事件
                function fClick(e, obj) {
                    var node = obj.parent();
                    var currentValue = node.attr('data-value');
                    $('.selectUl li[value="'+ currentValue +'"]').removeClass('selected');
                    // // 重置catList 内容标签
                    resetTag();

                    e.stopPropagation(); // 阻止点击击穿
                    e.preventDefault(); // 阻止点击击穿
                }

                // 给catList 下追加tag span
                function appendCatlistSpan(currentValue, currentText) {
                    currentText = $.trim(currentText.replace(/[^a-zA-Z]/g, ''));
                    $('.catList').append('<span data-value="'+ currentValue +'" class="tagify__tag-text"> <icon> X </icon>'+ currentText +'</span>');
                    var span = $('.catList').children('span'); // 获取新插入的span元素
                    // 为span的子元素icon添加点击事件
                    span.children('icon').each(function(e) {
                        $(this).on('click', function(e) {
                            fClick(e, $(this));
                        });
                    });
                }

                function initValue() {
                    // 查看catIds的input 值,如果值不为空,则把值赋到catList span 和 为selectUl 设置 selected
                    var catIds = $('input[name="catIds"]').val();
                    if(catIds !== '') {
                        var catIdsArr = catIds.split(",");
                        catIdsArr.forEach(function(currentValue) {
                            $('.selectUl li[value="'+ currentValue +'"]').addClass('selected');
                            var currentText =$('.selectUl li[value="'+ currentValue +'"]').text();
                            // 给catList 下追加tag span
                            appendCatlistSpan(currentValue, currentText);
                        });
                    } else {
                        // 如果是catId不为空,则按catId
                        // 否则按 selectUl 的第一个li
                        var catId = $('input[name="catId"]').val();
                        if(catId === '') {
                            var defaultCat = $('.selectUl').find('li').first();
                            defaultCat.addClass('selected');
                            currentValue = defaultCat.attr('value');
                            currentText = defaultCat.text();
                            var currentText =$('.selectUl li[value="'+ currentValue +'"]').text();
                            // 给catList 下追加tag span
                            appendCatlistSpan(currentValue, currentText);
                            // 为catId赋值
                            $('input[name="catId"]').val(currentValue);
                        } else {
                            $('.selectUl li[value="'+ catId +'"]').addClass('selected');
                            var currentText =$('.selectUl li[value="'+ catId +'"]').text();
                            // 给catList 下追加tag span
                            appendCatlistSpan(catId, currentText);
                        }
                        $('input[name="catIds"]').val($('input[name="catId"]').val());
                    }
                }

                $(document).ready(function () {

                    $('div[lay-filter="catIds"]').width('100%');

                    // 初始值
                    initValue();
                    

                    // selectUl 点击后 selectUl li 则全部显示
                    
                    $('.catList').click(function() {
                        var displayValue = $('ul.selectUl').css("display");
                        if (displayValue === "none") {
                            $('ul.selectUl').css({'display': 'block'});
                        } else {
                            $('ul.selectUl').css({'display': 'none'});
                        }
                        
                    });
                    $('ul.selectUl').find("li").each(function() {
                        
                        // 点击option,去掉option的背景色, 为input去掉对应span
                        $(this).on("click", function() {
                            if($(this).hasClass('selected')) {
                                $(this).removeClass('selected');
                            } else {
                                $(this).addClass('selected');
                            }
                            // 重置catList 内容标签
                            resetTag();
                        });
                        
                    });
                    // 点击标签 删除标签\去掉option的背景色
                    $('.catList span icon').click(function(e) {
                        fClick(e, $(this));
                    });

                   
                });
            </script>
            @endif


建议与意见:

以上是后台处理内容类多选问题的过程。前台处理多选相关暂时就不一一列出了,如想了解或者有其它相关详细处理问题,请留言。

评论

感谢提供多选方案,后续我们会增加进去。

 
1
我来评论
QQ
微信