laravel blade form not routing to a named route - html

I am new to named routing in Laravel 5.5 and I am facing a strange thing while trying to perform an action of a form;
Setups and Explanations:
I set up my routes in web.php
Route::post('questions/save_bulk', 'QuestionsController#save_bulk')->name('save_bulk');
Route::post('questions/store_bulk', 'QuestionsController#store_bulk')->name('store_bulk');
Then I set up store_bulk and save_bulk in QuestionsController:
public function store_bulk(Request $request)
{
//$x = some DB::selects statements;
return view('questions.store_bulk', ['x'=> $x]);
}
public function save_bulk(Request $request){
dd($request);
}
And finally this is my blade form in questions.store_bulk which should lead to QuestionsController.save_bulk:
<form method="post" action="{{route('save_bulk')}}">
{{csrf_field()}}
/* some codes and input fields */
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit"/>
</div>
</form>
Problem
The problem is that when I submit this form, instead of taking me to the desired route and perform dd($request), it is just refreshing the page without the inputs I had as if Laravel took the last post form which returned the view questions.store_bulk.
Though this is the exact same way I used to get into the view questions.store_bulk in the first place, a strange thing occurs: when I try to inspect elements in the blade page I get the following:
<form method="post" action="http://127.0.0.1:8000/questions/store_bulk">
/* some codes and inputs */
</form>
in the codes the route should go to QuestionsController.save_bulk but when inspecting the HTML it says it goes to http://127.0.0.1:8000/questions/store_bulk, and if I inspect and change the route manually inside the HTML and write http://127.0.0.1:8000/questions/save_bulk it goes to the right route and perform dd($request).
Question
Why is this happening? am I missing something?
Note
I am using Laravel 5.5 locally on my PC preparing a website.

I've had similar issues with routing.. You can change the url.. e.g. questions/somethingelse/save_bulk.. so the urls won't clash.. Or run php artisan cache:clear or view:clear incase you implemented a page caching system

Related

With use PathVariable CSS not loading and how to fill form to update in thymeleaf

