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
Related
I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}
I have a Customer fiels that is dependent on a Project field.
In my form, I have a dropdown for project, and I need my second dropdown of customers to change dynamically according to the project.
I find the solution in a few places on the web, but the array doesn't change.
Can anyone help with this?
My form:
$dataProject=ArrayHelper::map(Project::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'project_id')->dropDownList($dataProject,
['prompt'=>'-Choose a Project-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('customer/lists?id=').'"+$(this).val(), function( data ) {
$( "select#title" ).html( data );
});
']);
$dataPost=ArrayHelper::map(Customer::find()->asArray()->all(), 'id', 'first_name');
echo $form->field($model, 'customer_id')
->dropDownList(
$dataPost,
['id'=>'title']
);
Code in the Customer controller:
public function actionLists($id) {
$countPosts = Customer::find()
->where(['project_id' => $id])
->count();
$posts = Customer::find()
->where(['project_id' => $id])
->orderBy('id DESC')
->all();
if($countPosts>0) {
foreach($posts as $post){
echo "<option value='".$post->id."'>".$post->first_name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
So far the best way to add the dropdown options to the select when you have the access to jquery is to use .each() but you need to provide the options from the controller/action as json rather than creating the html and then adding the html to the dropdown.
Then you are using $.post and adding query string with the url for the id whereas you can use the data option to send the id.
Change your onchange function to the following
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('/customer/lists').'", {id:$(this).val()},function( data ) {
//this will clear the dropdown of the previous options
$("#title").children("option").remove();
//optionally you can use the following if you have a placeholder in the dropdown so that the first option is not removed
//$("#title").children("option:not(:first)").remove();
$.each(data, function(key, value) {
$("#title")
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
Then you are querying 2 times to the Customer table once for count all records and one for all the lists of customers
$countPosts = Customer::find()
->where(['project_id' => $id])
->count();
$posts = Customer::find()
->where(['project_id' => $id])
->orderBy('id DESC')
->all();
you can simply query for the customers and use php:count() function on the result set $posts to count the total number of records.
$posts = Customer::find()
->where(['project_id' => $id])
->orderBy('id DESC')
->all();
$countPosts = count($post);
But we are not going to need the count anyway this was just for information, change your action actionLists() to below and remove the parameter $id now as we are sending the id with post.
public function actionLists() {
//set the response format to JSON
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//get the id
$id = Yii::$app->request->post ( 'id' );
$posts = Customer::find ()
->where ( [ 'project_id' => $id ] )
->orderBy ( 'id DESC' )
->all ();
return ArrayHelper::map ( $posts , 'id' , 'first_name' );
}
Apart from doing all the above you should get used to of using available resources in form of extensions or plugins that are widely available one of them is Kartik/DepDropdown which does the same thing with a lot of less pain of writing the javascript and just providing data from server-side.
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
}
});
});
I'm trying to include a csv exporter in my application, And i used https://github.com/FriendsOfCake/cakephp-csvview.
It works fine on my local machine but for some reason it doesn't work on my server. It throws me View class "CsvView.csv" is missing. error. Is there a way to fix this issue?
Here's my controller for reference
public function export() {
$this->response->download('export.csv');
// $opts1['order'] = array('Blogs.created' => 'desc');
// $blogsinfos = $this->Blogs->find('all',$opts1);
$opts1['order'] = array('Incomes.title' => 'desc');
$data = $this->Incomes->find('all',$opts1)->toArray();
$_serialize = 'data';
// Give the needed the colums to extract
$_extract = ['id', 'title' ,'description' , 'created' , 'amount'];
//headings for the CSV
$_header = ['ID', 'Title' ,'Description' , 'Created' , 'Amount'];
$this->set(compact('data', '_serialize', '_header', '_extract'));
$this->viewBuilder()->className('CsvView.csv');
return;
}
Code to create the downloadable link.
<?= $this->Html->link('Monthly Report', [
'controller' => 'incomes',
'action' => 'export',
'_ext' => 'csv'
],
['class' => 'btn btn-success'])
?>
I'm using CakePHP 3.4.7.
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}'
]
]);