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;
}
}
Related
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.
I've view page(index.php) in my Yii2 project, and I'm using Kartik gridView for showing the data
This the view from index.php:
On the right side of view, I've a checkbox column.
And I've an Export button.
I want to export the selected name (selected by checkbox) into name.txt file.
I've finally make the export function, but I don't know how to get the selected data from view into controller.
I've try suggestions that I got from many forums, for example:
I put this javascript code in my view index.php:
<script>
function getRows(){
var keys = $('#grid').yiiGridView('getSelectedRows');
$.post({
url: FakturOutController / exportAction,
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
});
}
and set the export button like this:
<p>
<button type="button" onclick="getRows()" class="btn btn-success">Export</button>
</p>
But I got nothing, the button didn't showed any action/reaction when clicked.
This is the gridView code in index.php:
`<?php Pjax::begin(); ?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' => ['class' => 'table table-hover'],
'columns' => [
['class' => 'yii\grid\SerialColumn',
'header' => 'No',
],
[
'label' => 'Name',
'value' => function($data) {
return $data->name;
}
],
['class' => '\kartik\grid\CheckboxColumn'],
],
'toolbar' => [
['content' =>
Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['index'], ['data-pjax' => false, 'class' => 'btn btn-default', 'title' => 'Reset Grid'])
],
'{export}',
'{toggleData}'
],
'panel' => [
'heading' => '<i class="glyphicon glyphicon-align-left"></i> <b>Data</b>',
'before' => '', //IMPORTANT
],
]);
?>
<?php Pjax::end(); ?>
<?=
Html::a('<i class=" glyphicon glyphicon-export"></i> Export', ['export', 'userId' => $userId], ['class' => 'btn btn-success']);
?>`
Any help would be appreciated. Thanks
By inspect element on checkbox column you can find name of row ( checkbox name ). it contain id as value.
from that you can find how many rows are selected.
in my case i get 'selection[]' in checkbox name.
ex.
<input type="checkbox" class="kv-row-checkbox" name="selection[]" value="1">
i write jquery code to get selected rows below.
<script>
function getRows()
{
var strvalue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strvalue!="")
strvalue = strvalue + ","+this.value;
else
strvalue = this.value;
});
// strvalue contain selected row by comma separated
$.post({
url: FakturOutController / exportAction,
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
});
}
</script>
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]);
}
I have a dropdown menu, that has a onchange function. Once the function is executed it changes another dropdown menu.
I need to make it so it executes the script onload.
1st dropdown:
echo $form->field($model, 'company_id')->dropDownList($items_company, ['prompt' => 'Select Company', 'style' => 'width:400px;', 'onchange' => '
$.post("index.php?r=project/lists&id=' . '"+$(this).val(), function( data ) {
$( "select#project-client" ).html( data );
console.log("On change");
console.log(data);
});
',])->label('Company');
2nd dropdown:
echo '<label class="control-label">Company Client</label>';
echo Select2::widget([
'model' => $model,
'attribute' => 'client',
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [ 'label' => 'Client',
'multiple' => true, 'style' => 'width:400px;', 'overwriteInitial' => true],
'pluginOptions' => [
'disabled' => false,
],
]);
This is what I tried:
$(document).ready(function () {
var currentProjectCompany = $('#project-company_id').val();
$.post("index.php?r=project/lists&id=' . '" + currentProjectCompany, function (data) {
$("select#project-client").html(data);
console.log("Company ID:");
console.log(currentProjectCompany);
console.log("Clients");
console.log(data);
});
});
Move the onchange code into its own function (it should be there anyway), and execute that function in the ready() function.
That way it will fire both onchange and onload.
I do the same check my code it may help you .But i use ajax and jquery.
For firs dropdown .
echo $form->dropDownListGroup(
$model 'id', array(
'wrapperHtmlOptions' => array(),
'widgetOptions' => array(
'data' => abc::getName($model->id),
'htmlOptions' => array(
'prompt' => 'Select Project',
'ajax' => array(
'type' => 'POST',
'url' => ( Yii::app()->createUrl('/' . $domain_name . '/qq/xyz/abc') ),
'update' => '#seconddropdownid',
//'dataType' => 'json',
'data'=>array('id'=>'js:this.value'),
)
),
),
)
);
in second dropdown :
echo $form->dropDownListGroup(
$project, 'tag', array(
'wrapperHtmlOptions' => array(),
'widgetOptions' => array(
'data' =>$this->getProjectTags(),
'htmlOptions' => array(
'prompt' => 'Select Tags',
),
)
)
);
on change of the second list you can update the the list-view of yii .
i have two tables user and department where department has two fields id and name i want to create a view so that when someone selects a department name from the dropdownlist the user's name of all in that department show in another dropdownlist using AJAX and How to call that in controller
<script>
jQuery(document).ready(function ($) {
//jQuery('#searchTable').dataTable();
$('#department_id').change(function () {
jQuery('#user').empty();
var data2 = {};
data2['department_id'] = jQuery(this).val();
var json = JSON.stringify(data2);
jQuery.ajax({
type: "POST",
url: "/AjaxRequests/name",
data: json,
dataType: "json",
success: function (response) {
var app = "<option value>All</option>";
jQuery('#user').append(app);
jQuery.each(response, function (i, text) {
jQuery('#user').append(jQuery('<option></option>').val(i).html(text));
});
}
});
});
</script>
this is the script i am using
and in view the department dropdown is like this
<?php echo $this->Form->input('department_id', array('onChange' => 'showFields(this.value)', 'class' => 'form-control-custom', 'id' => 'department_id', 'type' => 'select', 'label' => true, 'label' => 'department:', 'options' => $departments, 'empty' => 'Select A Department', 'required' => 'false'))
?>
Anyone please help me with this ajax and also the controller
According to your code, can u try to replace 'id' => 'department' with 'id' => 'department_id' . Cause it's seen here you are using department_id as selector but your department_id id as not declared in dropdownlist. Here you declared department as ID. So selector is not found. So Just replace 'id' => 'department' with ''id' => 'department_id'', Hope it can be helpful to you.