Update / post database colum in Laravel - laravel-4

I have a general question.
I have a search form in larvel which returns results form the database.
in these i have an input field to enter a price if price is == 0
what my problem is when i enter price and submit it returns to the search page without my previous search results i.e it doesn't refresh the same page with results and the newly updated field etc.
form in view
{{ Form::open(['action' => 'price_input'])->with($gyms) }}
{{ Form::text('enter_price', null, ['class' => 'form-control', 'size' => '50', 'id' => 'enter_price', 'autocomplete' => 'on', 'runat' => 'server', 'required' => 'required', 'placeholder' => 'enter price!', 'style' => 'margin-bottom: 0px!important;']) }}
{{ Form::submit('Search', ['class' => 'btn btn- primary', 'style' => 'margin-left: 10px;']) }}
{{ Form::close() }}
route
Route::post('/', [ //not used yet
'as' => 'price_input',
'uses' => 'PagesController#priceUpdate'
]);
Model
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
return Redirect::back()->withInput();
}
Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gym);
}
not bothering with model as that works fine.
any ideas guys?
Thanks for your answer,
i have changed my controller to this
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
but when i run it i get
Missing argument 1 for PagesController::priceUpdate()
with the $gyms being passed into the method.
if i take out the $gyms that goes away but not sure if its still being passed with session or not, sorry im a novice.
orignally i had a search box which when run returns
return View::make('pages.home')->with($data);
what is the difference between that and
return View::make('pages.home')->with($data);
when i do the above line it returns to the search page with no search options from before update the form, any ideas?

Currently, you are just retrieving an existing session and doing nothing with it. You need to do:
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
Or
return Redirect::to('pages.home')->with('gyms', Session::get('gyms'));
Then you can access the gyms in the view with $gyms.
Alternatively, you could access Session::get('gyms') in the view as well.
Also, not sure if it's just the way you pasted it here, but you have an unnecessary space before the ->with. Just wanted to make sure that's not part of the issue, too!

Related

Validate Select2 in Yii2 via AJAX

