Yii2 redirect to previous page - yii2

Now My application is using gridview to list all information and it's also have pagination.when the user click on pagination number and then click on edit and then save. It redirect user to view page. What I want to do it to redirect user to previous page(url with pagination number).

You could use Yii::$app->request->referrer which returns the last page the user was on.
Usage is straightforward:
return $this->redirect(Yii::$app->request->referrer);
You need also take into account that referrer can be null:
return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
See the docs.

Here it says that it's a good practice to check if referrer is set at the first place.
So if you use the following code you will be redirected to last page if referrer is set or to your configured homeUrl if the return URL was not set previously.
return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));
goBack() details
redirect details

It is true what #Kostas says, but I think it would be better if you simply code the following, because goBack take account of a null parameter already to goBack HOME.
return $this->goBack(Yii::$app->request->referrer);
I tested it and it works fine.

If you use Html::submitButton when you are in a form and you want to be redirected to the previous page, so mostly to your module list I recommend using use yii\helpers\Url;:
return $this->redirect(Url::previous('previous') ?: ['list']);
because
return $this->redirect(Yii::$app->request->referrer);
will return you back to the form instead of a module list.

Related

Do not change the router values ​in the address

I have a page (index) with an #ActionLink that opens another page to edit an invoice, the page will appear correctly, but the [Url-address] shows the number for the invoice, and when I change the number for the invoice in the [Url-address], it means that he opened another invoice, and I want the modification page not to open from By modifying the [Url-address] or using a direct link, I found a nice way, but it is used with [Post] and not Get. Is there a way to protect the [Url-address] of the page from being modified and its values?
View Index:
#Html.ActionLink(
linkText: "Edit_Invoice",
actionName: "Invoice_Edit",
controllerName: "Invoice",
routeValues: new { ID_Invoice = 2 },
htmlAttributes: new { area = "Pro"})
Controller :
[HttpGet]
public ActionResult Invoice_Edit(int id_invoice)
{
Table.Invoice invoice = (from i in Cn.Invoice
where i.ID_Invoice == id_invoice
select i).FirstOrDefault();
return View(invoice;
}
View Invoice_Edit:
#Html.TextBoxFor(m => m.ID_Invoice)
#Html.TextBoxFor(m => m.Date_Invoice)
<button>save</button>
When you open the invoice modification page, its number will appear in the address as in the link below
https://localhost:44320/Pro/Invoice/Invoice_Edit?ID_Invoice=2
I only want to open invoices that are selected from the page only.
Update 1 : Change Title Answer
if you what users to open only invoices that they are allowed to open, antiforgery token has nothing to do with it. You neeed server side validation, authentication and authorization. All of these should be implemented on the server side. Client side javascript code is not enough.
Anti-Forgery Tokens don't make a lot of sense for any request where you're not modifying and persisting data. So I recommend to remove [ValidateAntiForgeryToken] from your GET since GET request will be returned to the user, not the attacker.
AntiForgeryToken is designed for POST requests and it expects the token in Request.Form collection. You can just use post instead of get to receive data. Or you can use ajax. Google and you will find some examples.
But make sure that you are using them when you're creating, updating or deleting data.

"Create or update" form behavior when hitting back button

I have the following workflow on a website:
Some user John Doe declares a company through form 1
(fields: name, head office location)
After John Doe submits (HTTP POST) form 1, he is redirected (HTTP 302) to company form 2 with additional legal information about the company.
The problem is, if John Doe hits the back button of his browser during step 2, he will land on the form 1, with data filled by the browser (using values he already submitted — that's what Firefox and major browsers seem to do).
John Doe might then think he can use this form to update some information (e.g. fix a typo in the name of the company) whereas he will actually create a new company doing so, as we don't know on the server side whether he wants to declare a new company or update the one he just created.
Do you know any simple solution to handle that problem ?
Use javascript/jquery script after the page is loaded to empty all the inputs. This will prevent confusion of "updating the company".
jQuery would look something like this:
$('#elementID').val('');
You can also handle the situation by manipulating the browser history
on load of form 2, and pass the CompanyId generated on submit of form 1 using querystring. So that you can actually update the company as the user
Suppose John submits form1.html, a unique CompanyId "1001" is generated and redirected to form2.html. Now on load of form2 you can modify the browser history form1.html?companyid=1001 using
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 1", "form1.html?companyid=1001");
Now, when the user click back button and submits the form1 again. you can check for companyid in querystring and update the company.
I think it is more user-friendly when user can return back to previous form and update it (instead preventing the described behavior).
I use in most cases similar way to handle described problem:
Let's assume that user is on the page /some-page, that contains "Create new company" button.
When the user opens this page, will be executed special method createOrFindCompanyDraft() on the server-side. This method creates new company "draft" record in DB (only for the current user). For example, draft record has primary key id=473. When you execute this method again it will return the same record with the id=473 (with "draft" status). "Draft" record should't display on any other interfaces.
And "Create new company" has link /company/common/473.
When user go to /company/common/473, you display form 1, that will be filled from "draft" record. At first time user will see empty form.
Technically user will update the existing record, but you can display "Create new company" title on the page.
Then user go to form 2, for example, /company/legal-info/473, you create similar draft record for the this form (similar to step 1).
When user submit the form 2, you will remove "draft" status from the record id=473 (and any related records).
Next time when user open page /some-page, will be created new draft record for the current user.
Browser history will contain:
/some-page
/company/common/473
/company/legal-info/473
/some-page2
I like this approach, because all form only update records. You can go to previous/next form many times (for example "Back"/"Forward" browser buttons). You can close browser, and open not completed forms tomorrow. This way doesn't require any additional manipulation with the browser history.
try this
<form autocomplete="off" ...></form>
And Another
Use temporary tables or session to store the Page 1 form data. If the page 2 form is submitted use the temporary data of page 1 which is stored in database or in session.
Use a Separate key (Hidden field ) in both page 1 and page 2.
Actually I thought of a trick to obtain that "create on first post, update after" behavior (just like the user thinks it should behave).
Let's say the step 1 form is at the URL /create_company/. Then I could have that page generate a random code XXX and redirect to /create_company/?token=XXX. When I create the company I save the information that it was created through page with token XXX (for instance, I save it in user's session as we don't need to keep that information forever) and when the form is submitted, if I know that a company was already generated using this token, I know the user used the same form instance and must have used the back button since the token would be different if he explicitly asked for another company.
What do you think ? (I initially thought there should be a simpler solution, as this seems a little bit over-engineered for such a simple issue)
This is more like a UX question.
I'd think that the solution lies within the information given to the user on that form, to help them understand what they're doing.
Set a title that says 'Create a company', for example, and set your submit button as 'Create Company' will help your user with that. Use a unique id when you create the company object, and pass the id back to the same URL in order to perform an update. You should then update your title and button that tells user that they are updating instead of creating.
In that sense I'd say it's better to use a more generic URL like /company and /company?id=12345.
You could also consider using Restful API protocol to help your server identifies the CRUD operation. http://www.restapitutorial.com/lessons/httpmethods.html
Without the "routing" part of django it is hard to help. I can just answer my experience from the express.js-router functionality:
you can specify a post on /company, which is for new users.
you can specify another route for post on /company/:companyid for a changing form
and as a response from the create-post you can redirect to the different location.

Button in html that deletes an instance of a Django model

If I have a list of instances, and each instance has a button or checkbox.
When you press it, it calls delete() on the instance. How would you implement this in Django?
You'll need to create a function view that would query that exact instance that you want to delete. I have an example from my app that would query the selected comment on a post and deletes it when the user presses a delete button.
def delete_comment(request, comment_id):
comment = get_object_or_404(Comment, id=comment_id)
slug = slugify(comment.post.slug)
if request.user.is_staff or comment.user == request.user:
Comment.objects.get(id=comment_id).delete()
messages.success(request, "Your comment was successfully deleted.")
return HttpResponseRedirect(reverse("main.views.post", args=(slug,)))
So let me explain how does this function view work. I have a model called Comment, and that Comment model has a foriegnkey to the Post model. So each post has some comments. A user now commented on a post, and he decided to delete it. There is a delete button that redirects him to the delete_comment function view. The view tried to get the comment id, if it exists it continues, if it doesn't it returns a 404. Then it checks if the comment was made by the same user that is trying to delete it, or if the user is a staff member. Then we get the comment id, and make it the same as our function parameter comment_id so we can use that in the urls.py, as you can see we get the exact comment id and we use the delete() function to it, and that deletes the comment!
And ofcourse you'll need a url for that which would look like the following for the delete_comment view
url(r"^delete_comment/(?P<comment_id>\d+)/$", views.delete_comment, name="delete_comment"),
And here is how you write the delete button to hook it up with the view and the url
delete
As you can see the url contains where the delete function view is, and it's using the argument of the comments.id to be used in the view and the url. It's easy to implement, hope this example gave you a starting point/idea on how to start.

How should I edit a model entry in mvc?

I am working on a small app using phalcon for php framework. I have implemented multiple controllers and models, but so far when I want to edit a user for example, i use a link that links to
localhost/myappname/User/edit/11 "user's id"
I was told this is not the best way to do this, and I am trying to do this without passing the id through the url, like using post method like in forms but without success so far.
Is this the only correct way to edit or delete an entry or it there something better?
I tried to search for the problem but couldn't figure how to name this question so I am yet to find an answered question.
If you don't want to let everyone access to edit page you can do this in a few ways.
Solution #1
You can use Phalcon ACL to block user's who has no permission to edit this page so only allowed people like managers can edit user or whatever.
See Access Control Lists ACL
Solution #2
You can crypt/decrypt user id so in URL it will not be readable by humans and then in edit method try to dectypt that id and if it is not a valid echo error.
<?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
$key = 'le password';
$user_id = 5;
$encrypt = $crypt->encryptBase64($user_id, $key);
// Use $encrypt for URL like Edit
// Use decrypt to get the real id of a user
$crypt->decryptBase64($encrypt, $key);
?>
In this way users will see URL something like
localhost/myappname/User/edit/nomGPPXd+gAEazAP8ERF2umTrfl9GhDw1lxVvf39sGKF34AFNzok31VdaT/OwADPPJ4XgaUNClQKrlc/2MfaXQ==
For more info see Encryption/Decryption
But my personal opinion is that it is better to go with ACL. After all ACL was made for that kind of things.
Note! If you want to use Encrypt/Decript remember to wrap decryption
in edit method in try/catch block and catch exception so you don't
get Error if someone tries to guess sone id.
Solution #3
If you still want to do that using POST then don't use Edit instead you can try something like:
<form method="POST">
<input type="hidden" name="uid" value="{{ user_id }}"/>
<button type="submit">Edit</button>
</form>
And then in edit method catch that id like:
<?php
$user_id = $this->request->getPost("uid");
?>
NOTE! In this way your URL will not contain user id but someone still
can POST another uid so you can try to hide that real user id even
from input type hidden. You can use again crypt/decrypt so input
hidden uid can be crypted and then decrypt post data in method.
you could use sessionStorage. It would store the value of the userId in the browser and be deleted as soon as they leave the page.
http://www.w3schools.com/html/html5_webstorage.asp
set on one page
sessionStorage.userId = 11;
access on another
var user = sessionStoarge.userId;

Laravel Eloquent how to limit access to logged in user only

I have a small app where users create things that are assigned to them.
There are multiple users but all the things are in the same table.
I show the things belonging to a user by retrieving all the things with that user's id but nothing would prevent a user to see another user's things by manually typing the thing's ID in the URL.
Also when a user wants to create a new thing, I have a validation rule set to unique but obviously if someone else has a thing with the same name, that's not going to work.
Is there a way in my Eloquent Model to specify that all interactions should only be allowed for things belonging to the logged in user?
This would mean that when a user tries to go to /thing/edit and that he doesn't own that thing he would get an error message.
The best way to do this would be to check that a "thing" belongs to a user in the controller for the "thing".
For example, in the controller, you could do this:
// Assumes that the controller receives $thing_id from the route.
$thing = Things::find($thing_id); // Or how ever you retrieve the requested thing.
// Assumes that you have a 'user_id' column in your "things" table.
if( $thing->user_id == Auth::user()->id ) {
//Thing belongs to the user, display thing.
} else {
// Thing does not belong to the current user, display error.
}
The same could also be accomplished using relational tables.
// Get the thing based on current user, and a thing id
// from somewhere, possibly passed through route.
// This assumes that the controller receives $thing_id from the route.
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->first();
if( $thing ) {
// Display Thing
} else {
// Display access denied error.
}
The 3rd Option:
// Same as the second option, but with firstOrFail().
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->firstOrFail();
// No if statement is needed, as the app will throw a 404 error
// (or exception if errors are on)
Correct me if I am wrong, I am still a novice with laravel myself. But I believe this is what you are looking to do. I can't help all that much more without seeing the code for your "thing", the "thing" route, or the "thing" controller or how your "thing" model is setup using eloquent (if you use eloquent).
I think the functionality you're looking for can be achieved using Authority (this package is based off of the rails CanCan gem by Ryan Bates): https://github.com/machuga/authority-l4.
First, you'll need to define your authority rules (see the examples in the docs) and then you can add filters to specific routes that have an id in them (edit, show, destroy) and inside the filter you can check your authority permissions to determine if the current user should be able to access the resource in question.