Codeigniter loop through post array - codeigniter

So i have this form:
<form id="stepform" action="#" method="post">
<fieldset>
<legend>Step #1</legend>
<label>Title</label>
<input type="hidden" name="csrf_modo" value="b94961394f8e6f7efaa4e37ca9007822">
<input type="text" name="field[]" class="input-xlarge">
<label>Body</label>
<textarea class="input-xlarge" name="field[]"></textarea>
</fieldset>
</form>
When user clicks a button jquery dynamically appends another two exactly same fields:
count = 2;
$("#addstep").click(function(){
$('#stepform').append('<legend>Step #' + (count++) + '</legend>');
$('#stepform').append('<label>Title</label><input type="text" name="field[]" class="input-xlarge">');
$('#stepform').append('<label>Body</label><textarea class="input-xlarge" name="field[]"></textarea>');
$('#addstep').scrollintoview();
return false;
});
As you can see one step has 2 fields, when user clicks on the button step increments and adds another 2 fields to that step and so on...
After that i send data to the controller via ajax request. Now i'm stuck on the actual query which should insert new row for every step. How could i accomplish this?
Btw i'm using codeigniter and it's bind queries:
$this->db->query($sql, $data);

Update
I corrected the handling of the difference between textareas and input fields.
Sidenote: The whole Controller logic belongs into a model. I just put it into the Controller here for simplification reasons.
HTML
<form id="stepform" action="#" method="post">
<fieldset>
<legend>Step #1</legend>
<label>Title</label>
<input type="hidden" name="csrf_modo" value="b94961394f8e6f7efaa4e37ca9007822">
<input type="text" name="field[input][]" class="input-xlarge">
<label>Body</label>
<textarea class="input-xlarge" name="field[textarea][]"></textarea>
</fieldset>
</form>
JS
count = 2;
$("#addstep").click(function(){
$('#stepform').append('<legend>Step #' + (count++) + '</legend>');
$('#stepform').append('<label>Title</label><input type="text" name="field[input][]" class="input-xlarge">');
$('#stepform').append('<label>Body</label><textarea class="input-xlarge" name="field[textarea][]"></textarea>');
$('#addstep').scrollintoview();
return false;
});
PHP
class SomeController extends MY_Controller{
public function process_request()
{
$insert_data = array();
$field_data = $this->input->post('field');
for($i = 0; $i < count($field_data['input']); $i++)
{
$insert_data[] = array(
'db_col_name_input' => $field_data['input'][$i],
'db_col_name_textarea' => $field_data['textarea'][$i]
);
}
$this->db->insert_batch('my_table', $insert_data);
}
}
Old Answer:
Since you're appending square brackets to your input fields name you will get an array with the values of all fields that are having this name. So you can go trough them with a foreach loop and store all the values in an array and use CodeIgniters insert_batch() Method to insert multiple data at the same time.
class SomeController extends MY_Controller{
public function process_request()
{
$insert_data = array();
foreach($this->input->post('field') AS $field)
{
$insert_data[] = array(
'db_col_name' => $field
)
}
$this->db->insert_batch('my_table', $insert_data);
}
}

Related

Laravel insert multiple records in pivot table from arrays

