How to hide block with yii2 dropdown list - javascript

I have dropDownList in Yii2 project
<?= $form->field($model, 'license', ['options' =>['onchange'=>'getSalutationValue()'] )->dropDownList(['y' => 'Yes', 'n' => 'No']) ?>
i want hide some block if user seleckted value 'n'
I tried this function
function getSalutationValue() {
var label = this.value;
if(label == 'n' ) {
document.getElementById('driver').style.display='none';
}}
What am i doing wrong? Please help me

You are not passing object of input field, so that you can use its value,
try this
<?= $form->field($model, 'license', ['options' =>['onchange'=>'getSalutationValue(this)'] )->dropDownList(['y' => 'Yes', 'n' => 'No']) ?>
in script
function getSalutationValue(obj) {
var label = obj.value;
if(label == 'n' ) {
document.getElementById('driver').style.display='none';
}}
Updated:
<?= $form->field($model, 'license')->dropDownList(['y' => 'Yes', 'n' => 'No'],['onchange'=>'getSalutationValue(this)']) ?>

Related

how will I append data I am selecting from a dropdown list to the next input field in yii2

I want to select courses from the course field, then let it show in my courses field and submit the courses to the database. or if someone can help me so my courses can appear has a checkbox and once i tick a checkbox, it appears in the courses field
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'student_id') ?>
<?=
$form->field($model, 'faculty_id')->dropDownList(
ArrayHelper::map(Faculties::find()->asArray()->all(), 'faculty_id', 'faculty_name'), [
'prompt' => 'Select Faculty',
'onchange' => '$.post("' . Yii::$app->urlManager->createUrl('/departments/lists?id=') . '"+$(this).val(), function(data) {
$("select#registrations-department_id").html (data);
});'
]
);
?>
<?=
$form->field($model, 'department_id')->dropDownList(
ArrayHelper::map(Departments::find()->asArray()->all(), 'department_id', 'department_name'), [
'id' => 'registrations-department_id',
'prompt' => 'Select Department',
'onchange' => '$.post("' . Yii::$app->urlManager->createUrl('/courses/lists?id=') . '"+$(this).val(), function(data) {
$("select#registrations-course_id").html (data);
});'
]);
?>
<?=
$form->field($model, 'course_id')->dropDownList(
ArrayHelper::map(Courses::find()->asArray()->all(), 'course_id', 'course_name'), [
'id' => 'registrations-course_id',
'prompt' => 'Select Course',
'onchange' => '$.post("(selected:)."+$(this).val(), function(data){
$("#registrations-courses").append(data)
});'
]);
?>
<!-- <?//= $form->field($model, 'courses')->checkBoxList([]) ?> -->
<?=$form->field($model, 'courses') ?>
<?=$form->field($model, 'comment') ?>
<?=$form->field($model, 'status') ?>
<?=$form->field($model, 'created_at') ?>
<?=$form->field($model, 'updated_at') ?>
<div class="form-group">
<?=Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
EDIT
this is my controller how do I save the courses in the database in the same column?
public function actionCreate()
{
$model = new Registrations();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
// form inputs are valid, do something here
$model->student_id = Yii::$app->user->identity->id;
$model->faculty_id = 1 ;
$model->department_id = null ;
$model->course_id = 1;
$model->save();
return $this->redirect('../site/profile');
}
}
return $this->render('create', [
'model' => $model,
]);
}
You can use the checkBoxList() to create the list of checkboxes based on the courses list.
Change your course_id field to the following
$form->field($model, 'course_id')->checkboxList(yii\helpers\ArrayHelper::map(Courses::find()->asArray()->all(), 'course_id', 'course_name'), [
'inline' => true,
'unselect'=>null,
'item' => function($index, $label, $name, $checked, $value){
$checked = $checked ? 'checked' : '';
return "<input type='checkbox' class='my-courses' name='{$name}' value='{$value}' {$checked} data-label='{$label}'> <label>{$label}</label>";
}]);
add an id attribute to your courses field like below
$form->field($model, 'courses', ['inputOptions' => ['id' => 'courses']]);
and then add this javascript code to the top of your page
$js = <<< JS
$(".my-courses").on('click',function(e){
let course_name=$(this).data('label');
let course_field=$("#courses");
if($(this).is(":checked")){
$("#courses").val()==''?course_field.val(course_name):course_field.val(course_field.val()+', '+ course_name);
}else{
let regex=new RegExp(',{0,1}\\\s{0,1}('+course_name+')','g');
course_field.val(course_field.val().replace(regex,''));
}
})
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you select the checkbox the name of the course would be copied to the input field and when you submit your form you can get the fields in your $_POST array under your specific model index like below.
[course_id] => Array
(
[0] => 1
[1] => 2
)
[courses] => asdas, shugal, spoon
You can verify by adding a print_r(Yii::$app->request->post()) in your controller action inside the check
if($model->load(Yii::$app->request->post())){
print_r(Yii::$app->request->post());
You can iterate on the course_id to save all of the course_id that were selected as checkboxes.

Html::dropDownList depending Yii2

I have a problem to connect two select. I would like the choice of a select filters the search of the second select statement.Both select take data from their tableDB but are not influenced each other. Can someone help me?
my first select customers take data from db table customers:
<?=
Html::dropDownList('userlist', [],
ArrayHelper::map(Customers::find()->where('id',['company_id' =>
'name'])->orderBy('name')->all(), 'id', 'name'),
['prompt' => 'Select a User ...',
'class' => 'form-control',
'style' => 'width: 100%;']);
?>
my second select offers take data from db table offers:
<?=
Html::dropDownList('offerslist', [],
ArrayHelper::map(Offers::find()->where('customer_id',['company_id'
=> 'offers_n'])->orderBy('customer_id')->all(),
'id','offers_n','customer_id'),
['prompt' => 'Select a Offert ...',
'onchange' => 'change_user_list(this.value)',
'class' => 'form-control',
'style' => 'width: 100%;']);
?>
This is my function js:
function change_user_list(company_id)
{
$.ajax({
url: "<?= \yii\helpers\Url::to(['offers/userlist'])?>",
type: 'get',
data: {
company_id: company_id
},
success: function (data) {
document.getElementsByName('userlist')[0].innerHTML = data;
}
});
}
this is my actionFucntion in the controller:
public function actionUserlist($company_id)
{
if (Yii::$app->request->isAjax) {
$userlist = ArrayHelper::map(Customers::find()-
>where(['company_id' => $company_id])->orderBy('name')->all(),
'id', 'name');
$string = "<option value>Select a Users</option>";
foreach($userlist as $id => $name) {
$string .= "<option value=".$id.">".$name."</option>";
}
return $string;
}
}

Pass javascript value to a form action URL in Yii2

I'm trying to put a value from javascript into a form action in Yii2
is it possible?
More specifically I need to make a URL change for each option that is selected in a dropdownList.
form in views/site.php
$form = ActiveForm::begin([
'id' => 'form',
'method' => 'POST',
'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa]),
]);
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList([],
[
'prompt' => 'Programa',
'id' => 'child1_child2',
'onchange' => 'updateValue(this.value)',
]
)->label(false); ?>
Js file
function updateValue(val){
x = document.getElementById("test").value;
// document.getElementById("form").action = "programas/";
}
So, I rescue the value from the selected option with JS but I need to put it in here 'pk' => 'value'
where value is the #child1_child2 selected option value.
'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa])
Thanks for the help.
You can use one of the following approach with some modification:
//pk => programa
$data = [
1 => 'programa1',
2 => 'programa2',
3 => 'programa3',
];
1) Use JS
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, ['prompt' => 'Programa'])->label(false); ?>
JS
$this->registerJs('
$("#dropdownID").change(function() {
var text = $("#dropdownID option:selected").text();
$("#formID").attr("action", "/pathtoproject/programas/" + text);
});
', \yii\web\View::POS_END);
2) Use Ajax Call
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, [
'prompt' => 'Programa',
'onchange'=> '$.get( "'.Url::toRoute('get-action').'", { id: $(this).val() } )
.done(function( data ) {
$("#formID").attr("action", data);
}
);'
])->label(false); ?>
Controller
public function actionGetAction($id)
{
$name = Tours::findOne(['pk' => $id])->programa];
echo \yii\helpers\Url::to(['programas/'.$name]);
}

