I am trying to validate a field in a dynamic form.
I need the field color_provider to exist in another table for certain id, in this case for id 123456 that is seen in the combo above. If I had for example the table2 with the id 123456 and with the color codes 001 and 002, any other that you enter in the form of the image will give me an error. I was trying to use the existent validator but I do not finish understanding and I do not know if it is possible to do something with the validator or do something personalized. Thanks
public function rules()
{
return [
[['id', 'cod_color_int','tela' ,'descripcion', 'nom_proveedor', 'tela_proveedor', 'color_proveedor', 'color_predominante', 'temporada'], 'required'],
[['id'], 'string', 'max' => 10],
[['id_tela'], 'string', 'max' => 7],
[['tela'], 'string', 'max' => 4],
[['cod_color_int', 'temporada'], 'string', 'max' => 3],
[['descripcion'], 'string', 'max' => 255],
[['nom_proveedor', 'color_proveedor'], 'string', 'max' => 50],
[['tela_proveedor', 'color_predominante'], 'string', 'max' => 45],
[['proceso'], 'string', 'max' => 10],
[['temporada'], 'string', 'max' => 3],
[['color_proveedor'], 'exist', 'targetClass' => TelasProvDet::className(), 'targetAttribute' => ['color_proveedor' => 'cod_color'],'allowArray' => true], // Se que esta mal pero estuve probando cosas similares.
[['id_tela'], 'exist', 'skipOnError' => true, 'targetClass' => Telas::className(), 'targetAttribute' => ['id_tela' => 'id']],
];
}
So what I'm looking for is that the provider_color field exists in the TelasProvDet table where cod_color is called for a given id
public function actionValidation() {
$model = new Telas();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
<?php $form = ActiveForm::begin(
[
'id' => $model->formName(),
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validationUrl' => Url::toRoute(['telas/validation']),
'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'd-none']],
'formConfig' => ['showLabels'=>false],
'errorSummaryCssClass' => 'alert alert-danger',
]
); ?>
<div class="form-group mt-3 card-grid p-3">
<?php Pjax::begin(['id' => 'pjax-container']); ?>
<?php $form = ActiveForm::begin(
[
'id' => $model->formName(),
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validationUrl' => Url::toRoute(['telas/validation']),
'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'd-none']],
'formConfig' => ['showLabels'=>false],
'errorSummaryCssClass' => 'alert alert-danger',
]
); ?>
<?php echo $form->errorSummary($model); ?>
<?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' => 999, // the maximum times, an element can be cloned (default 999)
'min' => 0, // 0 or 1 (default 1)
'insertButton' => '.clonar', // css class
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsTelasColores[0],
'formId' => $model->formName(),
'formFields' => [
'cod_color_int',
'descripcion',
'color_proveedor',
'color_predominante'
],
]); ?>
<div class="row">
<div class="col-md-2">
<?=
$form->field($model, "temporada")->widget(Select2::classname(),
[
'data' => ArrayHelper::map($getTemporadas,'id','descripcion'),
'language' => 'es',
'theme' => Select2::THEME_BOOTSTRAP,
'options' => ['placeholder' => 'Temporada'],
'pluginOptions' => [
'allowClear' => true,
],
'pluginEvents' => [
'change' => "function(){
setTimeout(function(){
$('#telas-id').focus().select()
}, 1);
}"
]
]);
?>
</div>
<div class="col-md-2">
<?= $form->field($model, 'id')->textInput(['maxlength' => 4, 'autocomplete' => 'off', 'placeholder' => 'Tela'])?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'descripcion')->textInput(['maxlength' => true, 'autocomplete' => 'off', 'placeholder' => 'Descripción', 'readonly' => true, 'tabindex' => '1']) ?>
</div>
<div class="col-md-3">
<?= $form->field($model, 'composicion')->textInput(['maxlength' => true, 'autocomplete' => 'off', 'placeholder' => 'Composición', 'readonly' => true, 'tabindex' => '1']) ?>
</div>
</div>
<div class="row">
<div class="col-md-3">
<?=
$form->field($model, 'nom_proveedor')->widget(Select2::classname(),
[
'data' => ArrayHelper::map($getProveedores,'nom_proveedor','nom_proveedor'),
'language' => 'es',
'theme' => Select2::THEME_BOOTSTRAP,
'options' => ['placeholder' => 'Seleccione un proveedor', 'disabled' => $model->isNewRecord ? true : false],
'pluginOptions' => [
'allowClear' => true,
],
'pluginEvents' => [
'change' => "function(){
setTimeout(function(){
$('#telas-id_telaprovcab').select2('focus')
}, 1);
}"
]
]);
?>
</div>
<div class="col-md-5">
<?=
$form->field($model, 'id_telaprovcab')->widget(DepDrop::classname(), [
'type' => DepDrop::TYPE_SELECT2,
'select2Options'=>['pluginOptions'=>['allowClear'=>true]],
'pluginOptions'=>[
'depends'=>['telas-nom_proveedor'],
'initialize' => true,
'params'=> ['input-type-1'],
'url' => Url::to(['proveedor-telas']),
'loadingText' => 'Cargando Telas...',
'placeholder' => 'Seleccione una Tela',
],
'pluginEvents' => [
'change' => "function(){
$.post('".Url::to(['colores'])."', {id : $(this).val()}, function(result){
data = JSON.parse(result)
$('.container-items').html('')
$.each( data, function( key, value ) {
$('button[name=new]').click();
index = $('.panel-default').length - 1
$('#telascolores-'+index+'-color_proveedor').val(value.cod_color)
$('#telascolores-'+index+'-color_proveedor').prop('readonly',true)
$('#telascolores-'+index+'-color_predominante').val(value.color_predominante).trigger('change')
$('#telas-descripcion').val(value.tela_proveedor)
$('#telas-composicion').val(value.composicion)
if(value.tipo == 'APTA'){
$('#telascolores-'+index+'-descripcion').val($('#telas-descripcion').val())
}else{
$('#telascolores-'+index+'-descripcion').val(value.descripcion)
}
$('#tipo').val(value.tipo)
var cant = $('.panel-default').length
$('#cant').val(cant);
});
setTimeout(function(){
$('#telascolores-0-cod_color_int').focus().select()
}, 1);
});
}"
]
]);
?>
</div>
<div class="col-md-2 d-none">
<button type="button" title="Agregar Fila" style="font-size: 0.8rem !important" class='add-item btn btn-success p-2 hidden-sm-down' name='new' tabindex="1"><i class="fa fa-plus text-center "></i></button>
</div>
</div>
<?php echo Html::hiddenInput('input-type-1',$model->id_telaprovcab,['id'=>'input-type-1']); ?>
<?php echo Html::hiddenInput('tipo',$model->tipo,['id'=>'tipo']);?>
<?php echo Html::hiddenInput('cant',count($modelsTelasColores),['id'=>'cant']);?>
<hr>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsTelasColores as $i => $modelTelasColores): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelTelasColores->isNewRecord) {
echo Html::activeHiddenInput($modelTelasColores, "[{$i}]id");
}
?>
<div class="row">
<div class="col-md-2">
<?= $form->field($modelTelasColores, "[{$i}]cod_color_int",[
'addon' => ['prepend' => ['content'=>'Color']]
])->textInput(['maxlength' => true, 'autocomplete' => 'off', 'placeholder' => 'Cod. Color']) ?>
</div>
<div class="col-md-4">
<?= $form->field($modelTelasColores, "[{$i}]descripcion")->textInput(['maxlength' => true, 'autocomplete' => 'off', 'placeholder' => 'Descripción']) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelTelasColores, "[{$i}]color_proveedor")->textInput(['maxlength' => true, 'autocomplete' => 'off', 'placeholder' => 'Color proveedor', 'readonly' => true, 'tabindex' => '1']) ?>
</div>
<div class="col-md-2 col-8">
<?=
$form->field($modelTelasColores, "[{$i}]color_predominante")->widget(Select2::classname(),
[
'data' => ArrayHelper::map(ColoresWeb::find()->all(),'descripcion','descripcion'),
'language' => 'es',
'theme' => Select2::THEME_BOOTSTRAP,
'options' => ['placeholder' => 'Color predominante'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-md-2 col-4">
<button type="button" title="Clonar" style="font-size: 0.8rem !important" class='add-item btn btn-warning p-2 clonar'><i class="fa fa-clone text-center"></i></button>
<button type="button" title="Eliminar" style="font-size: 0.8rem !important" class='remove-item btn btn-danger p-2' tabindex= '1'><i class='fa fa-trash text-center'></i></button>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
<div class="row mt-2">
<div class="col-md-12">
<!-- BOTON GUARDAR AJAX -->
<?php AjaxSubmitButton::begin([
'label' => 'Guardar',
'useWithActiveForm' => $model->formName(),
'ajaxOptions' => [
'type'=>'POST',
'url'=>$model->isNewRecord ? 'create' : Url::to(['update', 'id' => $model->temporada.$model->id]),
'success' => new \yii\web\JsExpression('function(data){
}')
],
'options' => ['class' => 'btn btn-primary', 'type' => 'submit'],
'icon' => 'fas fa-save'
]);
AjaxSubmitButton::end(); ?>
<?= Html::a("<i class='fas fa-ban text-center'></i> Cancelar", ['cancelar'], ['class'=>'btn btn-danger']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
<?php
$this->registerJs("
if( $('#telas-temporada').val() !== '' && $('#telas-nom_proveedor').prop('disabled') == false){
$('#telas-id').focus().select()
}
$('#telas-id').on('keyup',function(e){
if(e.target.value.length==4){
$.ajax({
url: '".Url::to(['buscar-tela'])."',
data: {id : $('#telas-temporada').val()+$(this).val() },
success: function(result) {
if(!result){
$('#telas-nom_proveedor').prop('disabled',false)
$('#telas-nom_proveedor').focus()
}
},
})
}
});
$('.dynamicform_wrapper').on('afterInsert', function(e, item) {
if($('.panel-default').length <= $('#cant').val() ){
index = $('.panel-default').length -1
}else{
index = $('.panel-default').length -1
$('#telascolores-'+index+'-descripcion').val($('#telas-descripcion').val())
if($('#tipo').val() == 'APTA'){
$('#telascolores-'+index+'-color_proveedor').val($('#telascolores-'+(index-1)+'-color_proveedor').val())
$('#telascolores-'+index+'-color_proveedor').prop('readonly',true)
}else{
$('#telascolores-'+index+'-color_proveedor').prop('readonly',false)
}
}
})
"
, \yii\web\View::POS_END);
?>
<?php Pjax::end(); ?>