I have two input fields that a user can repeat to insert multiple records in a single form submission. I'm currently using a foreach loop to loop through one of those inputs and grab the value however now I need to loop through both inputs at the same time to save the data together.
I want to loop through both the input-type & input-label together and save the stored values to the db.
I guess I could create two foreach loops but that just seems like a horrible way to go about things.
Form -
<form method="post" action="{{ route('savePage') }}">
{{ csrf_field() }}
<ul class="field-list">
<li v-for="(input, index) in inputs">
<input type="text" name="input-type[]" v-model="input.one" style="display: none">
<input type="text" name="input-label[]" v-model="input.two" placeholder="Label name">
<p><span class="codesnippet">text</span></p>
<button class="p-btn secondary" #click.prevent="deleteRow(index)" >Remove field</button>
</li>
</ul>
<button>Submit</button>
</form>
Controller -
public function saveAtt(Request $request)
{
foreach ($request->input('input-label') as $label) {
$field = new Attribute;
$field->page_id = 1;
$field->label = $label;
$field->type = 2;
$field->save();
}
return redirect()->route('indexPage');
}
Use this:
$types = $request->input('input-type');
foreach ($request->input('input-label') as $i => $label) {
$field = new Attribute;
$field->page_id = 1;
$field->label = $label;
$field->type = $types[$i];
$field->save();
}
Related
Created a drop down menu that is supposed to work as a filter. I am filtering with enum values so not sure how to make it work. The view + route are working fine. When the button is pressed the URL changes and adds the selected enum value /dropdown?filter_status=inactive. But the results are not filtered.
View:
<div class="container d-flex justify-content-start">
<div class="row">
<div class="col-md-12">
<form action="{{ route('dropdownView') }}" method="GET">
<div class="form-group">
<div>
<span>
<select class="mb-2" name="filter_status" >
<option value="Status" disabled selected>Status</option>
#foreach ($enumoption as $status)
<option value="{{ $status }}">{{$status}}</option>
#endforeach
</select>
<button type="submit" class="btn btn-primary btn-sm ms-1 mb-1">Filter</button>
</span>
</div>
</div>
</form>
</div>
</div>
</div>
Route:
Route::get("/dropdown", [CompetitionController::class, 'index'])->name('dropdownView');
Controller(getPossibleEnumValues is the function I am using in my model to get the enum values)
$enumoption = Competition::getPossibleEnumValues('competitions','status');
EDIT:
public static function getPossibleEnumValues($table, $column) {
$type = DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[0]->Type ;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$enum = array();
foreach( explode(',', $matches[1]) as $value )
{
$v = trim( $value, "'" );
$enum = Arr::add($enum, $v, $v);
}
return $enum;
}
I'm having a problem to insert a single data from my database
Example: I have two data's which is the question1 with ID:1 and question2: with ID:2. Those 2 questions does have different button. The problem is once I click the question1 or question2 button it inserting both of the ID's in my database.
Like this:
Here's My Controller
$data['posts'] = $this->Post_Model->get_posts();
$this->load->view('templates/header');
$this->load->view('posts/index', $data);
$this->load->view('templates/footer');
$this->load->library('form_validation');
if($this->form_validation->run()==FALSE) {
if($this->input->post("add")) {
$this->Post_Model->count_up();
redirect('posts');
}
}
My Model
function count_up(){
for($i=0; $i<count($this->input->post('hidden')); $i++){
$data = array(
'post_id' => $this->input->post("hidden[$i]")
);
$this->db->insert("userspost", $data);
}
}
My View
<?php
$iq = 0;
$i = 0;
$arrtry = array();
foreach($posts->result() as $post){
?>
<br>
<div class="card card-nav-tabs">
<div class="card-header card-header-primary">
<!-- colors: "header-primary", "header-info", "header-success", "header-warning", "header-danger" -->
<div class="nav-tabs-navigation">
<input class="form-control" value="<?php echo $arrtry[$iq++] = $post->id; ?>" name="hidden1[<?php $i; ?>]" type="hidden">
<input class="btn btn-primary" type="submit" name="add" value="UP" />
</div>
</div>
</div>
<?php
$i++;
}
?>
My problem is i want to insert question2 ID without inserting question1 ID. Hope you guys can help thanks!
What is happening is that you have all your inputs within the same form with multiple submit buttons.
I can imagine a few ways you could solve this:
Ajax way. Require some JS and another controller method.
One form for each button: So you will always have one $this->input->post('hidden'). No need to iterate over it.
With only one form You could set the button for something like this:
<input class="btn btn-primary" type="submit" name="add-up" value="<?= $i; ?>" />
So on your controller/model you can get the index that was clicked:
/* controller/model */
$index = $this->input->post('add-up');
$hidden_value = $this->input->post("hidden")[$index]
I'm new to laravel. I'm saving some checkbox value to the database using loop the loop work but it only saves the last value in the array to the database.
this is my form
<form action="{{url('resortf')}}" method="post" enctype="multipart/form-data">
<input hidden name="h_id" value="{{ $hotel->id}}">
#foreach($facility as $facilities)
<div class="col-md-4">
<img src="{{$facilities->image}}" width="50px" height="50px;">
<label>{{$facilities->name}}</label>
<input type="checkbox" value="{{$facilities->id}}" name="facilities[]">
</div>
#endforeach
<div class="row">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-success" value="Next">
<input type="reset" class="btn btn-success" value="Reset">
</div>
</form>
form working fine; $facilities and $hotel are passed from the controller.
this is the store function
public function store(Request $request) {
$resortfacility = new Resortfacility;
$loop = $request->get('facilities');
foreach ($loop as $value){
$resortfacility->h_id = $request->get('h_id');
$resortfacility->f_id = $value;
$resortfacility->save();
}
}
is there any other way to do this that works?
Your problem occurs because you create one instance of Resortfacility, and then you fill in its values and save. The problem is, every time you perform changes to this object in a loop, you are updating existing object and that's why there is only one record in your database, the last one from the loop.
Try making new instance of Resortfacility inside the loop like this:
public function store(Request $request) {
$loop = $request->get('facilities');
foreach ($loop as $value){
$resortfacility = new Resortfacility;
$resortfacility->h_id = $request->get('h_id');
$resortfacility->f_id = $value;
$resortfacility->save();
}
}
The other answer is correct but, bulk insertion might be helpful, as creating new object within foreach loop will make query for every record.
public function store(Request $request)
{
$facilities = $request->get('facilities');
$data=array();
foreach($facilities as $facility)
{
$data[] =[
'f_id' => $facility,
'h_id' => $request->get('h_id'),
];
}
}
Resortfacility::insert($data);
I've got 2 models (producten and voorraad), and one controller (producten).
So i've build a form inside the producten CRUD (create/update).
This is a custom form:
<div class="form-group">
<span class='btn btn-default addOption'>Optie toevoegen</span>
</div>
<div class='opties'>
</div>
<div class="form-group">
Verkrijgbaar als backorder?
<select name="backorder">
<option value="1">Ja</option>
<option value="0">Nee</option>
</select>
</div>
This is very easy. If you press on the button addOption, it will add a few form inputs.
Now when the form is being saved (here the trouble begins), it will always add the data from the form to the database. But i don't want that. I want the data to be checked first, if it already exsists, if so, it has to be replaced and not added again.
Is there a yii function for that, or how do I do this?
ProductenController piece:
foreach($_POST as $key => $value){
if(substr($key, 0,5) == 'maat_'){
$index_expl = explode('_',$key);
$index = $index_expl['1'];
$aantal = $_POST['aantal_'.$index];
$maten = explode(',',$value);
foreach($maten as $maat_key => $maat){
$kleuren = explode(',',$_POST['kleur_'.$index]);
foreach($kleuren as $kleur_key => $kleur){
$voorraad = new Voorraad();
$voorraad->product_id = $model->id;
$voorraad->maat = $maat;
$voorraad->kleur = $kleur;
$voorraad->aantal = $aantal;
$voorraad->backorder = (int)$_POST['backorder'];
$voorraad->save();
}
}
}
}
Replace the following :
$voorraad = new Voorraad();
with :
$voorraad = Voorraad::model()->findByPk($model->id); // assuming id is primary key, you can also use `findByAttributes`
if($voorraad == null) $voorraad = new Voorraad();
$voorraad->save(); is also used for updating the record.
just put a hidden input field in your form:
<div class="form-group hidden">
<input name="id" value="<?php echo YOURID;?>"/>
</div>
check if id exist in your server with empty(),if not just add;if exist then update.
What I'm trying to do is get the available credits from the users table and 'credits' field and get the price of the current item in the foreach loop which is the 'normalprice' field in the 'items' table.
When a user fills in the amount he wants to put toward the 'normalprice' of an item, i want to subtract from the number in his 'credits' field, and create a new variable for 'This is the price of the item after you've put credits toward it' and display it.
The users table and items table are on a many-to-many relationship, and i've been able to display a user item by doing
$user->item
What i've done is bellow is wrong, because 'normalprice' in '$item->normalprice;' is not a property. I'm trying to find out how I can make $itemprice equal the value of 'normalprice' in the current #foreach ($user->items as $item)
Controller:
public function allocateCredit(){
$validator = Validator::make(Input::all(),
array(
'puttoward' => 'Integer',
));
$user = Auth::user();
$items = Item::all();
$userItems = Auth::user()->items;
$itemprice = $item->normalprice;
$available = $user->credits;
$goodtogo = ($available > $itemprice) ? TRUE : FALSE;
if($goodtogo === true){
$howmuch = Input::get('puttoward');
$newavailable = $howmuch - $available;
$itembalance = $itemprice - $howmuch;
$user->credits = $newavailable;
}
if($user->save()){
return Redirect::route('account')->with('global', 'Success.');
}
}
View:
#foreach ($user->items as $item)
<div class="sep">
<div class="nameIt">
{{ $item->name }}
<form action="{{ URL::route('allocate-credits-post') }}" method="post" role="form">
<div class="form-group">
<label for="exampleInputPassword1">Allocate credits</label>
<input type="intiger" class="form-control" name="puttoward" placeholder="$0.00">
</div>
<button type="submit" class="btn btn-default">Submit</button>
{{ Form::token() }}
</form>
Since you're using a form submission to call your Controller, why don't you populate the $item->normalprice into the form as hidden type like:
<input type="hidden" name="NormalPrice" value="{{$item->normalprice}}">
Then access the value in your controller with Input::get('NormalPrice')
or if that is not desired for security reason, then you can populate the $item->id instead and find out the price for that ID in your controller.