YII2如何从动态形式的Select2中删除选定的值?
我使用wbraganca / yii2-dynamicform < / code>创建了一个动态表单,以处理我的解决方案中的请求。我有几个字段,例如项目,数量和单位。我有一个使用
arrayHelper
加载的项目列表,并且正在使用kartik的select2
窗口小部件来加载数据。
_FORM.PHP
<?php
use backend\models\Item;
use backend\models\ItemCategory;
use backend\models\ItemUnit;
use backend\models\Jobs;
use common\models\User;
use kartik\depdrop\DepDrop;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $model backend\models\Requests */
/* @var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
var i = index;
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
});
});
';
$this->registerJs($js);
$itemCategory = ItemCategory::find()->where(['cat_status' => 'Active'])->all();
$catData = ArrayHelper::map($itemCategory, 'cat_id', 'cat_name');
if (!Yii::$app->user->identity->isAdmin) {
$modelJobs = Jobs::find()
->joinWith('myJobs')
->where(['ja_user_id' => Yii::$app->user->id, 'ja_status' => 'Active'])
->all();
} else {
$modelJobs = Jobs::find()
->where(['job_status' => 'In Progress'])
->all();
}
$jobs = ArrayHelper::map($modelJobs, 'job_id', function ($modelJobs) {
return $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
});
if (isset($_GET['cid'])) {
$cat_id = $_GET['cid'];
$subCate = Item::find()->where(['item_category' => $cat_id, 'item_status' => 'Active'])->all();
$invListData = ArrayHelper::map($subCate, 'item_id', 'item_title');
} else {
$cat_id = '';
$invListData = [];
}
if (isset($_GET['job']) && $_GET['job'] != null) {
$job_id = $_GET['job'];
$modelJobs = Jobs::find()->where(['job_id' => $job_id])->one();
$job = $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
} else {
$job_id = '';
}
$modelUnit = ItemUnit::find()->where(['unit_status' => 'Active'])->all();
$unit = ArrayHelper::map($modelUnit, 'unit_id', function ($modelUnit) {
return $modelUnit->unit_name . '(' . $modelUnit->unit_short_name . ')';
});
?>
<div class="requests-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?php $form->errorSummary($model); ?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($model, 'rq_cat_type')->widget(Select2::class, [
'data' => $catData,
'options' => ['placeholder' => '--Select Material Category--', 'value' => $cat_id, 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
"select2:select" => "function(params) {
console.log($(this).val());
window.history.pushState('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
window.location.replace('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
jQuery.pjax.reload({ container: '#loaderPjax', async: false });
}",
],
]);
?>
</div>
<div class="col-md-4">
<?php if (isset($_GET['job']) && $_GET['job'] != null) { ?>
<?= $form->field($model, "rq_job_no")->dropDownList([$job_id => $job], ['value' => $job_id]) ?>
<?php } else { ?>
<?php echo $form->field($model, 'rq_job_no')->widget(Select2::class, [
'data' => $jobs,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?php } ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_req_date')->widget(\yii\jui\DatePicker::class, [
//'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
'clientOptions' => [
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
'yearRange' => '1990:2030',
'minDate' => date('Y-m-d'),
],
'options' => ['class' => 'form-control', 'readOnly' => true, 'placeholder' => 'Enter the Item Required Date'],
]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_priority_type')->dropDownList(['Urgent' => 'Urgent', 'Normal' => 'Normal'], ['prompt' => '--Select Priority Type--']) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_approval_type')->dropDownList([1 => 'Aramco Approved Vendor Needed', 2 => 'Approved Aramco Submitted Needed', 3 => 'Warranty Certificate to be Collected', 4 => 'Long Lead Material',], ['prompt' => '--Select Type of Approval--']) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4>
</div>
<?php Pjax::begin(['id' => 'loaderPjax']); ?>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'rt_item',
'rt_qty',
'rt_unit',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress) { ?>
<div class="item panel panel-default">
<!-- widgetBody -->
<div class="panel-heading">
<h4 class="panel-title pull-left"></h4>
<span class="panel-title-address"></span>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]rt_id");
}
?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php } ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
<?php Pjax::end(); ?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'rq_remarks')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
</script>
表单正常工作,但是我面临着新需求的一些问题。更新的是从列表中删除所选值。这意味着,如果我从下拉列表中选择一个值,则应在动态形式中更新列表,而无需选择下一个索引的选定值。
尝试使用JQuery和JavaScript的几个解决方案。需求的目的是避免重复的相同价值进入。谁能帮我吗?
I created a dynamic form using wbraganca / yii2-dynamicform
to handle requests in my solution. I have couple fields like Item, Qty and Unit. I have a list of items loaded using ArrayHelper
and I am using Kartik's Select2
widget to load the data.
_form.php
<?php
use backend\models\Item;
use backend\models\ItemCategory;
use backend\models\ItemUnit;
use backend\models\Jobs;
use common\models\User;
use kartik\depdrop\DepDrop;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $model backend\models\Requests */
/* @var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
var i = index;
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
});
});
';
$this->registerJs($js);
$itemCategory = ItemCategory::find()->where(['cat_status' => 'Active'])->all();
$catData = ArrayHelper::map($itemCategory, 'cat_id', 'cat_name');
if (!Yii::$app->user->identity->isAdmin) {
$modelJobs = Jobs::find()
->joinWith('myJobs')
->where(['ja_user_id' => Yii::$app->user->id, 'ja_status' => 'Active'])
->all();
} else {
$modelJobs = Jobs::find()
->where(['job_status' => 'In Progress'])
->all();
}
$jobs = ArrayHelper::map($modelJobs, 'job_id', function ($modelJobs) {
return $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
});
if (isset($_GET['cid'])) {
$cat_id = $_GET['cid'];
$subCate = Item::find()->where(['item_category' => $cat_id, 'item_status' => 'Active'])->all();
$invListData = ArrayHelper::map($subCate, 'item_id', 'item_title');
} else {
$cat_id = '';
$invListData = [];
}
if (isset($_GET['job']) && $_GET['job'] != null) {
$job_id = $_GET['job'];
$modelJobs = Jobs::find()->where(['job_id' => $job_id])->one();
$job = $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
} else {
$job_id = '';
}
$modelUnit = ItemUnit::find()->where(['unit_status' => 'Active'])->all();
$unit = ArrayHelper::map($modelUnit, 'unit_id', function ($modelUnit) {
return $modelUnit->unit_name . '(' . $modelUnit->unit_short_name . ')';
});
?>
<div class="requests-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?php $form->errorSummary($model); ?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($model, 'rq_cat_type')->widget(Select2::class, [
'data' => $catData,
'options' => ['placeholder' => '--Select Material Category--', 'value' => $cat_id, 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
"select2:select" => "function(params) {
console.log($(this).val());
window.history.pushState('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
window.location.replace('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
jQuery.pjax.reload({ container: '#loaderPjax', async: false });
}",
],
]);
?>
</div>
<div class="col-md-4">
<?php if (isset($_GET['job']) && $_GET['job'] != null) { ?>
<?= $form->field($model, "rq_job_no")->dropDownList([$job_id => $job], ['value' => $job_id]) ?>
<?php } else { ?>
<?php echo $form->field($model, 'rq_job_no')->widget(Select2::class, [
'data' => $jobs,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?php } ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_req_date')->widget(\yii\jui\DatePicker::class, [
//'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
'clientOptions' => [
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
'yearRange' => '1990:2030',
'minDate' => date('Y-m-d'),
],
'options' => ['class' => 'form-control', 'readOnly' => true, 'placeholder' => 'Enter the Item Required Date'],
]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_priority_type')->dropDownList(['Urgent' => 'Urgent', 'Normal' => 'Normal'], ['prompt' => '--Select Priority Type--']) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_approval_type')->dropDownList([1 => 'Aramco Approved Vendor Needed', 2 => 'Approved Aramco Submitted Needed', 3 => 'Warranty Certificate to be Collected', 4 => 'Long Lead Material',], ['prompt' => '--Select Type of Approval--']) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4>
</div>
<?php Pjax::begin(['id' => 'loaderPjax']); ?>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'rt_item',
'rt_qty',
'rt_unit',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress) { ?>
<div class="item panel panel-default">
<!-- widgetBody -->
<div class="panel-heading">
<h4 class="panel-title pull-left"></h4>
<span class="panel-title-address"></span>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]rt_id");
}
?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php } ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
<?php Pjax::end(); ?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'rq_remarks')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
</script>
The form is working perfectly, But I am facing some issues with the new requirement. The updated is to remove the selected value from the list. Which means if I select a value from the dropdown, the list should be updated without the selected value for next index in the dynamic form.
Tried couple of solutions with JQuery and javascript. The goal of requirement is to avoid duplicate entry of same value. Can anyone help me on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论