Refresh a job in livewire - laravel

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>

Related

Can not get the value from input Livewire?

I have this form :
<div class="coupon d-flex align-items-center">
<input wire.model="coupon" type="text" class="input-text">
<button wire:click="applyCoupon" class="ml-3">#lang('site.apply_coupon')</button>
</div>
My Component:
class CouponCart extends Component
{
public $coupon;
public function applyCoupon(){
dd($this->coupon);
}
public function render()
{
return view('livewire.user.coupon-cart');
}
}
Why I always get null value when I click button ? even I fill the input!!
Because it's wire:model instead of wire.model.
You probably made a typo and added a . instead.

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

Codeigniter loop through post array

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

CodeIgniter Update Not Working

I have a form in a modal that I'm using to do an update on a record. The form seems to submit okay, the URL in the browser points to the right location (domain.net/cities/update_city/1) but no view shows up and the record is never updated. I've searched the internet but most tutorials seem to skim over the update or hardcode the id to update. I've only been using CI for a week.
Model Code
// Edit City
function edit_city($city_id) {
$data = array('city_name' => $this->input->post('city_name'));
$this->db->where('city_id', $city_id);
$this->db->update('cities', $data);
}
View Code (Form is in a modal and gets city_id added by jQuery)
<div class="modal-body">
<?php $this->load->helper('form'); ?>
<?php echo form_open('/cities/update_city/'); ?>
<label class="control-label" for="name">City</label>
<input type="text" name="city_name" id="city_name" value=""/><br />
<input type="submit" name="submit" class="btn-small btn-primary" value="Edit City" />
<button class="btn-small" data-dismiss="modal">Cancel</button>
<?php echo form_close(); ?>
</div>
<script>
// scripts for modal windows
$(document).on("click", ".edit-modal", function () {
var city_name = $(this).data('name');
var city_id = $(this).data('id');
$(".modal-body #city_name").val( city_name );
//set the forms action to include the city_id
$(".modal-body form").attr('action','/cities/update_city/'+city_id);
$('#editCityDialog').modal('show');
});
Controller Code
// Update City
function update_city($city_id) {
$this->load->model('cities_model');
if ($this->input->post('submit')) {
$data = array('city_name' => $this->input->post('city_name'));
$this->cities_model->edit_city('cities', array('city_id' => $city_id),$data);
redirect('/cities');
}
}
Here is an example, you can use it to update easily (i'm bad at english, sorry).
Model:
class Cities_model extends CI_Model{
function edit($table,$where,$data){
foreach ($where as $key => $value){
$this->db->where($key,$value);
}
$this->db->update($table,$data);
}
}
Controller:
function update_city($city_id){
$this->load->model('cities_model');
if($this->input->post('submit'){
$data = array('city_name' => $this->input->post('city_name'));
$this->cities_model->edit('cities',array('city_id' => $city_id),$data); //(table,where,data); see in model.
redirect('');
}
}
* if you go a link as "http://......update_city/2" and a function update_city($city_id), $city_id will receive as "2" and you need not to write uri_segment to get $city_id. Hope that help you
EDIT :
Controller:
function update_city($city_id) {
$this->load->model('cities_model');
if ($this->input->post('submit')) {
$this->cities_model->edit_city($city_id);
redirect('/cities');
}
}

Resources