Laravel : send value of check box to controller without posting? - laravel

I'm using Laravel for my application.
I have made a PRINT button on my HTML page which is simply calling a route, to be able to send it throught DOMPDF to print it to PDF.
Print
Now, in my Controller, I would like to get the value of a radio button which has been created in the HTML this way
<div class="col-lg-7 selectie">
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="1" checked> Alle facturen&nbsp
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="2"> Betaalde facturen
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="3"> Onbetaalde facturen
</div>
In my controller I can not find the way to get the value of the checkbox, I suppose because I'm not doing a submit ?
How would I be able to get the value of the radio button please?
public function printFacturen(Request $request){
}
I already tried three following ways, but it is not working :
$fields = Input::get('factuur_selectie');
$value = $request->get('factuur_selectie');
$request->input('factuur_selectie');
Bestregards,
Davy

You need to grab the value of factuur_selectie using JavaScript and add it to the generated URL, something like:
var val = document.querySelector('#factuur_selectie:checked').value;
var btn = document.querySelector('.btn.btn-default');
var url = btn.getAttribute('href');
btn.setAttribute('href', url + '?factuur_selectie=' + val);
Then you should be able to retrieve factuur_selectie from your controller.
Probably you are going to need to update the value everytime an option is selected. In that case you can retrieve the value from then event itself:
var btn = document.querySelector('.btn.btn-default');
document.querySelector('.selectie').addEventListener('change', function(event) {
var val = event.target.value;
var url = btn.getAttribute('href');
var pos = url.indexOf('?');
// If URL already contains parameters
if(pos >= 0) {
// Remove them
url = url.substring(0, pos);
}
btn.setAttribute('href', url + '?factuur_selectie=' + val);
});
Here you have a working example.

Related

AngularJS Form Validation inside an ng-repeat

So I am trying to validate the input of one item inside of an ng-repeat. For examples sake lets say that I have 5 items (1,2,3,4,5) and I only want to validate the form if the 4th item is selected.
I have used ng-pattern before to validate forms, but not one that had a dropdown menu to select item.name
I have included the regex I would like the 4th item to be validated with inside the ng-pattern.
<div>
<select name="name" ng-model="item.name" ng-options="item for item in items" required></select>
</div>
<div>
<input name="results" type="text" ng-model="item.results" ng-pattern="/^\d\d\d\/\d\d\d/" required>
</div>
Any suggestions as to the correct way to validate this situation would be greatly appreciated. I have thought about creating a directive to validate this, but that feels like is an overly complicated solution to this since I would not use the directive more than once in this app.
//////////////////////////////////////////////////
It wouldn't let me answer my own question so here is the answer I figured out.
What I ended up having to do was use ng-pattern and pass it a function.
<input name="results" type="text" ng-model="vital.results" ng-pattern="vitalRegEx()" required>
Here is the controller code
$scope.item4RegEx = /^\d{2,3}\/\d{2,3}$/;
$scope.itemRegEx = function() {
if($scope.item && $scope.item.name === "fourth item")
return $scope.item4RegEx;
else return (/^$/);
};
or else...
add ng-change directive on the select dropdown which calls a Controller method and that controller method sets a flag whether to validate form or not.
eg.
<select ng-change="checkIfFormShouldbeValidated()" ng-model="item.name"></select>
// Inside controller
$scope.checkIfFromShouldBeValidated = function(){
if( $scope.item.name == 4th Item ) $scope.shouldValidate = true;
else $scope.shouldValidate = false;
};
$scope.formSubmit = function(){
if(($scope.shouldValidate && form.$valid) || (!$scope.shouldValidate)){
// Submit Form
}
};
See if it helps.
I wrote this recursive function inside my controller to check the validity of all child scopes.
function allValid(scope) {
var valid = true;
if (scope.$$childHead) {
valid = valid && allValid(scope.$$childHead);
}
if (scope.$$nextSibling) {
valid = valid && allValid(scope.$$nextSibling);
}
if (scope.scorePlannerForm) {
valid = valid && scope.myForm.$valid;
}
return valid;
}
Then in my controller I check this with the controller scope.
function formSubmit() {
if (allValid($scope)) {
// perform save
}
}

How to get checked checkbox value from html page to spring mvc controller

