Codeigniter: How do I pass multiple inputs with multiple same names? - codeigniter

First off, thank you for your valuable time and interest - any input to a beginner is greatly appreciated!
How do I insert multiple inputs with (in most cases) multiple same names? Here is my code:
View:
//Simplified version, original is a jquery append script
Passes: <input type="text" name="passes[]">
Points: <input type="text" name="points[]">
Passes: <input type="text" name="passes[]">
Points: <input type="text" name="points[]">
Controller:
//Loops through a table like form for inputting stats
function add_stat() {
$i = 0;
foreach ($this->input->post('points') as $points) {
$dataSet1[$i++] = array (
'points' => $points
);
}
foreach ($this->input->post('passes') as $passes) {
$dataSet2[$i++] = array (
'passes' => $passses
);
}
//Not sure how to pass multiple arrays, or if even possible
$this->sport_model->insert_stat($dataSet1, $dataSet2);
}
Model:
//Passing multiple params error out due to "String to Array Conversion"
function insert_stat($dataSet1, $dataSet2) {
$this->db->insert_batch('table', $dataSet1, $dataSet2);
return $this->db->insert_id();
}

set your controller and model as:
controller:
//Loops through a table like form for inputting stats
function add_stat() {
$points = $this->input->post('points');
$passes = $this->input->post('passes');
for($i=0;$i<sizeof($points);$i++)
{
$dataSet[$i] = array ('points' => $points[$i], 'passes' => $passses[$i]);
}
// $dataSet is an array of array
$this->sport_model->insert_stat($dataSet);
}
model:
function insert_stat($dataSet)
{
$this->db->insert_batch('table', $dataSet);
return $this->db->insert_id(); // this will return the id of last item inserted.
}

First, insert_batch() only takes two params: the table name and a data set.
Second, insert_id() isn't going to do you much good on a batch insert, but that's not a huge deal.
I assume you want points and passes to be in the same record, and that you're appending another set of points/passes inputs via JS.
View:
Passes: <input type="text" name="scores[0][passes]">
Points: <input type="text" name="scores[0][points]">
Passes: <input type="text" name="scores[1][passes]">
Points: <input type="text" name="scores[1][points]">
// etc...
In your controller, you would then just use one $dataSet array and loop through $this->input->post('scores')
When $dataSet is complete, you'd batch insert with $this->db->insert_batch('table', $dataSet)

Related

How to create dynamic url in Spring Thymeleaf

#GetMapping("/deposit")
public String deposit(#RequestParam("amount") double amount,#RequestParam ("id") int id) {
if (amount > 0) {
accountService.deposit(id, amount);
}
return "redirect:/account";
}
I have two parameters that I need to send from my html file, my problem is that 'amount' parameter should be coming from html file. How can I dynamically do that?
<input type="number" id="amount">
<a th:href="#{/account/deposit(id=${account.id}, amount=????)}">Deposit</a>
I want to put the input value into amount in th:href would appreciate any help.
As it is mentioned by #andrewJames it would be mush easier to submit this value using form. For example:
In your HTML
<form th:action="#{/account/deposit(id=${account.id})}" method="post">
<input type="number" id="amount" name="amount">
<button type="submit">Deposit</button>
</form>
In your Controller
#PostMapping( "/deposit" )
public String onDepositSubmit( #RequestParam Long id, #RequestParam Integer amount ) {
if (amount > 0) {
accountService.deposit(id, amount);
}
return "redirect:/account";
}
This would be the easiest solution. However, it is possible to dinamically alter a link as at the client-side the link is already rendered to a normal link (e.g. /account/deposit?id=12345), so you can manipulate it using JS as you wish, for example something like this (using JQuery):
<input type="number" id="amount">
<a th:href="#{/account/deposit(id=${account.id},amount=0)}" id="amount_link">Deposit</a>
<script>
let amountInput = $( '#amount' )
let amountLink = $( '#amount_link' )
amountInput.keyup( function() {
let url = new URL( amountLink.attr( 'href' ) );
url.searchParams.set( 'amount', amountInput.val() )
amountLink.attr( 'href', url.toString() )
} )
</script>
Which would create a keyup event listener on input and update link every time the character is typed or deleted. However, this is needlessly complicated and as such is considered a bad practice.

How to send the values of checked items in a dynamic list from a database displayed in a view to controller?

How to send the values of checked items in a dynamic list from a database displayed in a view to controller ?
A concrete solution depends on your data, but if you are talking about a list of checkboxes, you can give them a common name in array notation:
<form type="post" action="...">
#foreach($elements as $elem)
<input type="checkbox" name="my_input[{{ $elem->id }}]" value="1">
#endforeach
</form>
On the server-side, you can then query the data like this:
use Illuminate\Http\Request;
class MyController
{
public function postData(Request $request)
{
$myInput = (array) $request->get('my_input', []);
// ... remaining logic
}
}
The line $myInput = (array) $request->get('my_input', []); will read the POST variable my_input as array and, if no such post variable is given, an empty array will be returned. In other words, $myInput will always be an array, where the key is $elem->id and the value '1' as defined by value="1".

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

preg_replace() laravel -Insert array in database

I have this error :
ErrorException in helpers.php line 748:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
SerialController.php
public function createSerial(Request $request)
{
$serial = new Serial();
$serial->nume_serial = $request['numeSerial'];
$serial->claritate = $request['claritate'];
$serial->aparitie = $request['aparitie'];
$serial->genuri = $request['genuri'];
$serial->save();
return redirect('/admin');
}
view
<div class="checkbox">
SF<input type="checkbox" name="genuri[1]" value="sf" id="">
Biografic<input type="checkbox" name="genuri[2]" value="biografic" id="">
Animat<input type="checkbox" name="genuri[3]" value="animat" id="">
</div>
I guess a problem is you're trying to insert an array into a DB table.
$serial->genuri = $request['genuri']; // it's an array
You could convert an array to a json data:
$serial->genuri = json_encode($request['genuri']);
Of course you have to change genuri data type to JSON:
$table->json('genuri');
Apparently from looking at your view, $request['genuri'] is an array, and the error is this line $serial->genuri = $request['genuri']; since you are assigning an array to an object property that is string (I think?) in your DB table.
Not sure what you are trying to accomplish, if you provide more info I might help more.

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

Resources