我想保存一个公司的电话。我在表格中使用多个选择来列出电话。
我试图从多个select但是dd$请求中获取输入值-
这是我表单的一部分(add_company.blade.php):
{!! Form::model($company = new App\Models\Setting\Organization\Company, ['method' => 'POST', 'action' => 'Setting\Organization\CompaniesController@store', 'files'=>true]) !!}
<div class="form-group">
<!-- Form::label parameters : LabelFor, Text -->
{!! Form::label('NewPhone', 'Telephones : ', ['class' => 'col-lg-3 col-md-3 col-sm-3 col-xs-3']) !!}
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
{!! Form::text('NewPhone', null, ['class' => 'form-control', 'id' => 'txtNewPhone']) !!}
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
{!! Form::button('', ['class' => 'form-control btn btn-info fa fa-plus', 'id' => 'btnAddPhone']) !!}
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
{!! Form::select('Phones[]', $phones, null, ['class' => 'form-control', 'multiple' => true, 'id' => 'ddPhone']) !!}
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
{!! Form::button('', ['class' => 'form-control btn btn-danger fa fa-minus', 'id' => 'btnDelPhone']) !!}
</div>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
{!! Form::submit('Add Company', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
这是我要添加的JQuery
$('#btnAddPhone').on('click', function(){
var newPhone = $('#txtNewPhone').val();
if($("#ddPhone option[value='" + newPhone + "']").length == 0){
$('#ddPhone').append($('<option>', {
value: newPhone,
text: newPhone
}));
}
});
$('#btnDelPhone').on('click', function(){
var selected = $("#ddPhone option:selected").text();
$("#ddPhone option[value='" + selected + "']").remove();
});
...
...
以下是公司模型中的电话关系(应用\模型\设置\组织\Company.php):
public function phones(){
return $this->hasMany('App\Models\Setting\Organization\Phone', 'OwnerID', 'CompanyCode');
}
公司模型中的“电话”属性:
public function getPhonesAttribute(){
return $this->phones()->lists('PhoneNumber');
}
...
...
在手机模型(应用\模型\设置\组织\Phone.php)中:
protected $fillable = ['OwnerID', 'PhoneNumber'];
public function company(){
return $this->belongsTo('App\Models\Setting\Organization\CompanyCode', 'CompanyCode');
}
...
...
设置\组织\公司控制器中的存储方法:
public function store(CompanyRequest $request){
$phones = $request->input('Phones');
dd($request->input('Phones'));
if(count($phones) > 0){
foreach($phones as $phone){
Phone::create(['OwnerID' => $request->CompanyCode, 'PhoneNumber' => $phone]);
}
}
flash()->success('Company ' . $request->Name . ' Added.');
return redirect('company');
}
如果我删除dd$请求-
请帮忙,谢谢之前。
对于多选择,你应该传递所选的值,因为你的代码,我的理解是,你在ddPhone中追加选项,但你没有让它们被选择。所以试试这个。
$('#btnAddPhone').on('click', function(){
var newPhone = $('#txtNewPhone').val();
if($("#ddPhone option[value='" + newPhone + "']").length == 0){
$('#ddPhone').append($('<option>', {
value: newPhone,
text: newPhone,
selected: true
}));
}
});