【问题标题】:How to fill other field in view laravel blade using select2 and laravelcollective如何使用 select2 和 laravelcollective 填充视图 laravel 刀片中的其他字段
【发布时间】:2019-04-02 01:12:21
【问题描述】:

我想使用 Laravel Collective Select 和 Select2 从控制器中使用以下代码检索数据:

public function create() {
   $customers=Customer::all();
   $customerAlt= Customer::get()->pluck('customer_name', 'id')->prepend('Please Select', '');
   return view('req.create', compact 'customer', 'customerAlt')
}

现在在我的刀片视图中,如果使用普通形式,我想使用类似这样的 Laravel 集合

<select id="NamaPelanggan" name="nama_pelanggan" class="form-control"> 
 <option>Pilih Satu</option>
    @foreach($customers as $cus)
     <option data-contact="{{ $cus->contact_person }}" data-phone="{{ $cus->phone_number }}" value="{{$cus->id}}">{{$cus->name}}</option>
    @endforeach
</select>

并且下面的JS来填充其他文本字段PICPIC_Phone

     $('#NamaPelanggan').change(function() {
          let contact = $(this).find(':selected').data('contact_person');
          let phone = $(this).find(':selected').data('phone_number');
          $('#PIC').val(contact);
          $('#PIC_Phone').val(phone);
      })

问题是我如何使用 laravelcollective 和 select2 来替换上面的正常选择以及我应该使用哪个 $customer

【问题讨论】:

    标签: javascript php laravel jquery-select2 laravelcollective


    【解决方案1】:

    用等价的 laravelcollective 替换您的 select 元素,并将 select2 css 类作为属性传递,如下所示:

    {!! Form::select('customer', $customers, null, ['class' => 'select2']) !!}
    

    客户必须是二维数组,key => value,其中key为html选项值,value为html选项标签。

    $customers = [
        1 => 'Customer A',
        2 => 'Customer B',
    ]
    

    ---已编辑---

    要为选项字段添加额外的属性,例如 data-contact 和 data-phone,您可以将其作为数组作为第五个参数传递。

    注意这一点:第五个参数是一个带有options元素属性的数组;第四个参数是带有属性的数组来选择元素。

    LaravelCollective 选择元素允许您将这第五个参数作为由您的选择值索引的数组传递,并且在每个索引中您必须有另一个带有额外属性的数组。所以你需要02个数组来实现你所需要的。

    1. 第一个数组$customers 作为值和标签传递;
    2. 要传递的第二个数组$extraParameters,其中每个索引都是前一个数组的值。

    假设这是你的第一个数组:

    $customers = [
        1 => 'Customer A',
        2 => 'Customer B',
    ]
    

    这应该是你的第二个

    $extraParameters = [
        1 => ['data-contact' => 'Customer A Contact', 'data-phone' => 'Customer A Phone'],
        2 => ['data-contact' => 'Customer B Contact', 'data-phone' => 'Customer B Phone']
    ]
    
    {!! Form::select('customer', $customers, null, ['class' => 'select2'], $extraParameters) !!}
    

    【讨论】:

    • 但是我如何在 laravelcollective 中传递这些数据 data-contact="{{ $cus->contact_person }}" ?
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2021-01-25
    • 2012-02-12
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多