how to return to a specific page after form submit based on value laravel - laravel

i have a logic whereby on form submission i want to return to specific page based on a certain value the user choosed when submiting the form.the form works well but when i try to return it doesnt work.where might i be missing the point here.
public function addtoorder(Request $request){
$userid=Auth::user()->id;
$addresses=Deliveryaddress::where('user_id',$userid)->first();
if($request->isMethod('post')){
$data=$request->all();
$order = new Order();
$order->name = Auth::user()->name;
$order->phone =$addresses->phone;
$order->county =$addresses->shipcharges->county;
$order->town =$addresses->towns->town;
$order->order_status="New Order";
$order->payment_method = $request->payment_method;
$order->user_id =$userid;
$order->grand_total = Session::get('grand_total');
$order->shipping_charges=$addresses->shipping_cost;
$order->save();
}
if($data=="SKRILL"){
return view('frontend.product.skrill');
}elseif($data=="PAYPAL"){
return view('frontend.product.paypal');
}
}
}
i have been able to save the data on the database but am unable to return to the specific pages.rather it return to blank page without any error,but it saves the data to the orders table perfectly.

I guess blank screen means that nothing was returned, because you are trying to check whether $data(which is array) is equal to some string.
My thoughts would be for you to try check string in your if statement.
Like this
if($data['payment_method'] === "SKRILL"){
return view('frontend.product.skrill');
}elseif(data['payment_method'] === "PAYPAL"){
return view('frontend.product.paypal');
}

Related

laravel - how can I call a function stored in a controller after saving to a database?

I'm following a tutorial on Laravel, adding to a DB via a form. At the end of a function that saves to a DB, it returns back to the page where the form is, but I want to be taken to another page where the information is displayed. In the tutorial I created a controller with a function that returns a view containing all the database info - that element works fine however I can't seem to find a way of calling this function directly after saving to the database. I can also return any other view which just displays static view ( just html with no data handling ). Is what I'm trying to achieve possible?
public function store(){
$li = new \App\LTest1();
$li->creator = request('creator');
$li->title = request('title');
$li->views = request('views');
$li->save();
return back(); // this works
// return view('info'); // this works
//return ('Listings#showList'); this doesnt work = how do i call a function in a controller???
}
// routing
Route::get('info', function () {
return view('info'); // i can get to this static page from my store() function
});
Route::get('thedataviewpage', 'Listings#showList'); // you can route to this but not from the store() function
Redirect is the thing you need here
public function store() {
$li = new \App\LTest1();
$li->creator = request('creator');
$li->title = request('title');
$li->views = request('views');
$li->save();
return redirect('info'); // Redirect to the info route
}
Take this example. Be sure to add the proper route name and a proper message.
return redirect()->route('put here the route name')->with('success', 'Created.');'
to return to a controller action just use
return redirect()->action('Listings#showList');
or you can use route to call that controller action
return redirect('/thedataviewpage');

Yii2 validation on controller action

I am developing a Yii 2.0 application in which users can create orders then send the orders to review and after that it follows a number of stages in the workflow.
Everything is ok until yesterday that the customer ask for the possibility that before sending the orders to review the order are considered as draft. Which means I have to turn off validations on create and validate them when users clicks Send To Review button. I know Yii 2.0 supports scenarios but maybe scenarios doesn't apply to this because the Send To Review button is shown in a readonly view. This forces me to do validation inside the controller action because there is no send_to_review view. How can this be done (I mean model validation inside controller action)?
Here is the controller action code
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
What I need to solve is the TODO.
Option 1: Showing validation errors in the same view and the user has to clic Update button change the requested values save and then try to Send To Review again.
Option 2: Redirecting automatically to update view already setting scenario and validation errors found in the controller.
Thanks,
Best Regards
You can use $model ->validate()for validation in controller.
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
//optional
$model->scenario=//put here the scenario for validation;
//if everything is validated as per scenario
if($model ->validate())
{
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
return $this->render('update', [
'model' => $model,
]);
}
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
If you don't need validation in actionCreate().Create a scenario for not validating any field and apply there.

Loading page dynamically from database via id in controller

