I am new in Yii framework, so I don't have much idea in it.
My question is, I want to get details of the company which is selected in a search box.
Code in my frontend/companies.php
<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ?>
Here's my select2 widget code:-
$typeahead = Select2::widget([
'id' => 'front_companies_select',
'name' => 'state_10',
'data' => $companyNameList,
'options' => [
'placeholder' => 'Select ...',
'sigle' => true
],
]);
My js code:-
$("#getinfo").click(function(){
var obj = $("#front_companies_select option:selected").val();
console.log(obj);
});
If you want to get only company name you can try this.
$("#getinfo").click(function(){
var company_id = $("#front_companies_select option:selected").val();
console.log(company_id);
var companyName = $("#front_companies_select option:selected").text();
console.log(companyName); //here you can get company name
});
Or If you want to get whole company details then you have to call ajax like this.
$("#getinfo").click(function(){
var company_id = $("#front_companies_select option:selected").val();
$.ajax({
type: "POST",
url:"YOUR_URL/YOUR_FUNCTION_TO_GET_COMPANY_DETAILS",
data: {company_id:company_id},
dataType:'json',
async: false,
success: function (data)
{
console.log(data); //here you can get all the company details in object
}
});
});
Related
This is my code:
[
'attribute' => 'status',
'value' => function ($model) {
return Html::dropDownList('status', ['10' => 'Active', '20' => 'Deactive']);
},
],
I just want dropdown in status column. If record is active or deactive it will be selected.
You need to use 'format' => 'raw' for the column options and your definition for the dropDownList() is wrong you need to have the selection string as the second parameter and the dropdown options as the third parameter. Change your code to below:
[
'attribute' => 'status',
'format' => 'raw',
'value' => function ($model) {
return Html::dropDownList('status', $model->status, ['10' => 'Active', '20' => 'Deactive']);
},
],
EDIT
You didnt had in the initial requirements that you waned to update the status too when the drop down is changed. You can bind ajax call to the drop-down.
Add the following javascript on top of your view where you are initializing the GridView.
NOTE: Change the url:'controller/update-status?id'+id in the ajax call to the relative controller where you want to update the status for the row, but dont remove the id
$js = <<<JS
$(document).on('ready pjax:success',function(){
$(".switch-status").on('change',function(){
var data={};
data[$(this).attr("name")]=$(this).val();
var id=$(this).closest("tr").data('key');
$.ajax({
method:'post',
url:'/controller/update-status?id='+id,
data:data,
success:function(data){
if(!data.success){
alert(data.message);
}else{
alert("Status updated.");
}
},
error:function(jqXHR, textStatus, errorThrown ){
alert(errorThrown);
}
});
});
});
JS;
$this->registerJs($js, yii\web\View::POS_END);
Then inside your GridView column for status change the dropdown to the following
return Html::dropDownList(Html::getInputName($model, 'active'), $model->active, [10 => 'Active', 20 => 'Deactive'], ['class' => 'switch-status']);
And the go to your controller and add the action code for updating the status
Note: Change the Model in the first line $model = Model::findOne($id); name with the respective model you are using.
public function actionUpdateStatus($id) {
$model = Affiliate::findOne($id);
$app = Yii::$app;
$request = $app->request;
if($request->IsAjax && $request->isPost) {
Yii::$app->response->format = Response::FORMAT_JSON;
if($model->load($request->post()) && $model->save()) {
return ['success' => true];
} else {
return [
'success' => false,
'message' => implode('<br />', ArrayHelper::getColumn($model->errors, '0'))
];
}
}
}
Use content property to render HTML elements. For example:
[
'attribute' => 'status',
'content' => function ($model) {
return Html::dropDownList('status', $model->status, ['10' => 'Active', '20' => 'Deactive']);
},
],
homepage.html.twig
<a class="load-form" href="{{ path('article_load_form', {slug:page.slug}) }}">Load my beautiful form</a>
<div class="show-form">form will appear here</div>
<script>
$( ".load-form" ).on( "click", function(e) {
e.preventDefault();
var $link = $(e.currentTarget);
$.ajax({method:'POST', url: $link.attr('href')}).done(function(data){
$('.show-form').html(data.output);
});
});
</script>
myController.php
/**
* #Route("/pages/{slug}/heart", name="article_load_form", methods={"POST"})
*/
public function loadForm($slug, Request $request){
$id = 9;
$item = new User();
$item= $this->getDoctrine()->getRepository(User::class)->find($id);
$form = $this->createFormBuilder($item)
->add('username', TextType::class, array('attr' => array('class' => 'form-control')))
->add('email', EmailType::class, array('attr' => array('class' => 'form-control')))
->add('is_active', HiddenType::class)
->add('plainPassword', RepeatedType::class, array('type' => PasswordType::class,'invalid_message' => 'The password fields must match.','options' => array('attr' => array('class' => 'password-field')),'required' => false,'first_options' => array('label' => 'Passwort', 'attr' => array('class' => 'form-control')),'second_options' => array('label' => 'Passwort wiederholen', 'attr' => array('class' => 'form-control')),))
->add('cancel', ButtonType::class, array('label' => 'Abbrechen','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
if($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
}
}
My form is loaded when I click on "Load my beautiful form" with all the data from the database for each field. So this is working fine. BUT when I then change the data inside the form (for example the username from "leo" to "alan") and click the save button, then no data is stored in the database (the username is still "leo").
In the profiler the POST parameters are correct. But no forms were submitted for this request.
The action will return a response before the following block will be reached
if($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
}
So nothing will be stored in the DB.
then let's see what you are trying to do,
you try to get your beautiful from with ajax and put it to your load-form, so you need at first to use a get method, method:'GET',
after that you need an other ajax method to load your data to the server with post
$('#submit-my-beautiful-form').click(function(e){
e.preventDefault();
var form = $(this).closest('form');
var formData = form.serialize();
alert(formData);
$.ajax({
method:'POST',
url: $link.attr('href'),
data: formData,
success: function(data){
alert(data);
}
});
})
ps: your form data will be serialized and affected to formData variable and then loaded to the server
ps: you need to add an id to your save button :
->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('id' => 'submit-my-beautiful-form', 'class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
ps: dont forget to persist your $item object
$entityManager->persist($item);
I have a dropdown list of company names. When I select companies from it and click on 'get info' button I should get rows with selected company id.
View
$typeahead = Select2::widget([
'id' => 'front_companies_select',
'name' => 'state_10',
'data' => $companyNameList,
'options' => [
'placeholder' => 'Select ...',
'multiple' => true
],
]);
<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ?>
Javascript file
$("#getinfo").click(function(){
var id = $("#front_companies_select option:selected").val();
console.log(id); //want to pass this id in controller as ap parameter actionInfo($id)
});
Controller
public function actionVerify($id) // want to get id here
{
$model = $this->findModel($id);
$connection = Yii::$app->db;
$model = $connection->createCommand("SELECT * FROM companies where id=$id");
$users = $model->queryOne();
return $this->redirect(['companies/index']); //want to show rows in this gridview
}
Can any one fix it? I am stuck with it..
Asuming that you're in a controller without any URL params you can do something like this:
$("#getinfo").click(function(){
var id = $("#front_companies_select option:selected").val();
window.location.href = 'verify?id=' + id;
});
Otherwise you have to build the URL and passing it to window.location
I've a field called employee_name and depending on this field value I want to autofill another field employee_id. I've searched and I found this answer and tried implementing this on my form but I'm getting Error in ajax request. The jquery code in my form is
$('#emp').focusout(function() {
empName = this.value;
if ( empName != '' || empName != null ) {
$('#depcustomer-employee_name').val(empName);
}
$.ajax({
url: '".yii\helpers\Url::toRoute("deposit/employeeid")."',
dataType: 'json',
method: 'GET',
data: {name: $(this).val()},
success: function (data, textStatus, jqXHR) {
$('#depcustomer-employee_id').val(data.id);
},
beforeSend: function (xhr) {
alert('loading!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
});
My Controller name is Deposit and my controller code is
public function actionEmployeeid($name){
$model= app\modules\settings\models\DepEmployee::findOne(['employee_name'=>$name]);
return \yii\helpers\Json::encode([
'id'=>$model->employee_id
]);
What could be the possible reason that my ajax code is not working?
My form is quite big. Here's the part of the employee field entry
<div class="row">
<div class="col-md-6">
<?= $form->field($model, 'employee_id')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<label for='emp'>Employee Name</label>
<?= Html::activeHiddenInput($model, 'employee_name')?>
<?php
echo AutoComplete::widget([
'name' => 'employee_name',
'id' => 'emp',
'clientOptions' => [
'source' => $dataEmp,
'autoFill'=>true,
'minLength'=>'2',
'select' => new JsExpression("function( event, ui ) {
$('#depcustomer-name').val(ui.item.id);
}")
],
]);
?>
</div>
</div>
According to your autocomplete data you already have employee_id. So no need to make ajax request to get employee id.
DepEmployee Model
public static function getEmpData()
{
$dataEmp = DepEmployee::find()
->select(['employee_name as value', 'employee_name as label','employee_id as id'])
->asArray()
->all();
return $dataEmp;
}
_form
<?= AutoComplete::widget([
'name' => 'employee_name',
'id' => 'emp',
'clientOptions' => [
'source' => DepEmployee::getEmpData(),
'autoFill'=>true,
'minLength'=>'2',
'select' => new JsExpression("function( event, ui ) {
$('#depcustomer-name').val(ui.item.id);
$('#depcustomer-employee_id').val(ui.item.id);
}")
],
]);?>
What i should do if i was at your place:
Here the view:
<?= $form->field($model, 'employeeName')->textInput([
// I use onfocusout instead of focusout
'onfocusout' => '
$.post("generateemployeeid?name="+$(this).val(), function(data) {
$("#employee_id_container").html(data);
});
',
]) ?>
<div id="employee_id_container"></div> // <- I will autofill here
Now here is the function who will fill the ID input: (should be in your controller)
public function actionGenerateemployeeid($name) {
$employeeModel = DepEmployee::find()
->where(['employee_name' => $name])
->one();
if($employeeModel !== NULL) {
echo 'Employee ID: <input type="text" name="EmployeeID" value="'.$employeeModel->employee_id.'" readonly><br>';
}
else {
// error 404
}
}
Resume: the jquery function take the employee name and send to the controller who will look for the employee ID in the database. Then send an input text with default value (employee ID) as response and load this input in the form.
Good day!
How can I add a search on a dropdownlist?
I want a dropdown search like the Select2 widget.
Dropdownlist:
<?= $form->field($modelRis, "[{$i}]lib_item_item_id")->dropDownList(
ArrayHelper::map(LibItem::find()->orderBy('item_description')->all(), 'item_id', 'item_description'),
[
'prompt'=>'Select Item',
'onchange'=>'
var tmp = $(this).attr("id");
var thisId = tmp.split("-");
var tmp2 = "";
var tmp3 = "";
var sample_id = $(this).val();
$.post( "'.Yii::$app->urlManager->createUrl(['online-requisition/listsofunit?item_id=']).'"+$(this).val(),
function( data ) {
$( "#risrequesteditem-"+thisId[1]+"-lib_unit_id").html( data );
$( "#loop-"+thisId[1]+"-lib_item_item_id").val( sample_id );
tmp2 = data;
tmp3 = tmp2.split("=====");
$( "#loop-"+thisId[1]+"-available_stock").val( tmp3[1] );
});
',
'pluginOptions' => [
'allowClear' => true
],
])->label('Item',['class'=>'label-class']); ?>
I can't use the select2 widget because the 'onchange' or this line of code is not supported:
'onchange'=>'
var tmp = $(this).attr("id");
var thisId = tmp.split("-");
var tmp2 = "";
var tmp3 = "";
var sample_id = $(this).val();
$.post( "'.Yii::$app->urlManager->createUrl(['online-requisition/listsofunit?item_id=']).'"+$(this).val(),
function( data ) {
$( "#risrequesteditem-"+thisId[1]+"-lib_unit_id").html( data );
$( "#loop-"+thisId[1]+"-lib_item_item_id").val( sample_id );
tmp2 = data;
tmp3 = tmp2.split("=====");
$( "#loop-"+thisId[1]+"-available_stock").val( tmp3[1] );
});
',
Thanks...
Updates:
If i'm going to used the select2 widget in order to have a search function during the selection of items there will be a problem.
In the :
first selection its working:
And the onchange function has been working also. And automatically fill all the data in form field (Item no, Unit and StockAvailable) after the selection of item.
1st Selection
second selection is not working:
But I can select an item. Only the jquery function onchange is the problem...
2nd Selection
Thanks...
As suggested by Ajith above, you should use the Yii2 Select2 Widget from http://demos.krajee.com/widget-details/select2
If you go through the details you will find that the above widget does allow you to add event handlers by using the pluginEvents parameter settings of the widget.
pluginEvents = [
"change" => "function() { log('change'); }",
"select2:opening" => "function() { log('select2:opening'); }",
"select2:open" => "function() { log('open'); }",
"select2:closing" => "function() { log('close'); }",
"select2:close" => "function() { log('close'); }",
"select2:selecting" => "function() { log('selecting'); }",
"select2:select" => "function() { log('select'); }",
"select2:unselecting" => "function() { log('unselecting'); }",
"select2:unselect" => "function() { log('unselect'); }"
];
Although it's not possible to provide proper code without knowing the context etc of your code snippet, however it can be re-written using Yii2 Select2 widget as below (the code below is untested, but should give you an idea of the structure):
use kartik\widgets\Select2;
$data = ArrayHelper::map(LibItem::find()->orderBy('item_description')->all(), 'item_id', 'item_description');
// Usage with ActiveForm and model
echo $form->field($modelRis, "[{$i}]lib_item_item_id")->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Select Item'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => 'function(e) {
var tmp = e.target.id;
var thisId = tmp.split("-");
var tmp2 = "";
var tmp3 = "";
var sample_id = e.target.value;
$.post( "'.Yii::$app->urlManager->createUrl(['online-requisition/listsofunit?item_id=']).'"+$(this).val(),
function( data ) {
$( "#risrequesteditem-"+thisId[1]+"-lib_unit_id").html( data );
$( "#loop-"+thisId[1]+"-lib_item_item_id").val( sample_id );
tmp2 = data;
tmp3 = tmp2.split("=====");
$( "#loop-"+thisId[1]+"-available_stock").val( tmp3[1] );
});
}
'
],
]);
Please note I have used select2:select as the event handler.
I had to provide this as a separate answer because I don't have enough reputation to add a comment.
You can use yii2 select2 widget for this purpose. There is good documentation with demos available at
http://demos.krajee.com/widget-details/select2
An example usage with active form is given below
// Usage with ActiveForm and model
echo $form->field($model, 'state_1')->widget(Select2::classname(), [
'data' => $data,// the select option data items.The array keys are option values, and the array values are the corresponding option labels
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'change' => 'function(){// write your on change code here}'
]
]);