Laravel 5.1, update multiple values from checked checkbox - laravel

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();
}

Related

Laravel: Textbox value is not getting received

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.

Get next and previous records in laravel

how to get next and previous records using buttons instead of href,
for example
<form method="post" action="/">
//Question and options will come here,
//when click on next button next question should appear and
// if I click on prev button it should goto prev question
<button type ="submit">Next Question
<button type ="submit">Previous Question
</form>
my Controller
$questions = Question::find($qId);
$options = Question::find($qId)->options;
$previous = Question::where('id', '<', $questions->id)->max('id');
$next = Question::where('id', '>', $questions->id)->min('id');
return view('Pages/User/Questions/Question2')
->with('options',$options)
->with('questions',$questions)
->with('previous',Question::find($previous))
->with('next',Question::find($next));
Now How to send next and prev id on the button submit.
You can do it like this:
You need to add value to button and on submit value will be submitted as well. So, You can get desired record.
<form method="post" action="/">
// your question content
<input name="qId" value="{{$question_id}}" hidden>
<button type ="submit" name="option" value="0">Previous </button>
<button type ="submit" name="option" value="1">Next </button>
</form>
Now, You have to check which button is clicked by using option value,
public function getQuestion(Request $request){
if($request->option==0){
// Get previous record using $request->qId
}else{
// Get Next record using $request->qId
}
// Write code here to return data
}
Hope you understand,

Meteor, Session values and reactivity

I recall reading somewhere that one of the nice things about Session variables in Meteor was that when you changed a Session variable, anywhere that you used Session.get for that variable would react to the new value. I have a form where if the user cancels out of adding a new record I set that Session variable back to the last document in the collection, #2 in my case, but the form stays on the never added new record #3.
Here is my basic form;
<template name="transactions">
<form id="trx_form">
{{#each currentVal}}
Trx No. <input type="text" value="{{trx_num}}" id="trx_num" readonly>
Amount: <input type="text" value="{{trx_amount}}" id="trx_amount">
<input type="submit" value="Save" id="save_trx">
<input type="button" value="Cancel" id="cancel_trx">
{{/each}}
</form>
</template>
The Session variable gets set to the last record in the collection in a seperate navigation form Session.set('trx_DB_currentID', trx_DB_currentID)
This is what gets the values of that document;
Template.transactions.currentVal = function() {
var currValues = {trx_num: '', trx_amount: '''};
var trxCursor = trx.find({"_id": Session.get('trx_DB_currentID')});
trxCursor.forEach( function(rec) {
currValues.trx_num = trx.find({"userID": Meteor.userId()}).count();
currValues.trx_amount = rec.trx_amount;
});
var array = [];
array[0] = currValues;
return array;
};
Everything up to this point works fine. Here is the event for clicking the cancel button;
'click #cancel_trx': function(theEvent, theTemplate) {
// Change trx_DB_currentID to last record
var trxCursor = trx.find({"userID": Meteor.userId(), 'trx_num': trx.find({"userID": Meteor.userId()}).count()});
trxCursor.forEach( function(rec) {
Session.set('trx_DB_currentID', rec._id);
});
}
I can see in the console that trx_DB_currentID is indeed set to the id for record #2 but the form still shows a blank record #3. If I click go back one record on my navigation form it brings up record #1. So why doesn't my form react to trx_DB_currentID being set to record #2?

MVC3: Geting values of cloned objects

I have a drop down list with options from a model; and I want to add a similar drop down list when the user clicks on a button. My drop down list and button are defined as
<div id="parent">
<div class="id">
#Html.DropDownListFor(m =>m.mymodel)
</div>
</div>
<input type="button" value="submit" onclick="JSFunc()"/>
And the function, JSFunc() is
var control = document.getElementById('id').cloneNode( true );
document.getElementById( 'parent' ).appendChild( new );
How can I get the value of the clone objects from the controller?
You must set the name attribute of a newly-created <select> to something unique that matches a parameter name in your controller.
(or parameter property name, or anything else depending on the model binder and your situation)

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.
};
}

Resources