Laravel: Textbox value is not getting received - laravel

View file:
<form action="" method="POST" enctype="multipart/form-data">
#csrf
<input type="checkbox" name="img_check" id="upload" value="dummy value">
<button type="submit" class="btn btn-primary">Update</button>
</form>
Controller file:
function editProduct(Request $request){
echo 'Checkbox value: '.$request->input('img_check');
............
............
............
return view('dashboard.editProduct', array('product' => $productData,
'categories' => $categoriesData,
'shippingPolicy' => $shippingPolicyData,
'returnPolicy' => $returnPolicyData,
'subcategory' => $subcategory,
'success' => $success));`
}
OUTPUT:
Checkbox value:
Output shows only text message, not textbox value.
All other fields of forms are working fine but only checkbox value is not getting received.
Surprisingly it is working fine on other form of mine which is being called from another controller. I tried a lot but couldn't figure out what is making textbox value fail!
Any idea?
EDIT:
Route path:
Route::match(['get', 'post'], 'edit_product', [dashboardController:: class, 'editProduct']);

your method should check whether request is post or get.So in request get method it return empty
public function editProduct(Request $request){
if($request->isMethod('POST')){
dd($request->input('img_check'));
}
return view('dashboard.editProduct', array('product' => $productData,
'categories' => $categoriesData,
'shippingPolicy' => $shippingPolicyData,
'returnPolicy' => $returnPolicyData,
'subcategory' => $subcategory,
'success' => $success));`
}

Update your route path to post as suggested by John.
If you are doing update operation it will be post method, get is only used for fetching the data.
Route::match(['post'], 'edit_product', [dashboardController:: class, 'editProduct']);

