I have a show action where I show the directions like this:
= gmaps({"direction" => { "data" => { "from" => "#{#ride.latitude},#{#ride.longitude}", "to" => "#{#ride.spot.latitude},#{#ride.spot.longitude}" } }})
I want the user to edit the model and update the directions via javascript.
so i have a coffe script here that looks like this:
$('#ride_address').autocomplete {
select: (event,ui) ->
Gmaps.map.direction_conf.destination = "#{spot_lat},#{spot_lng}"
Gmaps.map.direction_conf.origin = "#{ride_lat},#{ride_lng}"
Gmaps.map.create_direction()
}
now the new directions are rendered on the map,
BUT on TOP of the existing directions.
how can i delete the previous directions first?
Related
i have function in my controller that create a forecast :
public function updateOrCreate(Request $request, $subdomain, $uuid)
{
$fixture = Fixture::where('uuid',$uuid)->firstOrFail();
request()->validate([
'local_team_score' => 'integer|min:0',
'visitor_team_score' => 'integer|min:0',
'winner_team_id' => 'integer|nullable'
]);
if ($fixture->status !== "PENDING"){
return response()->json([
'message' => "You can not add or modify a forecast if the fixture is not pending"
], 403);
}
$winner_team = null;
// local team win
if ($request->local_team_score > $request->visitor_team_score) {
$winner_team = $fixture->localTeam;
}elseif ($request->local_team_score < $request->visitor_team_score){ //visitor win
$winner_team = $fixture->visitorTeam;
}else{ // draw
$winner_team = FixtureTeam::where('team_id',$request->winner_team_id)->first();
}
$user = auth('api')->user();
$platform = Platform::first();
$forecast = Forecast::updateOrCreate([
'user_id' => $user->id,
'fixture_id' => $fixture->id,
'platform_id' => $platform->id
],[
'local_team_score' => $request->local_team_score,
'visitor_team_score' => $request->visitor_team_score,
'winner_team_id' => is_null($winner_team) ? null : $winner_team->team_id
]);
$forecast->load('winnerTeam');
return new ForecastResource($forecast);
}
As you can see i use updateOrCreate methods to add or update a forecast.
The problem is when 2 requests from the same user run at the same time (and no forecast is already created) 2 row are inserted.
Do you have a solution ?
I See that the problem is not new but i could not find a solution https://github.com/laravel/framework/issues/19372
updateOrCreate does 2 steps:
tries to fetch the record
depending on the outcome does an update or a create.
This operation is not atomic, meaning that between step 1 and 2 another process could create the record and you would end up with duplicates (your situation).
To solve your problem you need following:
determine what columns would give the uniqueness of the record and add an unique index (probably compound between user_id, fixture_id, platform_id)
you need to let database handle the upsert (ON DUPLICATE KEY UPDATE in MySQL, ON CONFLICT (...) DO UPDATE SET in Postgres, etc). This can be achieved in Laravel by using the upsert(array $values, $uniqueBy, $update = null) instead of updateOrCreate.
This is the controller code:
$player1QID = time().'.'.$request->player1_Id->extension();
$images1= $request->player1_Id->move(public_path('images'), $player1QID);
$player2QID = time().'.'.$request->player2_Id->extension();
$images2= $request->player2_Id->move(public_path('images'), $player2QID);
///this is adding to database:
$registeredusers = Registrations::create([
'tournament_id' => $request->input('tournament_id'),
'player1_name' => $request->input('player1_name'),
'player1_email' => $request->input('player1_email'),
'player1_Id' => $player1QID,
'player1_gender' => $request->player1_gender,
'player1_phone' => $request->input('player1_phone'),
'player2_name' => $request->input('player2_name'),
'player2_email' => $request->input('player2_email'),
'player2_Id' => $player2QID,
'player2_gender' => $request->player2_gender,
'player2_phone' => $request->input('player2_phone'),
'category' => $request->category,
'status' => $request->input('status'),
]);
This is in view blade:
Upload image1
Upload image2
Really appreciate if someone can help
you should first look at your inspection in Chrome, Firefox or whatever you are using, and check what your request contains, I mean if you are sending the images in separate names like:
...
player1_Id:
player2_Id:
...
i think, of course is sending like that because you are receiving it on your controller. Then try save it with datetime at end of name like:
public function obtainImage(Request $request){
$image1=request('player1_Id');
$this->manageImage($image1);
$image2=request('player2_Id');
$this->manageImage($image2);
}
public function manageImage($image){
$fileImageNameExtencion=$image->getClientOriginalName();
$fileName=pathInfo($fileImageNameExtencion, PATHINFO_FILENAME);
$fileExtencion=$image->getClientOriginalExtension();
$newFileName=$fileName."_".time().".".$fileExtencion;
$saveAs=$image->storeAs('public/images',$newFileName);
return $newFileName;
}
where $ newFileName is what you need to save to your database
otherwise you can do a dd ($ player1QID. '-'. $ player2QID) before saving to database and comparing names
I am trying to cleanup and optimize my come I am running on podio's API. What I am currently doing is using the filter query to return a collection from one app. I then loop over that collection. On each item I use Podio get_field_value to return the value(s) of a field in a referenced app. This creates a lot of API calls. I would like to retrieve everything in one API call Here is a simple version of my current code:
$collection = PodioItem::filter(WHSE_ID, array(
"filters" => array(
WHSE_EQUP_STATUS => array(2),
),
"sort_by" => WHSE_LOAD_IN,
"sort_desc" => false,
"limit" => 50
)
);
foreach ($collection as $item) {
// Table-A ID
$whId = $item->item_id;
// Referenced App Item(s)
$nucId = $item->fields[0]->values[0]->item_id;
// Get Referenced App Item Field
$app_b_value = PodioItem::get_field_value($nucId, NUC_LOAD_OUT);
echo $app_b_value;
}
Is there a more efficient way of doing this? I am thinking inline with the way you would use JOIN in a mysql query.
Thank you for any help you can provide!
if you are trying to get value from each item from filtered collection, you don't need to make podio calls each time.
Podio filter call will give you item with values. you just have to get value from each item.
like following
foreach ($podioFilterData['items'] as $itemData) {
$itemFields = $itemData['fields'];
foreach ($itemFields as $field) {
$value = $field['values'][0];
}
}
I am running into a little snag with combining extensions "EchMultiSelect" and "MultiModelForm" of YII framework.
What I'm trying to do is copy a set of form elements one of which elements is an EchMultiSelect widget.
According to tutorial on the jqRelCopy page, I would need to pass a copy of the element (datePicker in their example) to the 'jsAfterNewId' option:
'jsAfterNewId' => JQRelcopy::afterNewIdDatePicker($datePickerConfig),
So, I tried to modify that to:
'jsAfterNewId' => MultiModelForm::afterNewIdMultiSelect($memberFormConfig['elements']),
Where I also added the following to MultiModelForm.php:
public static function afterNewIdMultiSelect($element)
{
$options = isset($element['options']) ? $element['options'] : array();
$jsOptions = CJavaScript::encode($options);
return "if(this.attr('multiple')=='multiple'){this.multiselect(jQuery.extend({$jsOptions}));};";
}
its copied and working properly when i am using Add Person link but what happens if i am adding/cloning three items for example and when i change the third item multiselct option then its reflecting to the first multiselect dropdown only this is same for other as well also when i am adding new items by clicking on the Add Person link then its cloning the same element to the new row item
here is the code for the form configuration variables and multimodel widget call.
//$userList=array of the userIds from users table
$memberFormConfig = array(
'elements'=>array(
'userId'=>array(
'type'=>'ext.EchMultiSelect.EchMultiSelect',
'model' => $User,
'dropDownAttribute' => 'userId',
'data' => $userList,
'dropDownHtmlOptions'=> array(
'style'=>'width:500px;',
),
),
...
...
));
calling the MultiModelForm widget from the same view file
$this->widget('ext.multimodelform.MultiModelForm',array(
'id' => 'id_member', //the unique widget id
'formConfig' => $memberFormConfig, //the form configuration array
'model' => $model, //instance of the form model
'tableView' => true,
'validatedItems' => $validatedMembers,
'data' => Person::model()->findAll('userId=:userId', array(':userId'=>$model->id)),
'addItemText' => 'Add Person',
'showAddItemOnError' => false, //not allow add items when in validation error mode (default = true)
'fieldsetWrapper' => array('tag' => 'div',
'htmlOptions' => array('class' => 'view','style'=>'position:relative;background:#EFEFEF;')
),
'removeLinkWrapper' => array('tag' => 'div',
'htmlOptions' => array('style'=>'position:absolute; top:1em; right:1em;')
),
'jsAfterNewId' => MultiModelForm::afterNewIdMultiSelect($memberFormConfig['elements']),
));
Can someone help me with this please?
Thanks in advance!
After a long searching and googleing i found the solution for this, just replace the function in your MultiModelForm.php:
public static function afterNewIdMultiSelect($element)
{
$options = isset($element['options']) ? $element['options'] : array();
$jsOptions = CJavaScript::encode($options);
return "if ( this.hasClass('test123456') )
{
var mmfComboBoxParent = this.parent();
// cloning autocomplete and select elements (without data and events)
var mmfComboBoxClone = this.clone();
var mmfComboSelectClone = this.prev().clone();
// removing old combobox
mmfComboBoxParent.empty();
// addind new cloden elements ()
mmfComboBoxParent.append(mmfComboSelectClone);
mmfComboBoxParent.append(mmfComboBoxClone);
// re-init autocomplete with default options
mmfComboBoxClone.multiselect(jQuery.extend({$jsOptions}));
}";
}
Thats It....!!
Thanks...!!!
I'm trying to optimize an NHibernate query:
var profile = dc.Profiles.FirstOrDefault(p => p.IdProfile == idProfile);
I would like it to load a collection of Rights. I did this:
var profile = dc.Profiles.Fetch(x => x.Rights).FirstOrDefault(p => p.IdProfile == idProfile);
The results were totally different from what I expected - instead of getting single Profile with rights I got single profile with single right!
How can I fix it?
You can use like this
var profile = dc.Profiles.Where(p => p.IdProfile == idProfile).Select(x => x.Rights);