fill form fields from relationship model in vform vue laravel - laravel

I have used vue vform for my form, here is the function to edit modal,
editModal(household){
this.form.reset();
$('#addNewHouseholdModal').modal('show');
this.form.fill(household); // this line fills the form with data to be edited
}
But I have form fields for which data is stored in another table. I have received the data but mnot able to figure out how to display them in the form. Please help me with it. Below is the household data i have passed in my form above.
id: 1
address_details_id: 14
ward: 2
house_no: "2"
family_no: "45"
geolocation: "{"latitude":"1.1","longitude":"1.1"}"
address_details: Object
id: 14
province: "23"
name: "Strret"
All details are filled in the form except Address details which is an object, how do I fill name from address details in the form? Thank you. Help will be appreciated.

I think you need to pass first the data before you open the modal.
editModal(data) {
isEditting = true
this.form.family_no = data.family_no
this.form.house_no = data.house_no
this.form.address = data.address
$('#addNewHouseholdModal').modal('show');
}
and then you form must be like this
<modal>
<input type="text" v-model="form.family_no" />
<input type="text" v-model="form.house_no" />
<input type="text" v-model="form.address" />
<modal>

Related

Retrieve dynamically generate check box array values in controller

in my html i can able to add more fields using jquery and the field am generating is check box array. i need to retrieve this in my controller.
so far i have tried
<input type="checkbox" value="1" name="washing[]" id="washing[]">
<input type="checkbox" value="1" name="dryclean[]" id="dryclean[]">
In controller
$clothtypeid = $request->input('clothtypeid');
$washing = $request->input('washing');
$pressing = $request->input('pressing');
for($i=0;$i<count($clothtypeid);$i++){
//in here how to test if the checkbox is ticked then value=1 else 0 ??
}
I expect if the checkbox is ticked then i have to make 1 else 0
Thanks in Advance
So I did a bit of digging and found this Tutorial which suggests;
Setting the input type to "checkbox" like you did there..
Keep the same name and include the '[]' at the end of the name attribute so that you have the following in your form;
<input type="checkbox" name="check_list[]" value="washing">
<input type="checkbox" name="check_list[]" value="dryclean">
Then in the controller you can get the value by doing the following;
if(!empty($request['check_list'])){
// Loop through array to get the checked values.
foreach($request['check_list'] as $item){
//do something here like;
if($item == 'washing'){ //make db operation or assign to a variable..}
else if($item == 'dryclean'){//make db operation}
}
}
This is a very basic example as you can see and I have to say that I haven't tested it yet but I believe it will work. Try it and give feedback.
EDIT: There is an answer here

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 make Dojo as generic while submitting a form?

I have the following dojo (ver 1.9) code:
require(["dojo/dom", "dojo/on", "dojo/request", "dojo/dom-form"],
function(dom, on, request, domForm){
var form = dom.byId('user_login');
var selectedTabId = showIdOfSelectedTab();
// Attach the onsubmit event handler of the form
on(form, "submit", function(evt){
// prevent the page from navigating after submit
evt.stopPropagation();
evt.preventDefault();
// Post the data to the server
request.post("login1.php", {
// Send the username and password
data: domForm.toObject("user_login"),
// Wait 2 seconds for a response
timeout: 2000
}).then(function(response) {
dom.byId(selectedTabId).innerHTML = response;
});
});
}
);
And html below:
<form name="user_login" id="user_login">
User name: <input type="text" name="user_name" id="user_name" /><br />
Password: <input type="password" name="user_password" id="user_password" /><br />
<button id="submitbutton" name="submitbutton">Submit</button>
</form>
I want to make the above dojo code as generic by sending the post action (login1.php) and the form id (i.e., user_login). I tried several ways but I could not achieve it.
Please let me know if any of you have idea.
Thanks in advance.
-Uday
This is the demo drom the dojo Tutorial right?
http://dojotoolkit.org/documentation/tutorials/1.9/ajax/
Did you get any Errormessages?
So let's see.
Have you load the dojo libary correct? If not, the widgets can't be loaded.
Must be somthing like:
src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js">
Check the path to the login1.php.
If it's in another Folder than your code the path must be something like "../myfolder /myphp/login1.php"
Regards, Miriam

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.

Validate a Hidden Field

I'm using MVC3 with unobtrusive validation. I have a field that the user is expected to fill with some data and then press a "search" button. If search has never been pressed or the user has changed the input field after pressing search, the form should not be possible to submit.
I've added a hidden field that is set to true by the click() event of the button and emptied by the keyup() event of the input box. Now I would like to add a validation rule that requires the hidden field to be true to allow submit.
Preferably I would like to use unobtrusive validation, but if that doesn't work it is ok with something that requires some javascript, as long as it doesn't spoil the unobtrusive validation for the rest of the form.
The following code snippet does exactly what I want, until I add type="hidden".
<input class="required" id="client-searched" data-val="true"
name="ClientSearched" data-val-required="Press search!"/>
<span class="field-validation-valid" data-valmsg-replace="true"
data-valmsg-for="ClientSearched"/>
try
var validator = $("#myFormId").data('validator');
validator.settings.ignore = "";
Here is an informative blog post
EDIT
#RAM suggested a better solution please FOLLOW
I had a similar problem, and I used this code to change defaults, in MVC 4:
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$.validator.setDefaults({
ignore: ""
})
</script>
Source:
JQuery validate
In some cases you want just ignore validation on one or several
hidden fields (not all hidden field) in client side and also you want validate them and other hidden fields in server side.
In these cases you have validation attributes for all hidden fields in your ViewModel and they will be used to validate the form when you post it (server side).
Now you need a trick to just validate some of the hidden fields in client side (not all of them). In these cases i recommend you to use my mechanism!
Set data-force-val as true in the target hidden input tags. It's our custom attribute that we use to detect target hidden inputs witch we want validate them in client side.
// This hidden input will validate both server side & client side
<input type="hidden" value="" name="Id" id="Id"
data-val-required="The Id field is required."
data-val="true"
data-force-val="true">
// This hidden input will validate both server side & client side
<input type="hidden" value="" name="Email" id="Email"
data-val-required="The Email field is required."
data-val="true"
data-force-val="true">
// This hidden input just will validate server side
<input type="hidden" value="" name="Name" id="Name"
data-val-required="The Neme field is required."
data-val="true">
Also you can set data_force-val for your hidden inputs by jQuery:
$("#Id").attr("data-force-val", true); // We want validate Id in client side
$("#Email").attr("data-force-val", true); // We want validate Email in client side
$("#Name").attr("data-force-val", false); // We wont validate Name in client side (This line is not necessary, event we can remove it)
Now, active data-force-val="true" functionality by some simple codes like these:
var validator = $("#TheFormId").data('validator');
validator.settings.ignore = ":hidden:not([data-force-val='true'])";
Note: validator.settings.ignore default value is :hidden

Resources