I'm trying to save multiple records(rows) in a table. The html fields are dynamic fields and declared as array, so they can be 1, 2 or more.
My blade:
<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">
<div class="input-group mb-3">
<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">
<input type="text" name="fromNr[]" class="form-control m-input" placeholder="From" autocomplete="off">
<input type="text" name="toNr[]" class="form-control m-input" placeholder="to" autocomplete="off">
<div class="input-group-append">
<button id="removeRow" type="button" class="btn btn-danger">X</button>
</div>
</div>
+
My JS to create dynamic fields:
$("#addRow").click(function () {
var html = '';
html += '<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">';
html += '<div class="input-group mb-3">';
html += '<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">';
html += '<input type="text" name="fromNr[]" class="form-control m-input" laceholder="From" autocomplete="off">';
html += '<input type="text" name="toNr[]" class="form-control m-input" placeholder="To" autocomplete="off">';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
My Offer.php Model:
protected $fillable = ['some columns];
public function table()
{
return $this->hasMany(Table::class);
}
My Table.php Model:
protected $fillable = ['offer_id','tableName','fromNr','toNr'];
public function offer()
{
return $this->hasMany(Offer::class);
}
Now, in my Controller, I have to get request input values and then save into Table table. The input values can be more than 1 and dynamically.
My tries:
public function store(Request $request)
{
$statement = DB::select("SHOW TABLE STATUS LIKE 'offer'");
$nextId = $statement[0]->Auto_increment;
$tableName = $request->get('tableName');
$fromNr = $request->get('fromNr');
$toNr = $request->get('toNr');
$offer = Offer::find($nextId);
$offer->table()->saveMany([
new Table(['restaurant_offer_id' => $nextId]),
new Table(['tableName' => $tableName]),
new Table(['fromNr' => $fromNr]),
new Table(['toNr' => $toNr]),
]);
}
Thank you in Advance.
If you want to make it dynamic you have to loop over the input array.
$tables = [];
foreach($tableName as $key => $value) {
$table = new Table;
$table->tableName = $tableName[$key];
$table->fromNr = $fromNr[$key];
$table->toNr = $toNr[$key];
$tables[] = $table;
}
$offer->table()->saveMany($tables);
If you use name="example[]" on the view, you are receiving the variable as an array in the controller. Also if you use Eloquent Model binding you can save the model instance to the database with simpler syntax.
Try something like this in the controller:
public function store(Request $request)
{
foreach($request->tableName as $key => $tableName)
{
Offer::create(['tableName' => $tableName',
'fromNr' => $request->fromNr[$key],
'toNr' => $request->toNr[$key]])
}
}
Additionally I recommend to use plural naming in case of arrays. Like tableNames, fromNrs. So you know that it should contain multiple variables.

Refresh a job in livewire

I have two inputs in livewire view. When a value is entered in the first input, a calculation is performed in the component based on the data received from the api and the value in the first input, the result of which is displayed in the second input. Now I want that calculation to be done again every ten seconds and displayed in the second input. According to the livewire documentation, I used the poll, but only the view was refreshed and the new value was not displayed.I will put the codes below.
inputs :
<input wire:model="unit" type="text" class="form-control form-control-xl" style="text-align: center" value="0">
</br>
<input id="toman" type="text" style="text-align: center" class="form-control form-control-xl">
component:
<?php
namespace App\Http\Livewire\Frontend\Order;
use App\Models\Currency;
use App\Models\Network;
use Livewire\Component;
class Buy extends Component
{
public $currencySelect ='btc';
public $unit;
public function mount()
{
$this->unit = 0;
}
public function updatedUnit()
{
$this->validate([
'unit' => 'numeric',
]);
if ($this->unit !== ''){
$this->dispatchBrowserEvent('changeToman', [
'toman' => calculatPrice($this->currencySelect , $this->unit),
]);
}
}
public function render()
{
$currencies = Currency::where('buy_status', 'active')->get();
return view('livewire.frontend.order.buy')->with('currencies', $currencies);
}
}
and this for set value in second input:
<script>
window.addEventListener('changeToman', event => {
$('#toman').val(new Intl.NumberFormat('ir-IR', { maximumSignificantDigits: 3}).format(event.detail.toman));
});
</script>
I assume that calculatPrice is a public method of the component. Don't understand well how every 10 seconds will perform this function if any change in first input is done.
public $calculated, $unit;
public function reCalculate()
{
if($this->unit) { // if input unit has value call the method and assign value
$this->calculated = $this->calculatPrice($this->currencySelect , $this->unit);
}
}
//......
<div wire:poll.10000ms="reCalculate"> // every 10 sec call the method
<input wire:model="unit" type="text" class="form-control" style="text-align: center">
{{ $calculated }}
</div>

How to Make Joomla 3x Custom Toolbar Button Work

I am trying to add a couple of custom toolbar buttons to my component, and at the moment the buttons are showing alright but can't get them to work.
My main problem is how to pass the id variable from the view layout to the sub-controller to perform a task in the case update a single column in the database.
These are my code structure
THE VIEW (view.html.php)
class LoanmanagerViewLoan extends JViewLegacy
{
protected $loanDetail;
public function display($tpl = null){
//Data from loanlist Model
$model=$this->getModel('Loan');
$this->loanDetail = $model->get_loan_detail();
$this->addToolbar();
parent::display($tpl);
}
protected function addToolbar()
{
// Get the toolbar object instance
$bar = JToolbar::getInstance('toolbar');
JToolBarHelper::Title(JText::_('Loan Details'));
//TRYING TO MAKE THIS BUTTON WORK
JToolBarHelper::custom('loan.approve', 'approve.png', 'icon-save.png', 'Approve Loan', false, false);
JToolBarHelper::custom('loan.deny', 'deny.png', 'deny.png', 'Deny Loan', false, false);
}
}
VIEW LAYOUT (tmpl/default.php)
JHtml::_('behavior.formvalidator');
<form action="<?php echo JRoute::_('index.php?option=com_loanmanager&view=loan&type=softloan&id='. (int) $loan->id); ?>" method="post" name="adminForm" id="loan-form" enctype="multipart/form-data">
<input type="hidden" name="option" value="com_loanmanager" />
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
SUBCONTROLLER (controllers/loan.php)
class LoanmanagerControllerLoan extends JControllerLegacy
{
public function approve()
{
$jinput = JFactory::getApplication()->input;
$id = $input->post->get('id', 0, 'INT');
//Perform some SQL query with the $id
return parent::display();
}
}
you need to write an input with the id in the form itself.
<input type="hidden" name="id" value="<?= (int) $loan->id ?>" />
alternatively, don't get the id from post, as you have put it in the action get url of the form
$id = $input->getInt('id');

how to Pass array from view to controller in Laravel?

I make a form in blade.php, Here I can select multiple checkbox, and I want to pass selected input’s value to controller in a array.But I failed, I can not send the data.
Here is code from view. The selected input’s value can be 1,2 etc;
<form method="post" action="{{action('votesubmitController#votesubmit')}}" class="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($candidate_list[$post_list->id] as $candidate_list[$post_list->id])
<li>
<input type="checkbox" name= "selected[]" value= {{
$candidate_list[$post_list->id]->id }}>
<label>
<!-- some code here -->
</label>
</li>
#endforeach
<button type="submit" id="login-button">Submit</button>
</form>
Here is route-
Route::post('/votesubmit','votesubmitController#votesubmit');
If I write return $input in controller I find –
{"_token":"TQIUxVz0LjzM84Z7TaUPk3Y7BLZPjmXUyhXhlQfp","selected":
["1","2"]}
That’s I need. I do not know how to get selected value. When I get specific route error exception happens . and says "Undefined variable: selected".
Here is my Controller’s code-
class votesubmitController extends Controller
{
public function votesubmit()
{
$input = Input::all();
// return $input;
foreach ($selected as $selected) {
echo $selected;
}
}
}
// You can try this
class votesubmitController extends Controller
{
public function votesubmit()
{
//$input = Input::all();
//$selected = $input['selected'];
$selected = Input::get('selected');
foreach ($selected as $selected)
{
echo $selected;
}
}
}
Either use
$selected = $input['selected']
Or
pass it using Ajax.

Array field always stores the last value of the field into database

Help me working with array inputs on my project.
This is the form field:
<form action="" method="">
<input type="text" class="form-control" name="scores[]">
<input type="hidden" name="lesson_id[]" value="">
<input type="hidden" name="year_id" value="">
<input type="hidden" name="grade_id" value="">
<input type="hidden" name="clas_id" value="">
<input type="hidden" name="student_id" value="">
</form>
My Controller:
public function store(Request $request)
{
foreach ($request->scores as $score)
{
$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
foreach($request->lesson_id as $lesson)
{
$scr->lesson_id = $lesson;
}
$scr->score = $score;
$scr->save();
}
}
My Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Assestment extends Model
{
protected $table = 'assestments';
protected $fillable = [
'year_id', 'grade_id', 'clas_id', 'student_id', 'lesson_id', 'score',
];
public function students()
{
return $this->belongsToMany('App\Models\Student');
}
}
I would like to make the value of field "scores[]" and "lesson_id[]" as array so that they store multiple data to database.
But when I submit the form, the "lesson_id[]" always store the last value of the form. For example, the field "lesson_id[]" contains multiple values like "1, 2, 3 , 4", but the value stored into database is always "4 (the last value of the field)".
What should I do?
Only the last value is stored because you stored the data after foreach loop.
If you want to store the socres[] and lesson_id[] as an array in the same table, you can use serialize()
$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
$scr->lesson_id = serialize($request->lesson_id);
$scr->score = serialize($request->$score);
$scr->save();
To retreive each value, use unserialize()

Resources