I have Yii2 application which uses the Kartik plugin to initialize Select2 dropdowns in forms.
I have one particular Select2 which uses AJAX call to get the data for the drop down options.
<?=
$form->field($model, 'court_house_id', ['enableAjaxValidation' => true, 'selectors' => ['input' => '#' . $id . "-court-house"],'template' => FormHelper::GenerateFieldTemplate([6])])
->widget(Select2::classname(), [
'options' => ['id' => $id . "-court-house", 'placeholder' => Yii::t('app', 'Search court house...')],
'hashVarLoadPosition' => \yii\web\View::POS_READY,
'pluginOptions' => [
'dropdownParent' => new JsExpression("$('#$modalWindowId')"),
'allowClear' => true,
'minimumInputLength' => 2,
'language' => [
'errorLoading' => new JsExpression("function () { return '" . Yii::t('app', 'Search...') . "'; }"),
],
'ajax' => [
'url' => app\components\UrlMaker::link('data/court-house-list'),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(courthouse) { return courthouse.text; }'),
'templateSelection' => new JsExpression('function (courthouse) { return courthouse.text;}'),
]])
->label(Yii::t('app', 'Court House'), ['class' => FormHelper::GenerateLabelClassTemplate([3])]);
?>
Intentionally pasting all of the code, although most of it is irrelevant I would assume.
I have this loaded in multiple dynamically created forms thus all the strange ids and selectors. However, the form has different dropdown which controls whether some of the fields are shown (and required) or not. This particular field above is only shown in one of the scenarios which all the other variations of the form do not have it. So the model has the following validation:
[['court_house_id', 'staff'], 'required', 'on' => self::SCENARIO_ONE],
By the way staff is just a regular text field and everything works for it.
In order to change the scenario, I have the following line in the view with the form:
<?php $model->scenario = \app\models\MyModel::SCENARIO_ONE; ?>
The problem is that when I submit the form empty, the staff field gets marked in red as invalid but the court house is marked in green as valid although it is empty.
If I go into the model and remove the 'on' => self::SCENARIO_ONE part then everything works as expected - on empty submit the court house field also lights up in red but that would be a problem for the rest of my scenarios where this field is not needed.
Any ideas what might be causing the problem and how to resolve it?
Try to set the scenario in controller before calling save() method, for example
$model = new MyModel(['scenario' => MyModel::SCENARIO_ONE])

Laravel 5.1, optional parameter causing blank page

The concerning route:
Route::patch('admin/track/practice/{practice_id}/close-practice-session/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
new is an optional route parameter.
The Controller method:
public function closePracticeSession($club, $practice_id, $session_id, $new = null)
{
$clubDetails = new ClubDetails();
$club_id = $clubDetails->getClubID($club);
date_default_timezone_set(config('app.timezone'));
$CurrentTime = date("Y-m-d H:i:s");
try
{
DB::table('practice_sessions')
->where('id', $session_id)
->where('club_id', $club_id)
->update(['is_current' => 0, 'updated_at' => $CurrentTime]);
if ($new == 'Y')
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id]);
}
else
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id, $session_id])
->with(array('success'=>'Practice was successfully closed.'));
}
}
catch(\Exception $e)
{
return view('errors.500')->with(self::getRequiredData($club))->with('error', $e->getMessage());
}
}
I have two forms on my view, one has the optional parameter, one doesn't.
When I click on the button on the form which has the optional parameter, I am getting a BLANK screen.
Here are some strange things:
No error message. Checked the laravel.log
Even if I remove all the logic from the controller method and do a
simple var_dump, I still get a blank screen
When I click on the button without the optional parameter, it
behaves as expected
I have been trying for the last two days to resolve this without any luck. I have even tried to make the {new} parameter mandatory. Anytime I am passing the last parameter, I am getting a blank screen.
Any idea? I am sure I am doing something silly. Just can't see it.
Update (the two forms on the view) - the csrf token is in the header.
{!! Form::open([
'method' => 'PATCH',
'route' => ['close-practice-session', $alias, $practiceDetails[0]->practice_id, $practiceDetails[0]->id]
]) !!}
{!! Form::submit('Close Session', ['class' => 'btn btn-primary btn-sm', 'style' => 'width: 160px;margin-left: 0px!important']) !!}
{!! Form::close() !!}
<!-- #2 -->
{!! Form::open([
'method' => 'PATCH',
'route' => ['close-practice-session', $alias, $practiceDetails[0]->practice_id, $practiceDetails[0]->id, "Y"]
]) !!}
{!! Form::submit('Close + Create New', ['class' => 'btn btn-secondary btn-sm', 'style' => 'width: 160px;margin-left: 0px!important']) !!}
{!! Form::close() !!}
As per your route
Route::patch('admin/track/practice/{practice_id}/close-practice-session/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
Your controller function should be like this
public function closePracticeSession(Request $request, $practice_id, $session_id, $new = null)
{
$clubDetails = new ClubDetails();
$club_id = $clubDetails->getClubID($club);
date_default_timezone_set(config('app.timezone'));
$CurrentTime = date("Y-m-d H:i:s");
try
{
DB::table('practice_sessions')
->where('id', $session_id)
->where('club_id', $club_id)
->update(['is_current' => 0, 'updated_at' => $CurrentTime]);
if ($new == 'Y')
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id]);
}
else
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id, $session_id])
->with(array('success'=>'Practice was successfully closed.'));
}
}
catch(\Exception $e)
{
return view('errors.500')->with(self::getRequiredData($club))->with('error', $e->getMessage());
}
}
Please take a look at this SO post. This gave me a hint to solve my problem. I had an identical GET route in my routes.php file. Once I modified my PATCH route to the following, everything is working as expected.
Route::patch('admin/close-practice-session/{practice_id}/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));

Laravel - HasMany CRUD - Update

I need some help, please,
I have two tables: carriers and sell
Carrier CRUD is working. Sell CRUD is also working, except Update method.
In order to update, i need carrierId and sell id, right?
This is my CarrierSellController:
And this is my carriers/sell/edit.blade.php
The model binding is working:
Form action has /edit at the end of the url. It's oke?
If i hit submit button, i get this error:
Try this one
{!! Form::model($sell,['url'=>url('carriers/'.$sell->carrier->id.'/sell/'.$sell->id),'method'=>'patch']) !!}
and in the Sell model add
public function carrier()
{
return $this->belongsTo(Carrier::class);
}
make sure the method is PUT
add this to your form
{{ method_field('put') }}
Why don't you if you want to be absolutely sure just try declaring the route yourself like:
Route::put('carriers/{carrierId}/sell/{id}', [ 'as' => 'carriers.sell.update', 'uses' => 'CarrierSellController#update' ]);
And then in your view have this:
{!! Form::model($sell, ['method' => 'PUT', 'route' => ['carriers.sell.update', 'carrierId' => $sell->carrier->id, 'id' => $sell->id]) !!}

Laravel parsing Input from a multiple select box not working

This is my pubf in my Controller which handles the request:
public function addPermissionsToRoleHandler($rid, Request $request)
{
$role = Role::find($rid);
dd($request->permissions);
foreach($request->permissions as $perm)
{
$permission = Permission::find($perm->id);
$role->attachPermission($permission);
}
return redirect()->route('showSpecificRole', $rid);
}
This is how I defined my multiple select-box:
{!! Form::select('permissions[]', $permissions, null, array('class' => 'selectpicker show-tick', 'data-live-search' => 'true', 'id' => 'permission_select', 'multiple' => true)) !!}
Why is my dd() returning null? $request->permission is empty. dd($request) only has token_.
I don't have the rep to comment so am posting as an answer. I am not sure, but I think it may be because the Request needs to be the first argument ?

Get the model ID when updating a resource

I have a form that will submit a Patch request to the controller's update method.
But the update method requires to have $id, as you can see below whenever I try that I get a
No query results for model [Item]. Since the update method did not receive the $id of the model
public function update($id)
{
$item = Item::findOrFail($id);
$update = Input::all();
// some codes to save changes
return Redirect::route('items.index');
}
Another thing is that whenever I submit the form, url turns into something like this:
mw.dev/items/%7Bitems%7D
Edit
routes.php
Route::resource('items','ItemsController');
ItemController
public function edit($id)
{
$item = Item::findOrFail($id);
return View::make('items.edit')->with('item',$item);
}
I have included the code on my edit.blade.php
{{Form::open(array('route' => 'items.update', 'method'=>'patch'))}}
{{Form::text('barcode', $item->barcode, array('placeholder' => 'barcode'))}}
{{Form::text('imei',$item->imei, array('placeholder' => 'imei'))}}
{{Form::text('item_name', $item->item_name, array('placeholder' => 'item name'))}}
{{Form::submit('edit')}}
{{Form::close()}}
You have to pass the model to your view and need to pass the id parameter when generating the form. Assume that you have a User model and it's available in the view. So you may generate the form action using something like this:
// Using Form::open method with route
Form::open(array('route' => array('route.name', $user->id)))
// Using Form::model method with route
Form::model($user, array('route' => array('route.name', $user->id), 'method' => 'patch'))
// Using Form::open method with action
Form::open(array('action' => array('Controller#update', $user->id), 'method' => 'patch'))
// Using Form::open method with url
Form::open(array('url' => 'something/update/' . $user->id, 'method' => 'patch'))
Check more on Opening A Form.
The URL
mw.dev/items/%7Bitems%7D
is most likely the url-encoded form of
mw.dev/items/{items}
I suppose there is a problem in the form submission or in the <form>'s action paremeter or in the Route::* declaration in routes.php.
This could also explain why you don't get any $id upon submission.

Resources