I am trying to do same small service and sometimes I am sending requests to my Rest Api.
I am getting two problems:
How to fill field in form in html using thymeleaf? I have form like this and would like to fill fields with current values (th:value="${}" - not working for me):
<form th:action="#{/offences/edit}" method="post" th:object="${createOffenceForm}"> <input th:field="*{name}" th:value="${currentOffence.name}"/> <input th:field="*{penaltyPoints}" th:value="${currentOffence.penaltyPoints}"/> <input th:field="*{amountOfFine}" th:value="${currentOffence.amountOfFine}"/> <button type="submit">UPDATE</button> </form>
The problem is with loading css styles to html when I redirect to the site with path variable. For example i created html with two buttons. First one is hardcoded:
<a th:href="#{/offences/test}" class="link" style="text-decoration: none"><button class="buttonOK" type="submit">EDIT</button></a>
after redirect my site looks like this (everything works, it should be like that):
`
and here is after second button - redirect with path variable:
<a th:href="#{'/offences/edit/' + ${offence.id}}" class="link" style="text-decoration: none"><button class="buttonOK" type="submit">EDIT</button></a>
and view after load:
For the issue with your form data not being filled, this is because th:field and th:value are not meant to be used at the same time. So th:field ends up overwriting you value.
In your case I would suggest either manualy setting name (and id) or replacing th:object with the a filled version of the bean you want to return and only using th:field
As for the second issue it looks like a faulty fragment return on a post call to me but need to atleast have the controller functions and more complete html to say anything about that. And in general it's advisable to have 1 question per problem and not bundle things.
Ok so i found soultion.
To fill fields in form I only had to add to ModelMap form with fields.
Something like this and thymeleaf autofilled fields in html.
modelMap.addAttribute("createOffenceForm", new CreateOffenceForm(offenceDTO.getName(), offenceDTO.getPenaltyPoints(), offenceDTO.getAmountOfFine()));
Second solution is simple too. When changed mapping in Controller from #GetMapping("/path/{id}") to #GetMapping("/path-{id}") - everything works. There is no other problems with styles...

How to Password Protect Index.html Only? [duplicate]

This question already has answers here:
password protect a single file using .htaccess
(2 answers)
Closed 2 years ago.
So, I have a website that has so many forms/surveys pages , not at the main index.html , but can be accessed by buttons that are inside my "index.html"
What I m looking for is, users can access forms/surveys pages but not the main home page by simply typing ( ex: example.com )
I know a website which when I visit requires me to enter a key to acces the page , I don't know if it's login function since it doesn't require any kind of registration, anyone with that key can visit that website.
For instance let's assume this is inside my main index.html and by clicking button I can visit forms to get shareable url to share forms with someone
<form method="get" action="/form1.html">
<button type="submit">this takes me to form1 page</button>
</form>
<form method="get" action="/form2">
<button type="submit">this takes me to form 2 page</button>
</form>
I don't want users to go to any forms/surveys pages which can be accessed by buttons in main index.html
That's why I want to Password Protect my index.html only but not it pages
Please help me out
As mentioned, This is not possible with HTML alone.
is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript.
CSS will give it some looks,
Javascript will give it some logic.
You can prompt the user for a password on page load and verify it and act accordingly. Only problem is as mentioned by #LosManos is that you'd be exposing your password in your HTML which will be visable by anyone. This is a big NO NO
That been said, Below is a proof of concept (unsecured). You could use the same logic by sending password() function to backend (your server code). - Just keep poping prompt untill it resovles.
Prompt will block all handlers in page untill resolved, thus page will be protected until password handled.
window.onload = () => {
password();
}
function password() {
let p = prompt('password:');
(p === 'password') ? true : password();
}
<form method="get" action="/form1.html">
<button class='btn' type="submit">this takes me to form1 page</button>
</form>
<form method="get" action="/form2">
<button class='btn' type="submit">this takes me to form 2 page</button>
</form>
But again as mentioned, you'd have to build a backend logic to handle prompt and respond even if not using a user authentication sys. FWIW it should look somehow, (although the next code block isn't tested and is for conceptualizing, of course), like:
function password() {
let p = prompt('password:');
fetch('/path/to/check/password', {body: {pass: p}}).then(res => {
if (res) {
return;
} else {
password();
}
});
}
When '/path/to/check/password' verifies the password and returns true/false from server, or something alike.

MVC HTML posting form data

Apologies in advance if this is a dumb question but I'm struggling to get the look and feel I want whilst posting the data I need to the server: s
I've built a simple file upload page using Dropzone.js and am able to upload files to the server. I also want to pass a value from a drop down to the same action method but can only achieve this if my drop down is contained within my dropzone (which I don't want!)
My Page and HTML look like this:
The class="dropzone" defines where the dropzone is and seems to be have to be attached to the action="~/Media/SaveUploadedFile" or the fallback class gets used instead and screws up the layout. So this code gives me the layout I want with the dropdown outside of the dropzone but does not pass the drop down value to my Action Method: (
What am I doing wrong?
Controller method:
public ActionResult SaveUploadedFile(string ContentDirectory)
Try using Html.BeginForm. Place your dropdown inside of the #using tag.
#using (Html.BeginForm("SaveUploadedFile", "Media", FormMethod.Post, new { #class = "dropzone", enctype = "multipart/form-data" }))
{
//Dropdown here
<div class="fallback">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</div>
}
Here's a similar existing post for uploading files in MVC

Add logic to delete method in Sinatra

I have been learning Sinatra for a couple of days now so I am still quite new. I am simply created a notes application and have added a delete function within the app.
Here is my Controller:
# Will display title of all notes
get '/' do
#notes = Note.all
erb :index
end
# Will display content within selected note
get '/:id' do
#note = Note.where(id: params[:id]).first
erb :note_description
end
# Will delete item from notes.
delete '/:id' do
Note.delete(params[:id])
redirect '/'
end
Here is my view with html/erb:
<div class="container">
<p>Return to Notes</p>
<h1><%= #note.title %></h1>
<p><%= #note.content %></p>
<form onsubmit="confirm('Are you sure you want to delete the following note?')" action="/<%= #note.id %>" method="POST">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete</button>
</form>
</div>
As you can see, I have created a delete button and have a pop-up on submit when you click it. This will simply verify if the user really wants to delete the object. What happens though, is no matter what I click the item will be deleted and I will be redirected to the home page. I want to add logic where the app will only delete and redirect me to home page if the user clicks okay. If they click cancel nothing should happen. Any advice or help would be greatly appreciated.
You need to return from the event handler itself, so the attribute will look like:
onsubmit="return confirm('Are you sure you want to delete the following note?')"
Currently the return value of return is being returned to the event handler, but the handler itself is returning true (or at least not false).
(The current recommendation seems to be to avoid inline event handling like this though.)
You are seeing this behavior because the client is doing a POST, not a DELETE.
HTML forms only know how to do GET and POST. They cannot do PUT or DELETE. One way you can make it work is by using an AJAX call.
If you are using JQuery, you can set the method to DELETE. Here is the reference.
You will need to create the URL: /1 for example. And you need to handle the success and failure cases. Perhaps set the location on success, and display an error on failure.
EDIT: According to Matt's comment below, _method param replaces the HTTP method. Even though this works, I don't think it is a good practice. It would be better to use the HTTP DELETE method.

Django form: *Nothing* happens when submit button is clicked

I'm probably missing something very basic but I'm stumped.
My HTML form (in a Django template):
<form id="site_signout" method="POST">{% csrf_token %}
<input type="submit" value="sign in">
</form>
In my browser (running my site on the dev server), when I click on the <input> button, nothing happens. Like, nothing nothing. Normally something would show in Terminal such as
[22/Apr/2014 08:29:17] "POST /my/url/ HTTP/1.1" 302 0
Or in Firebug, I would see something about a POST in the HTML tab of the Net panel. But I see nothing. Literally nothing happens when I click the button.
Other submit buttons (for other forms) on my site work just fine.
What could be causing this?
EDIT: The relevant part of my view is:
if request.method == 'POST':
pdb.set_trace()
That's all I have for the form right now because I want to examine what is posted in this scenario before I write more code.
EDIT: My intention is to simply POST to the same page (URL) that the form is on. As I understand it, this should be achievable by simply omitting the action attribute of the <form> element altogether. This is how I started but since it didn't work, I tried a couple of other options such as action="/", which is what I originally posted above. However, my intention is to have the form POST handled by the same view as the form itself. Therefore I've edited my original code sample to omit the action attribute altogether to clarify this point.
Here is my top-level urls.py:
urlpatterns = patterns('',
url(r'^inspection/', include('main_inspection.urls') ),
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is main_inspection.urls with the relevant URL:
urlpatterns = patterns('main_inspection.views',
url(r'^home/$', 'home', name="inspection_home"),
...
)
The URL for the view in question (on my dev server) is:
http://127.0.0.1:8000/inspection/home/
The solution turned out to be quite silly, and not discoverable by anyone reading the above question:
I had some JS capturing any click event happening inside the div in which the form was located.
Lesson learned: when something really strange seems to be happening at the basic HTML level, check to make sure you didn't write any stupid JS code that is producing the effect.
Your URL about "/" should be something like this:
...
url(r'^$','yourapp.views.index',name="base_address"),
...
It will run "yourapp.views.index" when you call "/" address.
If you want to set an address in you form action attribute try to set name of address instead:
<form id="site_signout" method="POST" action="{% url 'base_address' %}">{% csrf_token %}
<input type="submit" value="sign in">
</form>
We defined "base_address" name in urls that assigned to "/" address and then used that with "url" method in template.