dependendt dropdownlist in yii2 - yii2

<?= $form->field($model, 'fk_int_category_id')->dropDownList(
ArrayHelper::map(TblCategory::find()->all(), 'pk_category_id','vchr_category_name'),
['prompt'=> 'Select a category',
'onchange'=>'
$.post("index.php?r=product-size-variants/get-sub-category&id='.'"+$(this).val(), function(data){
//alert(data);
$("select#tblproduct-fk_int_sub_category_id").html(data);
});',
]) ?>
<?= $form->field($model, 'fk_int_sub_category_id')->dropDownList(
ArrayHelper::map(TblSubCategory::find()->all(), 'pk_sub_category_id','vchr_sub_category_name'),
['prompt'=> 'Select Sub category'
'onchange'=>'
$.post("index.php?r=product-size-variants/get-sub-category&subId='.'"+$(this).val(), function(data){
//alert(data);
$("select#tblproduct-fk_int_sub_category_id").html(data);
});'
]) ?>
<?= $form->field($model, 'fk_int_product_variants')->dropDownList(
ArrayHelper::map(TblProductSizeVariants::find()->all(), 'pk_int_product_size_variants_id','vchr_size_names'),
['prompt'=> 'Select Product Size']) ?>
i have three dropdownlist In second dropdownlist work using first one,
and third dropdownlist dependent to 1st and 2nd dropDown.
how to i pass 2 values in this index.php?r=product-size-variants/get-sub-category&subId= url??? of second dropdown

Your code is kind of mess, you might get caught error in writing js in php, where excape sequence has to be exectly to be same. i have done re-work. let me know if it working
<?= $form->field($model, 'fk_int_category_id')->dropDownList(
ArrayHelper::map(TblCategory::find()->all(), 'pk_category_id','vchr_category_name'),
['prompt'=> 'Select a category',
'onchange'=>'generateSubCat(this)',
]) ?>
<?= $form->field($model, 'fk_int_sub_category_id')->dropDownList(
ArrayHelper::map(TblSubCategory::find()->all(), 'pk_sub_category_id','vchr_sub_category_name'),
['prompt'=> 'Select Sub category'
'onchange'=>'generateProductVariant(this)'
]) ?>
<?= $form->field($model, 'fk_int_product_variants')->dropDownList(
ArrayHelper::map(TblProductSizeVariants::find()->all(), 'pk_int_product_size_variants_id','vchr_size_names'),
['prompt'=> 'Select Product Size']) ?>
<script>
function generateSubCat(obj){
$.post("index.php?r=product-size-variants/get-sub-category/?id="+obj.value, function(data){
$("select#tblproduct-fk_int_sub_category_id").html(data);
});
}
function generateProductVariant(obj){
var catID=$('#tblproduct-fk_int_category_id').val();
if(catID==""){
alert("Please select category");
}else{
$.post("index.php?r=product-size-variants/get-sub-category/?id="+catID+"&subId="+obj.value, function(data){
$("select#tblproduct-fk_int_sub_category_id").html(data);
});
}
}
</script>

Please refer to following url for dependent dropdown that can help you.
http://demos.krajee.com/widget-details/depdrop#basic-usage

Related

How to display a HTML tag in Yii2 form error summary

I am trying to display a link in error message in login for, but it is not working.
The error message in LoginForm valdiation:
$this->addError($attribute, 'Your account has been disabled. Enable It');
In login.php (view):
<?= $form->errorSummary($model); ?>
I tried like below, but not working:
<?= $form->errorSummary($model,['errorOptions' => ['encode' => false,'class' => 'help-block']]); ?>
I am getting the following output instead of rendered a tag:
You need to disable encoding at ActiveForm level using encodeErrorSummary property, if you want to use $form->errorSummary($model):
<?= $form = ActiveForm::begin([
'id' => 'login-form',
'encodeErrorSummary' => false,
'errorSummaryCssClass' => 'help-block',
]) ?>
<?= $form->errorSummary($model) ?>
Alternatively you may use Html::errorSummary() directly:
<?= Html::errorSummary($model, ['encode' => false]) ?>

Radio Button group separately in yii2 without using radiolist