I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)

View Same user_id

//Anyone can help to create a view data with same id? it is a multiple viewing.
this is my Controller. i dont khow apply in Model and View
function Get_Pitch($id){
$this->load->model('users_model');
$data['query'] = $id;
$this->load->view('view_pitch', $data);
}
Example this is my url "http://localhost/SMS_System/home/sample/102"
in my database is
id=1 name=erwin user_id=102
id=2 name=flores user_id=102
id=3 name=sample user_id=202
how to view the same user_id?
First of all with what you've supplied your URL won't work, you aren't following the normal conventions for CI so it won't know where to look. I am assuming your controller is called sample then you need to tell the application which function you're calling in that controller, finally URL names should be lower case so I changed that, so your URL should read:
"http://localhost/SMS_System/home/sample/get_pitch/102"
Also you need to get your data from a model, you loaded the model then didn't use it. The line after loading the model calls a function from that model and passes it the id you got from your url. Notice the if not isset on the id, this ensures that if someone goes to that page without the id segment there are no errors thrown from the model having a missing parameter, it will just return nothing, that is handled in the view.
Controller:
function get_pitch($id){
//the following line gets the id based on the segment it's in in the URL
$id=$this->uri_segment(3);
if(!isset($id))
{
$id = 0;
}
$this->load->model('users_model');
$data['query'] = $this->users_model->getUserData($id);
$this->load->view('view_pitch', $data);
}
Your model takes the id passed from the controller and uses that to retrieve the data from the database. I normally create the array I am going to return as an empty array and handle that in the view, this makes sure you get no errors if the query fails. The data then returns to the controller in the last line and is passed to the view in your load view call.
Model:
function getUserData($id)
{
$this->db->where('id',$id);
$result = $this->db->get('users') //assuming the table is named users
$data = array(); //create empty array so we aren't returning nothing if the query fails
if ($result->num_rows()==1) //only return data if we get only one result
{
$data = $result->result_array();
}
return $data;
}
Your view then takes the data it received from the model via the controller and displays it if present, if the data is not present it displays an error stating the user does not exist.
View:
if(isset($query['id']))
{
echo $query['id']; //the variable is the array we created inside the $data variable in the controller.
echo $query['name'];
echo $query['user_id'];
} else {
echo 'That user does not exist';
}

CodeIgniter - showing original URL of index function?

I'm not sure if I'm approaching this fundamentally wrong or if I'm just missing something.
I have a controller and within it an index function that is, obviously, the default loaded when that controller is called:
function index($showMessage = false) {
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$data['showMessage'] = $showMessage;
$this->load->view('main', $data);
}
I have another function within that controller that does a bulk update. After the updates are complete, I want the original page to show again with the message showing, so I tried this:
/**
* Will save all employee information and return to the call sheet page
*/
function bulkSave() {
//update each employee
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$success = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
$this->index($success);
}
What is happening is that the original page is accessed using:
localhost/myApp/myController
after the bulk update it is showing as:
localhost/myApp/myController/bulkSave
when I really want it to show the url as the index page again, meaning that the user never really sees the /bulkSave portion of the URL. This would also mean that if the user were to refresh the page it would call the index() function in the controller and not the bulkSave() function.
Thanks in advance.
Is this possible?
You are calling your index() funciton directly, within bulkUpdate() hence the uri does not change back to index because you are not making a new server request, you are just navigating within your controller class.
I usually use the same Controller function for tasks like this, directing traffic based on whether or not $_POST data has been passed or not like this...
function index() {
if($_POST) {
//process posted data
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$data['showMessage'] = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
}
else {
//show page normally
$data['showMessage'] = FALSE;
}
//continue to load page
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$this->load->view('main', $data);
}
Then if it is a form that you are submitting, just point the form at itself in your view like this...
<?= form_open($this->uri->uri_string()) ?>
This points the form back at index, and because you are posting form data via $_POST it will process the data.
I usually do a redirect to the previous page as it prevent users to refresh (and submit twice) their data.
You can use the redirect() helper function of CI.
http://codeigniter.com/user_guide/helpers/url_helper.html (at the bottom)

Resources