Yii2 call 2 functions on change of a dropdown - ajax

I have several dropdown imputs and on change of any of them I wanna a value to be offered for a textbox.
I have a code that i placed on each of my dropdown's and it works perfect for me:
<?= $form->field($model4, 'prevoditelj')->dropDownList(ArrayHelper::map(
\app\models\Prevoditelj::find()->orderBy('idprevoditelj')->asArray()->all(),
'idprevoditelj',
'naziv'
),['onchange'=>'
$.get( "'.Url::base().'/index.php?r=zadatak/trosak&id='.$model->projekt.'_"+$("#'.Html::getInputId($model3, 'usluga').'").val()+"_"+$("#'.Html::getInputId($model3, 'dodatak').'").val()+"_"+$("#'.Html::getInputId($model3, 'obr_jedinica').'").val()+"_"+$("#'.Html::getInputId($model4, 'prevoditelj').'").val(), function( data ) {
$( "#'.Html::getInputId($model, 'trosak').'" ).val( data );
});
']) ?>
in a controller I have:
public function actionCijena($id){
$sve=explode("_",$id);//0 - projekt_id, 1 - usluga, 2 - dodatak/jez_kombinacija, 3 - obr_jedinica
$projekt = Projekt::findone($sve[0]);
$klijent = Klijent::findone($projekt['klijent']);
$cjenik_klijent = CjenikKlijent::find()
->asArray()
->where('klijent = :id and usluga = :usluga_id and obr_jedinica = :obr_jedinica and jez_kombinacija = :jez_kombinacija and valuta = :valuta',
['id'=>$klijent['idklijent'],'usluga_id'=>$sve[1],'obr_jedinica'=>$sve[3],'jez_kombinacija'=>$sve[2],'valuta'=>$klijent['valuta']])
->all();
//ako nema, gledaj opci cjenik
if($cjenik_klijent==array()){
$cjenik_klijent = CjenikOpci::find()
->asArray()
->where('usluga = :usluga_id and obr_jedinica = :obr_jedinica and jez_kombinacija = :jez_kombinacija and valuta = :valuta',
['usluga_id'=>$sve[1],'obr_jedinica'=>$sve[3],'jez_kombinacija'=>$sve[2],'valuta'=>$klijent['valuta']])
->all();
}
return $cjenik_klijent[0]['cijena'];
}
The problem I have is that now I wanna add another calculated value to another textbox. but it needs to trigger on the same dropdown's. Unfortunately Get can't return an array so I need to split it up into 2 functions, but how do I call 2 of them?

Ok, I managed to find a solution in returning 2 values in 1 string and then exploding them in jquery. Don't know why I didn't think of that sooner.

Related

Modify single Item of Laravel Collection without mapping every single item

I loop trough an eloquent Collection and I want to add the data to another Collection called "$tagCollection". If an entry with the same tag_id already exists I only want to increase the rating-column for the existing entry.
At the moment it looks like this. Has anyone an Idea?
$tagCollection = collect();
$entries->each(function($entry) use($tagCollection){
$tagId = $entry->tag_id;
//something like this
if($tagCollection->contains('tag_id', $tagId)){
$tagCollection->update ('rating' => $oldRating + 0.5)
} else{
$tagCollection->push(array(
'tag_id' => $tagId,
'rating' => 0.35
));
}
});
I also tried to use ->pull() to remove the Item out of the Collection and then push it again with the new rating but I also do not know how
Can you do it with array instead of collection? For example:
$tagArray = [];
$entries->each(function ($entry) use (&$tagArray) {
if (isset($tagArray[$entry['tag_id']])) {
$tagArray[$entry['tag_id']] += 0.5;
} else {
$tagArray[$entry['tag_id']] = 0.35;
}
});
If the end goal is to update all the entries present in $entries that belong to a specific $tagId, then you can do this
$entryIds = $entries->where('tag_id',$tagId)->pluck('id')->toArray();
Entry::whereIn('id', $entryIds)->update(['rating' => \DB::raw('rating + 0.5')]);
And thats it.

Setting repeater values from database

I have this code
$w("#repeater1").forEachItem( ($item, itemData, index) => {
$item("#image2").src = reviews[count].ReviewerImage;
$item("#text17").text = reviews[count].ReviewerComment;
$item("#text28").text = reviews[count].ReviewerNickname;
$item("#ratingsDisplay1").value = reviews[count].ReviewerRating;
count++;
} );
When this runs, it updates the information in the repeater based on the information in the array reviews. The nickname, comment, and image all are being displayed correctly, but the ratings on the repeater are not updating with the rest of the data. I have tried console logging the 'reviews[count].ReviewerRating' which outputs a value of 5 for each item, but when the page loads, it the ratings display only shows 3 stars. Is there an event I need to trigger to update the reviews?
$w("#repeater1").forEachItem( ($item, itemData, index) => {
$item("#image2").src = reviews[count].ReviewerImage;
$item("#text17").text = reviews[count].ReviewerComment;
$item("#text28").text = reviews[count].ReviewerNickname;
$item("#ratingsDisplay1").rating= reviews[count].ReviewerRating;
count++;
} );
Had to set the ratings display with .rating instead of .value

Gravity Forms: Multi-Page Form Validation

I have a field 47 on Page 1 and a field 55 on Page 3 of a form. How do I create a gform_validation on Page 3 to prompt an error message when Field 47 < Field 55? The code below works for validation if both fields are on same page but it doesn't work for multi-page. Any idea plz?
Thanks!
// multi-page validation
add_filter( 'gform_validation', 'custom_validation' );
function custom_validation( $validation_result ) {
$form = $validation_result['form'];
// Financial Assets must be larger than Investment
if ( rgpost( 'input_47' ) < rgpost( 'input_55' ) ) {
// set the form validation to false
$validation_result['is_valid'] = false;
//finding Field with ID of 1 and marking it as failed validation
foreach( $form['fields'] as &$field ) {
//NOTE: replace 1 with the field you would like to validate
if ( $field->id == '34' ) {
$field->failed_validation = true;
$field->validation_message = 'Your Financial Assets (A) cannot be lower than your investment with us. Please fix the discrepancy.';
break;
}
}
}
//Assign modified $form object back to the validation result
$validation_result['form'] = $form;
return $validation_result;
}
I found the following information on their documentation however I'm not sure how to implement it inside the code above. Any clue? Thanks alot!
// 3 - Get the current page being validated
$current_page = rgpost( 'gform_source_page_number_' . $form['id'] ) ? rgpost( 'gform_source_page_number_' . $form['id'] ) : 1;
First, you can get the submitted page via the GFFormDisplay::get_source_page( $form_id ) method.
There are a few different ways this could be done. For simplicity, I would just bypass validation until your desired page is submitted. To do that, just add something like this:
if( GFFormDisplay::get_source_page( $form_id ) >= 3 ) {
return $validation_result;
}
...after this line:
$form = $validation_result['form'];
This would only run this validation on pages greater than page 3.

jquery datatable with ajax based pagination

I have javascript function that populates datatable using Ajax. My javascript code looks like :
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
My server side script in django has a function that loads around 500 data rows. Now the problem is that I don't want to load whole data at a time. Instead I want to have first 10 data rows. Then with pagination, another 10 rows like that.
I read the page server side processing documentation of datatables. I tried with "serverSide": true option as well. I am not understanding server side script. There is given an example of PHP. It seems that they are not using any parameters like draw, recordsFiltered, recordsTotal there. There they have used php SSP class. And it is unknown what does it do. I am trying to implement it in django.
But I am not finding proper good documentation to implement. Any help will be appreciated.
Old question but one I also had a surprisingly difficult time finding an answer to, so in case anyone else ends up here... :P
I found this 2020 article very helpful, specifically part 6 showing the "complete code" that includes getting the correct variables, building the SQL query, and how to build/structure the data object that it responds with:
https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
Their example posted below:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
Nice exemple:
https://datatables.net/examples/server_side/defer_loading.html
But you need edit server side.
Response demo
{
draw:2,
recordsFiltered:57,
recordsTotal:57
}

asp.net mvc 3 EF HTML MultiSelect - How to retrieve multiple values using LINQ

I have an Advanced Search form, It contains, input boxes, dropdown lists, etc. And now I want to change a dropdown list to a multiselect list.
I can set the view, like this:
#Html.ListBoxFor(model => model.IdState, null, new { size = "7" })
But I don't know how to change the controller from:
public ActionResult Index(FormData model)
{
IQueryable<mytable> results = from s in db.mytable.Include("State").where(s=> (model.IdState != null ? s.IdState == model.IdState : true)) select s;
return View(result);
}
To a multiple IdState Result???
Earlier the IdState was:
int IdState;
Now is:
IEnumerable<int> IdState;
Thanks for your time!
I still can't make it work. In SQL will be:
SELECT * FROM MyTable WHERE IdState IN (1,2,5,7,10)
Any Idea? The http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx Don't show similar situation
Workaround
I found on this discussion: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/ this code snippet:
IQueryable<Foo> foos = context.Foo.Where("it.Id in {1, 2, 3, ...}");
I changed to
string sState = "";
foreach (int a in model.IdState ) sState += (a.ToString() + ",");
sState = sState .Substring(0, sState .Length - 1);
IQueryable<mytable> results = from s in db.mytable.Where("it.IdState in {" + sState + "}");
And It works great!!!
I hope can find the final solution
Instead of
s.IdState == model.IdState
try using
model.IdState.Contains(s.IdState)

Resources