I need Radio Button group in separate place in yii2 like in this question . I can customise the radio button like in this picture
but when I submit the form only the value of last radio is always submitted if last radio button is clicked respective value else null . I am not able to submit previous checked value.
mine form looks like
<div class="cart-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'product_id')->hiddenInput()->label(false) ?>
<?= $form->field($model, 'size_id')->dropDownList(
ArrayHelper::map(Productsize::find()->where(['product_id'=>$id])->all (), 'product_size_id', 'product_size' ),
[ 'prompt'=>'Select size',
'onchange'=>'
$.get( "'.Yii::$app->urlManager->createUrl('cart/lists?id=').'"+$(this).val(),
function( data ) {
$( "#pricetag11" ).val(data);
$( "#pricetaghtml" ).html(data);
});
']); ?>
<?php $colors = Productcolor::find()->where(['product_id'=>$id])->all(); ?>
<h4>Price:</h4> <p id="pricetaghtml" style="color:red;"></p>
Select size to see the price
<?php echo $form->field($model, 'price_id')->hiddenInput(['id'=>'pricetag11'])->label(false)?>
<!-- here is my problem -->
<h4>Color:</h4>
<?php foreach($colors as $color):?>
<div style="background-color:<?= $color->product_color;?>;width:20px;height:20px;padding-left:3px; display: inline-block"> <?= $form->field($model, 'color_id')->radio(['value' =>$color->product_color, 'label'=>'','uncheck'=>'null']); ?></div>
<?php endforeach;?>
<!-- -->
<?= $form->field($model, 'quantity')->textInput(['type' => 'number','min'=>'0','max'=>'9999' , 'placeholder'=>'0']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
In my scenario, I have to load color (hexcode) from database table and display in form and need to save the respective code in another table using radio button.
I have tried so many ways to accomplish this task in yii2 but i am not able. i hope someone will point me to the right direction.
I guess this will work,
<?= $form->field($model, 'color_id')->radioList(
$colors,
[
'item' => function($index, $label, $name, $checked, $value) {
$return = '<div style="background-color:'.$value.';width:20px;height:20px;padding-left:3px; display: inline-block">';
$return .= '<input type="radio" name="' . $name . '" value="' . $value . '">';
$return .= '</div>';
return $return;
}
]
)
->label(false); ?>

Yii2: How to validate a form with multiple instances of the same model

In my form I update more start and end dates from the same model at once. See the simplified form:
<?php $form = ActiveForm::begin(); ?>
<?php foreach($dates as $i=>$date): ?>
<?= $form->field($date,"[$i]start"); ?>
<?= $form->field($date,"[$i]end"); ?>
<?php endforeach; ?>
</table>
<?= Html::submitButton('Save'); ?>
<?php ActiveForm::end(); ?>
In the model I need to control, if the end date is after the start date:
public function rules() {
return [
[['end'], 'compare', 'compareAttribute' => 'start', 'operator' => '>', 'message' => '{attribute} have to be after {compareValue}.‌'],
];
}
I tried to change selectors similarly as described in: Yii2: Validation in form with two instances of same model, but I was not successful. I suppose I need to change the 'compareAttribute' from 'mymodel-start' to 'mymodel-0-start' in the validation JS:
{yii.validation.compare(value, messages, {"operator":">","type":"string","compareAttribute":"mymodel-start","skipOnEmpty":1,"message":"End have to be after start.‌"});}
So, I look for something like:
$form->field($date,"[$i]end", [
'selectors' => [
'compareAttribute' => 'mymodel-'.$i.'-start'
]
])
Solution
The solution is based on the answer of lucas.
In the model I override the formName() method, so for every date I have a unique form name (based on ID for the existing dates and based on random number for new dates):
use ReflectionClass;
...
public $randomNumber;
public function formName()
{
$this->randomNumber = $this->randomNumber ? $this->randomNumber : rand();
$number = $this->id ? $this->id : '0' . $this->randomNumber;
$reflector = new ReflectionClass($this);
return $reflector->getShortName() . '-' . $number;
}
The form then looks like this:
<?php $form = ActiveForm::begin(); ?>
<?php foreach($dates as $date): ?>
<?= $form->field($date,"start"); ?>
<?= $form->field($date,"end"); ?>
<?php endforeach; ?>
</table>
<?= Html::submitButton('Save'); ?>
<?php ActiveForm::end(); ?>
Override the formName() method in your model class to make it unique. If you don't want to change your model class, create a subclass of it for the purpose of working for this controller action. After doing this, the html ID and name fields will automatically be unique.

How to create a dropdown dependent on another dropdown in yii2?

I have two api's:
1: returns all the industries,
2: returns all the industry category(based on industry id).
I need two dropdowns, one dependent on other. On selecting industry 2nd dropdown should show only relevant categories.
Thanks in advance.
I got it. I have simply used ajax which posts the value from one dropdown and sends the data to an action which returns the data and i am simply putting those values to my other drop down. :)
<?= $form->field($model, 'industryId')->dropDownList($industry,
['prompt'=>'Select Industry',
'onchange'=>'
$.get( "'.Url::toRoute('/site/category').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'industryName').'" ).html( data );
}
);
','class' => 'form-control'
]
); ?>
<?= $form->field($model, 'industryName')
->dropDownList(
['prompt'=>'Select category','class' => 'form-control']);
?>
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Category;
?>
<?php $form = ActiveForm::begin(); ?>
$model = Category::find()->select('id,name')->orderBy('name asc')->all();
$listData = ArrayHelper::map($model, 'id', 'name');
<?= $form->field($model, 'industryId')->dropDownList($listData,
['prompt'=>'Select Category',
'onchange'=>'
$.get( "'.Url::toRoute('/category/subcats').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'sub_category').'" ).html( data );
}
);
','class' => 'form-control'
]
); ?>
<?= $form->field($model, 'sub_category')
->dropDownList(
['prompt'=>'Select sub cat','class' => 'form-control']);
?>
----
You can use this extension. You can find explanation of plugin on its guide page.

Yii2-user, dektrium-yii2-user, Yii2 Populate a dropdown in yii2

I am pretty sure that there is a better way to populate the array, needed for the dropdown:
<?php
$items2 = [Yii::$app->user->identity->id => Yii::$app->user->identity->username ]; ?>
<!--...some html -->
<?= $form->field($model, 'idUser')->dropDownList($items2,['Item' => ''])?>
already try:
$item2 = ArrayHelper::map(Yii::$app->user->identity::find()->all(), 'id', 'name');
reason, I want to display 'name' but submit 'value'='id'.
Should be this
<?= $form->field($model, 'idUser')->
dropDownList(ArrayHelper::map(Yii::$app->user->identity->find()->all(),
'id', 'username'), ['prompt'=>'Select...'])?>