laravel-admin解决表单select联动时,编辑默认没选上的问题

吾爱主题 阅读:161 2021-08-25 15:34:00 评论:0

今天在开发公司一个功能时,公司开发环境用的是laravel-admin,因为需要用上select联动,所以根据文档说明进行开发,并成功的使用上了,代码我就不重复,大家可以去参考laravel-admin官网的说明。

首先我们找到select的js,路径:跟目录/vendor/encore/laravel-admin/src/Form/Field下的Select.php文件,找到下面代码:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 $script = <<<EOT $(document).on( 'change' , "{$this->getElementClassSelector()}" , function () {   var target = $(this).closest( '.fields-group' ).find( ".$class" );   $.get( "$sourceUrl?q=" + this.value, function (data) {    target.find( "option" ).remove();    $(target).select2({     data: $. map (data, function (d) {      d. id = d.$idField;      d.text = d.$textField;      return d;     })    }).trigger( 'change' );   }); });   EOT;

并修改成以下代码:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 $script = <<<EOT $(document).on( 'change' , "{$this->getElementClassSelector()}" , function () {   var target = $(this).closest( '.fields-group' ).find( ".$class" );   $.get( "$sourceUrl?q=" + this.value, function (data) {    target.find( "option" ).remove();    $(target).select2({     data: $. map (data, function (d) {      d. id = d.$idField;      d.text = d.$textField;      return d;     })    }).trigger( 'change' );   }); });   $( '{$this->getElementClassSelector()}' ).trigger( 'change' );   EOT;

我们在原有代码中加入这句:

?
1 $( '{$this->getElementClassSelector()}' ).trigger( 'change' );

作用就是在初始化的时候触发一次联动。

然后在我们的表单中,我们再来定义编辑初始时候的值,代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 $form - >select( 'hezuo' , "合作模式" ) - >options(function () {   $record = request() - >route() - >parameters();   $record = $record[ "chanpin" ];   $data = ChanpinModel::where( 'id' , $record) - >first();   $hezuoList = array(    "1" = > '测试1' ,    "2" = > '测试2' ,    "3" = > '测试3' ,    );   $hezuo = $data - >hezuo;   return [$hezuo = > $hezuoList[$hezuo]]; });

这段代码是根据当前记录的值,去获取对应所属那个选项,这样便使select联动编辑时,能够默认选上我们的值。

以上这篇laravel-admin解决表单select联动时,编辑默认没选上的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/HZX19941018/article/details/85052629

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容