This is extremely strange behaviors of laravel 8.
What actually I did was, I copy checkbox field from other form of my project and paste it in current form (in which I was doing modifications). So simply copied one field from another form to my current form.
And laravel wasn't accepting this copy paste field as input field. It's value wasn't getting received and it wasn't entering in following if condition if($request->isMethod('POST')){ .
So finally I typed checkbox checkbox field by myself and that field started to work!!!!
I mean why..............!!?? If I copy paste any field from one page to another then laravel don't consider it as input field but if you typed then it started working!!
Here is my previous textbox field
<input type="checkbox" name="img_check" id="upload" value="dummy value">
And here it is my new checkbox field which I typed instead of copy paste
<input type="checkbox" name="allow" id="upload" value="hello">
And new checkbox was working. Damn I am so confused.... whats the difference between those fields?? IS this laravel's some kind of bug or what...?
NOTE: Both forms ware already being made and working. For little modifications I did copy one field from one to another form. On newly created form, copy paste field didn't bother me.

Related

Laravel 5.1, update multiple values from checked checkbox

In Laravel 5.1, I need to update multiple values from checked checkbox.
I can edit some registries from a table by clicking the edit button for each registry, and that button send me to the edit view
(This is de edit view for a single registry)
With the url: http://myapp/someroute/2246/edit where 2246 is some id.
Inside that edit I can update 4 fields. One of those fields is called "my state" and can have the values 1, 2 or 3.
Now, I have to make a multi select edit feature, where I can check every row of the table that I need to update simultaneously (each have the name=someid) and then click some button called "Validate", and update for evey row only 1 field, the my state field, and the new value will be always 1 (in the picture the values are string but thats only for the view).
The question is: how can I call the method update for every id that I'm selecting in the view? every input checkbox has it's own name which is the id of the registry that I will update.
The update method just validate some values from the view and then call some myeditmethod, but in this case I will jump the update and go directly to myedit which is someting like:
public function myedit(Request $request, $id) {
$obj = Self::findOrFail($id);
$obj->fk_id_comuna = $req['fk_id_comuna'];
$obj->fk_id_user = $usuario_id;
$obj->date = \Carbon\Carbon::now();
$obj->fk_id_my_state = $estado; //THIS IS THE ONLY FIELD THAT I WILL EDIT, ALWAYS WITH THE SAME VALUE `1`
$obj->save();
I was trying the make a form for that Validate button but I don't know how to handle multiple id in one call on the edit method.
<form action="{!! route('myroute.update', ['id' => [HERE, HOW CAN I PASS MULTIPLE ID FROM THE CHECKED CHECKBOX] ]) !!}" method="POST">
<input type="submit" class="btn btn-primary pull-right" value="Validar" />
</form>
I was thinking on a javascript function which collect in a array every checked checkbox name and call the myedit method directly, without the formof the view, could be?
About passing multiple values as one Request value.
Assume you have form like this:
<form method="post">
<input type="checkbox" name="options[]" value="foo"/>foo<br/>
<input type="checkbox" name="options[]" value="bar"/>bar<br/>
<input type="checkbox" name="options[]" value="buz"/>buz<br/>
<input type="submit" value="Submit" />
</form>
Your request('options') would be an array: ["foo", "bar", "buz"].
Than you can iterate over options using foreach.
Inside your update method you can go with:
foreach ($option as request('options')) {
//put your previous code here, so it'd be applied for every option
}
In JS I did this:
var optionsChecked = [];
$('.options:checkbox:checked').each( function(){
optionsChecked .push($(this).val());
});
Then in ajax:
$.ajax({
type: 'POST',
data: {'id': optionsChecked },
etc
Then in PHP:
$all = $request->input('id');
foreach ($all as $id){
//whole obj->* = *;
$obj->save();
}

How to bind an error to a field from within a thymeleaf page

I have a simple 'user registration' page with a 'username' field along with other fields. My requirement is 'username' should not be duplicate, for this I have written a ajax function which checks if username is duplicate and if it is duplicate it prints an error message below the 'username' field, this flow is working fine, problem occurs when I click on submit button, even with the 'username not unique' message i am able to save the page [although i can catch exception and handle it accordingly]. I know this is happening because i am just displaying the error message and not binding error to 'username' field. How can I bind error message to username field(in case of username duplicate error) so that page is not submitted until this error is removed?
Code is below
1.JQuery
function check_username(){
$("#usernamentavlberror").empty();
var developerData = {};
developerData["userName"] = $("#username").val();
$.ajax({
type: 'POST',
contentType : "application/json",
url: '/checkForDuplicateUsername',
data : JSON.stringify(developerData),
dataType : 'json',
success: function(data){
if(data == "userNameExists"){
alert("inside user")
$("#usernamentavlberror").html("UserName Not Available");
}
else {
//do perform other actions like displaying error messages etc.,
}
},
error : function(data) {
alert("error---"+data);
}
});
}
Thymeleaf page
<form action="#" th:action="#{/signup}" th:object="${user}" method=post>
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-user"></i>
</span>
</div>
<input name="username" th:field="*{username}" class="form-control" placeholder="User Name" type="text" id="username">
</div>
<div class="form-group input-group" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></div>
<div class="form-group input-group" id="usernamentavlberror"></div>
.
.
</form>```
"How can I bind error message to username field(in case of username
duplicate error) so that page is not submitted until this error is
removed?"
You have to understand that Thymeleaf templates are processed on the server side so you first have to submit the page to be able to get back the errors. But this doesn't mean you cannot add some nice to have features like the one you're trying to and have both worlds working together for a better user experience.
In the first iteration I would have first implemented a signup page with Thymeleaf and Spring MVC without involving any JS code. The form should have its own validation annotations, and custom ones if needed and I would have triggered them back to the view via the standard BindingResult. So when you submit an invalid form you do the standard error handling which is happening on the server side and from the server you receive back to the client a page which already contains the html with the errors in it which you render as you already did.
So after your first iteration you decided you want to validate the username via this jQuery AJAX call which will inform the user even before the submit that his username is already used. You can do it but then you take the whole responsibility of this flow. So now we are in a state where the user is seeing the error and he's also able to click on the submit form. If he does it then the server will also respond back with a page which has the validations in it so this is let's say acceptable. You can improve it by disabling the submit button in case there are still fields with validation errors but you have to do this via some JS code again.

Hidden field "ufprt" being added to Razor Umbraco Form - Why?

I have got a form (below) that is posted to an umbraco surface controller.
#using (Html.BeginUmbracoForm("AddToBasket", "Basket"))
{
<h1>#Model.productSelectionModel.Product.Title - #Model.productSelectionModel.Product.Price.ToString("C")</h1>
<ul>
#foreach (var productOption in Model.productSelectionModel.ProductOptions)
{
<li>#productOption.Option.Title</li>
#Html.DropDownList(productOption.Option.Id.ToString(), productOption.ValuesInOptions.ToSelectList(f => f.OptionValue.OptionValue1,
f => f.Id.ToString(),
"Select"));
}
</ul>
<input type="submit" value="Add To Basket">
}
When I look at the HTML rendered for this form it seems to have added a hidden field called ufprt. Does any one know what this is? Why is it being added, I'm not using it any where ( I don't think I am anyway)
Any ideas?
<input name='ufprt' type='hidden' value='6C01896EF3D5F430F9ED041DD2B0D31F89FA969A085C6F4FDEC3C9D4B906846E7AA80041CEA12573E9F58C1740893B770AAE3319FAA8FA35C89A54D301CFE31B85ADC0D3D9506D208DB068D1257C5F0D5F1B3B90FD59A5C2938EED0A2EB1168AD4573CD5D043D47A8F1AA789E988CC614686B89BE57D35DA8EAAA110044C393F' />
It is to route the form to the correct controller/action method (Umbraco has the ability to route forms via that input value rather than the typical MVC approach of using the URL). I believe this is particular to surface controllers (i.e., it wouldn't apply to a normal controller, API controller, or RenderMvcController).
It is not a CSRF token as another answer indicates. If it were, it would likely have a name of "__RequestVerificationToken" as indicated here: http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-%28csrf%29-attacks
EDIT: This information has been added here: https://github.com/kgiszewski/LearnUmbraco7/blob/a97e85e5ad17e2ba9fc463f02c76885911046b57/Chapter%2006%20-%20Surface%2C%20WebAPI%20and%20RenderMVC%20Controllers/02%20-%20Surface%20Controllers.md#special-routing

Validation of dynamic created form (AngularJS)

I try to made nested form with validation. All works fine, but when I remove one of nested form, validation continue to use removed form. I made jsfiddle example http://jsfiddle.net/sokolov_stas/VAyXu/
When example runs, form are valid. If click "+" button, nested form will be added and valid will be false. Then click "-" button, and valid will be false all the same.
The question is: How to remove dynamic created form from validation processing.
Well, for one thing, a <form> inside of a <form> is not valid HTML.
Second, you're not supposed to be doing DOM manipulation from inside the controller. The controller is for "business" logic. See the section on controllers here
For what you're doing, you'd probably be better off using one form, with an ng-repeat inside of it, and adding additional elements to an array:
<form name="myForm" ng-controller="FormCtrl" ng-submit="doSomething()">
<div ng-repeat="item in items">
<input ng-model="item" type="text" required/>
</div>
<a ng-click="addItem()">+</a>
<a ng-click="removeItem()">-</a>
<button type="submit">Submit</button>
<div>Form valid: {{myForm.$valid}}</div>
</form>
and the controller:
function FormCtrl($scope) {
$scope.items = [];
$scope.addItem = function() {
$scope.items.push(null);
};
$scope.removeItem = function() {
$scope.items.pop();
};
$scope.doSomething = function () {
//your submission stuff goes here.
};
}

Client side validation not working for hidden field in asp.net mvc 3

I have got a hidden field with a validation for it as below
#Html.HiddenFor(m => m.Rating)
#Html.ValidationMessageFor(m => m.Rating)
The Rating property has Range validator attribute applied with range being 1-5. This is put inside a form with a submit button.
I have then got following jquery that sets the value in hidden field on some user event (Basically user clicks on some stars to rate)
$(".star").click(function(){
$("#Rating").val(2);
});
Now if I submit the form without the user event that sets the hidden field, the validation works. The error messages is displayed properly and it works all client side.
Now, in this situation, if I click on stars, that invokes the above javascript a sets the hidden field, the validation error message would not go away. I can submit the form after the hidden variable has some valid value. But I'm expecting that the client side validation should work. (When the hidden variable has been set with some valid value, the validation error should go away)
Initially I thought, the jquery validation would be invoked on some special events so I tried raising click, change, keyup, blur and focusout events myself as below
$(".star").click(function(){
$("#Rating").val(2);
$("#Rating").change();
});
But this is still not working. The error messages once appeared, does not go away at all.
You can wrap your hidden field with a div put somewhere but still inside the <form>. Add css to kick it to outer space.
<div style="position:absolute; top:-9999px; left:-9999px">
<input id="Rating" type="hidden" name="rating" >
</div>
Then add the following label to where you want to show the error:
<label for="rating" class="error" style="display:none">I am an an error message, please modify me.</label>
Client-side validation ignores hidden fields. You can set the "ignore" option dynamically but just to get it to work I did the following directlyl in the .js file.
For now this should do the trick.
In my aspx...
<%: Html.HiddenFor(model => model.age, new { #class="formValidator" }) %>
In jquery.validate.js
ignore: ":hidden:not('.formValidator')",
This turned out to be a very interesting issue. the default "ignore" setting is ignores hidden fields. The field was hidden in a jQuery ui plug-in. I simply added a class called "includeCheckBox" to the rendered input I wanted to validate and put the following line of code in...
var validator = $('#formMyPita').validate();
validator.settings.ignore = ':hidden:not(".includeCheckBox")';
if ($('#formMyPita').valid()) {....
In the code which sets the hidden field's value, manually invoke validation for the form, like so:
$("form").validate().form();
I think it is because hidden inputs don't fire any of these events.
What you could do instead would be to use a <input type="text" style="display:none" /> instead of the hidden field;
#html.TextBoxFor(m => m.Rating, new {display = "display:none"})

Resources