How to submit multipart form in Yii2?

I have a problem with my form because it cant serialize the image file. So how can I submit a form that contains an image file input in Yii2 using ajax?
(Below you can see the active form and the js code.)
<div class="cars-form">
<?php $form = ActiveForm::begin(['options'=>['id'=>$model->formName(),'enableAjaxValidation'=>true,'enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($model, 'colour')->widget(ColorInput::classname(), ['options' => ['placeholder' => 'Select Color...'],]); ?>
<?=$form->field($model, 'imageFile')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],'pluginOptions' => [
'previewFileType' => 'image',
'showUpload' => false],]);?>
<?= $form->field($model, 'price')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit',function(e)
{var \$form =$(this);
$.post(
\$form.attr("action"),
\$form.serializefiles()
)
.done(function(result)
{
if (result == 1)
{
$(\$form).trigger("reset");
$.pjax.reload({container:'#cars'});
}
else
{
$("#message").html(result);
}
}).fail(function(data)
{console.log("server error: " + data);});
return false;
});
JS;
$this->registerJs($script);?>
(Controller)
public function actionCreate()
{
$model = new Cars();
if ($model->load(Yii::$app->request->post())) {
$imageName= $model->name;
$model->imageFile= UploadedFile::getInstance($model,'imageFile');
$model->imageFile->saveAs('carsimages/'.$imageName.'.'.$model->imageFile->extension);
$model->image='carsImages/'.$imageName.'.'.$model->imageFile->extension;
if($model->save())
//{
//return $this->redirect(['view', 'id' => $model->id]);
//}
{
echo 1;
}
else
{
echo 0;
}
}
else {
return $this->renderAjax('create', [
'model' => $model,
]);
}}

how to unhidden field base on the field validation in yii2

i have some field that set to hidden and i want to unhidden the field based on the other field validation. how can i do this using jquery??
here is my code:
<?php $form = ActiveForm::begin([
'id' => 'assign-form',
'enableAjaxValidation' => true,
]); ?>
<?= $form->field($volunteeringin, 'acId', [
'template' => '{label} <div class="row"><div class="col-md-5">{input}{error}{hint}</div></div>',
])->dropDownList($model->getActivitySearch(),['prompt'=>'בחר פעילות לשיבוץ המתנדב'])->label('פעילויות לשיבוץ')?>
<?= $form->field($volunteeringin, 'passedTraining')->radioList([0=>'לא',1=>'כן'] ,['separator' => '</br>','class'=>'hidden','id'=>'demo'])->label('האם המתנדב עבר הכשרה?'); ?>
<div class="form-group">
<?= Html::submitButton( 'שבץ מתנדב' ,['class' => 'btn btn-success' ]) ?>
</div>
<?php ActiveForm::end(); ?>
i want to set the field "passedTraining" to unhidden base on the the above field validation.
i try to use this function:
$('#fieldID').on('afterValidateAttribute', function(event, attribute, messages) {
if(messages.length == 0){
$('#demo').removeClass('hidden');
}
});
thanks
eli
I tested your code, and you have just a small error:
<?php $form = ActiveForm::begin([
'id' => 'assign-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true, // enable this!
]); ?>
Hope this helps!

Categories