im using spring mvc framework with thymeleaf template engine
the problem is , i have 1 page with multiple check box iterated sing thymeleaf th:each iterator.When i clicked multiple check boxes i want to pass check box values to the controller method..
html content
<table>
<tr th:each="q : ${questions}">
<h3 th:text="${q.questionPattern.questionPattern}"></h3>
<div>
<p >
<input type="checkbox" class="ads_Checkbox" th:text="${q.questionName}" th:value="${q.id}" name="id"/>
</p>
</div>
</tr>
</table>
*Controller*
#RequestMapping(value = Array("/saveAssessment"), params = Array({ "save" }))
def save(#RequestParam set: String, id:Long): String = {
var userAccount: UserAccount = secService.getLoggedUserAccount
println(userAccount)
var questionSetQuestion:QuestionSetQuestion=new QuestionSetQuestion
var questionSet: QuestionSet = new QuestionSet
questionSet.setUser(userAccount)
questionSet.setSetName(set)
questionSet.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetService.addQuestionSet(questionSet)
var list2: List[Question] = questionService.findAllQuestion
var limit=list2.size
var qustn:Question=null
var a = 1;
for( a <- 1 to limit ){
println( a );
qustn= questionService.findQuestionById(a)
questionSetQuestion.setQuestion(qustn)
questionSetQuestion.setQuestionSet(questionSet)
questionSetQuestion.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetQuestionService.addQuestionSetQuestion(questionSetQuestion) } "redirect:/teacher/Assessment.html" }
I think you pretty much have it. With a checkbox, you can only send one piece of information back with the form...that being the value. So if you are trying to determine which checkboxes are checked when the user clicks the submit button, then I would have the checkboxes all use one name...like "id" (exactly like you have). Value is the actual id of the question (again like you have). Once submitted, "id" will be a String array which includes all the values of the checkboxes that were checked.
So your controller method needs to take param called "ids" mapped to parameter "id" which is a string[]. Now for each id, you can call questionService.findQuestionById.
(I'm not a Groovy guru so no code example sry :)
I have used JSTL with JSP and thymeleaf was something new. I read the THYMELEAF documentation.
There is a section which explains multi valued check boxes.
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:value="${q.id}" name="id"/>
In the above code we are not binding the value to the field of the command object. Instead try doing this
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:field="*{selectedQuestions}"
th:value="${q.id}" />
here the selectedQuestions is an array object present in the spring command object.

Parameters not being properly passed to controller action from view

For an app I am working on, I've got the following Razor code for a View I am working on:
#Html.InputFor(m => m.Property1); // A date
#Html.InputFor(m => m.Property2); // Some other date
#Html.InputFor(m => m.SomeOtherProperty); // Something else.
<a href='#' id='some-button'>Button Text Here</a>
<!-- SNIP: Extra code that dosen't matter -->
<script>
var $someButton = $('#some-button');
$(document).ready(function () {
$someButton.click(function (e) {
e.preventDefault();
window.open('#Url.Action("Foo", "Home", new {p1 = Model.Property1, p2 = Model.Property2, pX = Model.SomeOtherProperty})', '_blank');
});
});
</script>
...upon a comment, I checked the rendered HTML. The values come with values, as expected...
<input name="Property1" data-val="true" data-val-required="(Required)" type="text" value="1/1/2013">
<input name="Property2" data-val="true" data-val-required="(Required)" type="text" value="4/11/2013">
<input name="SomeOtherProperty" data-val="true" data-val-required="(Required)" type="text" value="42">
<a href='#' id='some-button'>Button Text Here</a>
<script>
var $someButton = $('#some-button');
$(document).ready(function () {
$someButton.click(function (e) {
e.preventDefault();
window.open('http://localhost:xxxx/Home/Foo?p1=1%2F1%2F2013&p2=4%2F11%2F2013&pX=42', '_blank');
});
});
</script>
...and on the server side...
public ActionResult Foo(string p1, string p2, string pX)
{
var workModel = new FooWorkModel
{
Property1 = p1,
Property2 = p2,
SomeOtherProperty = pX
};
// Do something with this model, dosen't really matter from here, though.
return new FileContentResult(results, "application/some-mime-type");
}
I've noticed that only the first parameter (p1) is getting a value from the front end; all my other parameters are being passed null values!
Question: Why is the ActionResult being passed null values, when some value is assigned for these other fields? Or, a complimentary question: why would only the first parameter be successfully passing its value, while everything else is failing?
The issue is being caused by the escaped URL being generated by Url.Action(). (Source: How do I pass correct Url.Action to a JQuery method without extra ampersand trouble?)
Simply add a #Html.Raw() call around the Url.Action(), and data will flow as intended.
window.open('#Html.Raw(Url.Action("Foo", "Home", new {p1 = Model.Property1, p2 = Model.Property2, pX = Model.SomeOtherProperty}))', '_blank');

Issue with validation on Razor View in MVC

I am building wizard step demo application with MVC3 and using razor view engine as begineer level.
I came across on problem with validation when hide & show control through javascript.
Please look my code section as per below
<div class="editor-field">
#Html.EditorFor(model => model.CheckName2)
#Html.ValidationMessageFor(model => model.CheckName2)
</div>
my javascript function as per below, hide & show on some condition
// attach nextStep button handler
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
//check if URL2 is having any content
var val = $("#URL2").val();
if (val == "") {
$("#CheckName2").hide();
//want to remove validation here
}
else {
$("#CheckName2").show();
//want to add validation here
}
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
How can i handle validation here?
thanks in advance.
Force validation of your form with $("#IdOfFormYouEdit").validate(); or $("#IdOfTextbox").validate(); to validate only one element.
This is possible if you have put validation attributes on your view model classes. If you don't you can add validation on an element by adding the data-val attributes. For example:
<input type="text" data-val="true" data-val-number="The field someField must be a number." data-val-required="SourceId required" />

MVC 3: Why is jquery form.serialize not picking up all the controls in my form?

I am trying to create a situation where if a user clicks on an "edit" button in a list of text items, she can edit that item. I am trying to make the "edit" button post back using ajax.
Here's my ajax code:
$(function () {
// post back edit request
$('input[name^="editItem"]').live("click", (function () {
var id = $(this).attr('id');
var sections = id.split('_');
if (sections.length == 2) {
var itemID = sections[1];
var divID = "message_" + itemID;
var form = $("#newsForm");
$.post(
form.attr("action"),
form.serialize(),
function (data) {
$("#" + divID).html(data);
}
);
}
return false;
}));
});
But the form.serialize() command is not picking up all the form controls in the form. It's ONLY picking up a hidden form field that appears for each item in the list.
Here's the code in the view, inside a loop that displays all the items:
**** this is the only control being picked up: ******
#Html.Hidden(indexItemID, j.ToString())
****
<div class="datetext" style="float: right; margin-bottom: 5px;">
#Model.newsItems[j].datePosted.Value.ToLongDateString()
</div>
#if (Model.newsItems[j].showEdit)
{
// *********** show the editor ************
<div id="#divID">
#Html.EditorFor(model => model.newsItems[j])
</div>
}
else
{
// *********** show the normal display, plus the following edit/delete buttons ***********
if (Model.newsItems[j].canEdit)
{
string editID = "editItem_" + Model.newsItems[j].itemID.ToString();
string deleteID = "deleteItem_" + Model.newsItems[j].itemID.ToString();
<div class="buttonblock">
<div style="float: right">
<input id="#editID" name="#editID" type="submit" class="smallsubmittext cancel" title="edit this item" value="Edit" />
</div>
<div style="float: right">
<input id="#deleteID" name="#deleteID" type="submit" class="smallsubmittext cancel" title="delete this item" value="Delete" />
</div>
</div>
<div class="clear"></div>
}
It's not picking up anything but the series of hidden form fields (indexItemID). Why would it not be picking up the button controls?
(The ID's of the edit button controls, by the way, are in the form "editItem_x" where x is the ID of the item. Thus the button controls are central to the whole process -- that's how I figure out which item the user wants to edit.)
UPDATE
The answer seems to be in the jquery API itself, http://api.jquery.com/serialize/:
"No submit button value is serialized since the form was not submitted using a button."
I don't know how my action is supposed to know which button was clicked, so I am manually adding the button to the serialized string, and it does seem to work, as inelegant as it seems.
UPDATE 2
I spoke too soon -- the ajax is not working to update my partial view. It's giving me an exception because one of the sections in my layout page is undefined. I give up -- I can't waste any more time on this. No Ajax for this project.
You could try:
var form = $('#newsForm *'); // note the '*'
Update
Did you change the argument to $.post() as well? I think I may have been a little too simple in my answer. Just change the second argument within $.post() while continuing to use form.attr('action')
New post should look like this:
$.post(
form.attr("action"),
$('#newsForm *').serialize(), // this line changed
function (data) {
$("#" + divID).html(data);
}
);

Resources