Handling multiple dynamic forms (not inputs) in one view - Laravel - php

I have a page with a form that has dynamic inputs, where the user can add and "remove" lines. (By "removes," I mean that it removes from the front end but doesn't actually remove from the database.) The functionality works, as far as updating existing rows and adding new rows. The problem I'm having is with deleting rows.
I'd like to have a modal popup that confirms that they want to delete the row before it deletes it. My first thought was to loop through the existing rows and create a corresponding modal per row with a form, but I'm stuck on setting up the controller to recognize which form/row it's looking to delete - so to recap there's going to be one form with dynamic fields (this is the one that works right now), and there's going to be multiple dynamic forms for deleting rows.
Here's my HTML:
<form action="{{route('preliminary-children.updateChildren')}}" method="POST">
#csrf
<!-- Content Row -->
<div class="row" id="childInfo">
<!-- About Process -->
<div class="col-xl-12 col-lg-12">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-secondary">Family Information - Children</h6>
</div>
<div id="dynamic_field">
#foreach($children as $i => $child)
<div class="card-body" id="row{{$i+1}}">
#if ($i != 0)
<hr/>
<div class="text-right px-2 my-2 child-{{$i+1}}">
<a href="#" class="text-decoration-none" data-toggle="modal" data-target="#remove{{$i+1}}">
<button type="button" class="px-0 btn btn-circle btn-danger">
<i class="fal fa-times"></i>
</button>
</a>
</div>
<div class="modal fade" id="remove{{$i+1}}" tabindex="-1" role="dialog" aria-labelledby="label{{$i+1}}" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="label{{$i+1}}">Delete Row</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Are you sure you want to remove this row?</div>
<div class="modal-footer">
<button class="btn bg-gray-300" type="button" data-dismiss="modal">Cancel</button>
<form id="remove-form{{$i+1}}" name="formrow[]" action="{{route('preliminary-children.updateChildren')}}" method="POST" class="d-inline-block">
<input type="text" name="removeID[]" id="removeID{{$i+1}}" value="{{$child->id}}" hidden="hidden">
<button type="submit" id="{{$i+1}}" name="removerow[]" class="btn btn-danger text-decoration-none btn_remove">Remove</button>
</form>
</div>
</div>
</div>
</div>
#endif
<input type="text" name="userID[]" id="userID{{$i+1}}" value="{{ $user->id }}" hidden="hidden">
<input type="text" name="ID[]" id="childID{{$i+1}}" value="{{$child->id}}" hidden="hidden">
<input type="text" name="rel[]" id="rel{{$i+1}}" value="child" hidden="hidden">
<div class="form-row">
<div class="form-group col-md-6">
<label for="first">First Name</label>
<input name="first[]" type="text" class="form-control" id="first{{$i+1}}" value="{{$child->first_name}}" placeholder="First Name">
</div>
<div class="form-group col-md-6">
<label for="last">Last Name</label>
<input name="last[]" type="text" class="form-control" id="last{{$i+1}}" value="{{$child->last_name}}" placeholder="Last Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputSSN">SSN</label>
<input data-inputmask="'mask': '999-99-9999'" value="{{$child->ssn}}" type="text" class="form-control" name="inputSSN[]" id="SSN{{$i+1}}" placeholder="SSN">
</div>
<div class="form-group col-md-6">
<label for="dob">Date of Birth</label>
<input data-inputmask="'mask': '99/99/9999'" type="datepicker" value="{{$child->dob}}" class="form-control" name="dob[]" id="do{{$i+1}}B" placeholder="Date of Birth">
</div>
</div>
<div class="form-row">
<div class="form-group col-md">
<label for="inputGender">Gender</label>
<br/>
<select class="form-control d-inline-block w-25 mr-1" name="inputGender[]" id="Gender{{$i+1}}" placeholder="Gender">
#foreach($genders as $gender)
<option value="{{$gender}}" #if($child){{ ($child->gender == $gender) ? 'selected' : ''}} #endif>{{$gender}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md">
<label for="primaryHeight">Height</label>
<br/>
<select class="form-control d-inline-block w-25 mr-1" name="primaryFeet[]" id="primaryFeet{{$i+1}}">
#foreach($feet as $foot)
<option value="{{$foot}}" #if($child){{($child->height_feet == $foot) ? 'selected' : ''}} #endif>{{$foot}}</option>
#endforeach
</select>
<span class="d-inline-block w-10 mr-3">ft</span>
<select class="form-control d-inline-block w-25 mr-1" name="primaryInches[]" id="primaryInches{{$i+1}}">
#foreach($inches as $inch)
<option value="{{$inch}}" #if($child){{($child->height_inch == $inch) ? 'selected' : ''}} #endif>{{$inch}}</option>
#endforeach
</select>
<span class="d-inline-block w-10">in</span>
</div>
<div class="form-group col-md">
<label for="primaryWeight">Weight (lbs)</label>
<br/>
<input type="number" min="0" step=".1" class="form-control d-inline-block w-75 mr-1" id="primaryWeight{{$i+1}}" value="{{$child->weight_lbs}}" name="primaryWeight[]" placeholder="Weight (lbs)">
<span class="d-inline-block w-10">lbs</span>
</div>
</div>
</div>
#endforeach
</div>
<hr/>
<div class="text-center my-4">
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
</div>
</div>
</div>
</div>
<div class="form-row mb-4 text-center">
<div class="form-group col-md-12 mt-4">
Go Back <button type="submit" name="savecontinue" class="btn btn-info">Save and Continue</button>
</div>
</div>
</form>
And here's my controller:
public function updateChildren(Request $request)
{
$id = Auth::user()->id;
$user = Auth::user();
$family = UserFamily::where(['user_id'=> $id, 'rel' => 'child'])->get();
$count = count($family);
$children = ($count > 0 ? $family : '');
$input = $request->all();
$rules = [
'first[*]' => 'required',
'userID[*]' => 'required',
'rel[*]' => 'required',
'first[*]' => 'required',
'last[*]' => 'required',
'inputSSN[*]' => 'required',
'dob[*]' => 'required',
'inputGender[*]' => 'required',
'primaryFeet[*]' => 'required',
'primaryInches[*]' => 'required',
'primaryWeight[*]' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
foreach($input['userID'] as $index => $value) {
$feet = $input['primaryFeet'][$index];
$inch = $input['primaryInches'][$index];
$weight = $input['primaryWeight'][$index];
$inches = ($feet * 12) + $inch;
$bmi = number_format(((703 * $weight) / ($inches * $inches)), 2, '.', '');
if(isset($input['ID'][$index])){
$famid = $input['ID'][$index];
}else {
$famid = '';
}
if($famid > 0 || $famid != '') {
$user = UserFamily::firstOrNew(['user_id'=> $id, 'rel' => 'child', 'id' => $famid]);
}else{
$user = UserFamily::create(['user_id'=> $id, 'rel' => 'child']);
}
$user->user_id = $id;
$user->bmi = $bmi;
$user->first_name = $input['first'][$index];
$user->dob = $input['dob'][$index];
$user->last_name = $input['last'][$index];
$user->rel = $input['rel'][$index];
$user->ssn = $input['inputSSN'][$index];
$user->gender = $input['inputGender'][$index];
$user->height_feet = $input['primaryFeet'][$index];
$user->height_inch = $input['primaryInches'][$index];
$user->weight_lbs = $input['primaryWeight'][$index];
$user->save();
}
return redirect()->route('preliminary-review');
}
return redirect()->route('preliminary-children')->withErrors($validator);
}
The only thing I've tried is setting up an if/else if($request->has('savecontinue'){ ... } and wrapping my existing controller in that. The else{} would handle all the modals, but it kept kicking back errors as if all my syntax was incorrect.
Thoughts? I'm also not opposed to approaching this differently if there's a better way.
PS, there's JS for the remove and add buttons, but I didn't think it was necessary for this question. If you need me to update this with it, I can. :)

Deleting a child is a different operation than updating a child, so you should have a different method for it in your controller. Not sure about how you've got anything named, but this should give you an idea.
Define a new route:
Route::delete('/whatever/{child}', [ChildController::class, 'deleteChild'])
->name('preliminary-children.deleteChild');
Note we'll use the delete HTTP method to access this route, and the ID is passed as part of the URL.
Update your view to point to this new route:
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="label{{$i+1}}">Delete Row</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Are you sure you want to remove this row?</div>
<div class="modal-footer">
<button class="btn bg-gray-300" type="button" data-dismiss="modal">Cancel</button>
<form id="remove-form{{$i+1}}" name="formrow[]" action="{{route('preliminary-children.deleteChild', $child->id)}}" method="POST" class="d-inline-block">
<input name="_method" value="DELETE" type="hidden"/>
<button type="submit" id="{{$i+1}}" name="removerow[]" class="btn btn-danger text-decoration-none btn_remove">Remove</button>
</form>
</div>
</div>
</div>
A web browser can't send a delete request, so we spoof the method with a hidden input.
And then we make the method:
public function deleteChild(UserFamily $child)
{
$child->delete();
return response()->json("success");
}
By type hinting the parameter, Laravel automatically looks up the relevant record in the database for you. Of course you'll want to do some error checking there too.

Related

Laravel form validation doesn't work when in my controller declaring more databases

I declare a variable containing the database so that the blade can select, but when doing so, the validation does not work. Please help me. Thank you very much.
this is the variable I call in the database to use select in the blade.
public function new_department(){
//return view('admin.new-department');
$manage_faculties=DB::table('faculties')->orderBy('id','asc')->get();
$all_manage_faculties=view('admin.new-department')->with('manage_faculties', $manage_faculties);
return view('layouts.master')->with('admin.new-department', $all_manage_faculties);
}
Here is the validation I use in the insert information and database.
public function save_new_department(Request $request){
$data = [];
$data['department_name'] = $request->input('department_name');
$data['description'] = $request->input('description');
$data['faculty_id'] = $request->input('faculty_name');
if($request->isMethod('post')){
$validator = Validator::make($request->all(), [
'department_name' => 'required|min:3|max:100|unique:departments',
'description' => 'required|max:500',
]);
if ($validator->fails()) {
return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
}
DB::table('departments')->insert($data);
return redirect('/admin/departments/new')->withSuccess('Post Created Successfully!');
}
}
display it in the blade
After entering data whether it is true or false, it is not possible to report an error on the screen.After entering data whether it is true or false, it is not possible to report an error on the screen.
<form class="mt-3"method="post" action="{{ url('admin/department/new-department') }}">
{{csrf_field()}}
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title">Create a Department</h5>
</div>
<!--end of modal head-->
<div class="modal-body">
<div class="form-group row align-items-center" {{ $errors->get('name') ? 'has-error' : '' }}>
<label class="col-2">Department</label>
<input class="form-control col" type="text" placeholder="Department name" name="department_name" required/>
#foreach($errors->get('name') as $error)
<span class="help-block">{{ $error }}</span>
#endforeach
</div>
<div class="form-group row align-items-center">
<label class="col-2">Faculty</label>
<select name="faculty_name" class="form-control col" required>
<option value="" selected>Select a Faculty</option>
#foreach($manage_faculties as $key => $cate_pro)
<option value="{{$cate_pro->id}}">{{$cate_pro->faculty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group row">
<label class="col-2">Description</label>
<textarea class="form-control col" rows="10" placeholder="Write something here..." name="description" required ></textarea>
</div>
</div>
<!--end of modal body-->
<div class="modal-footer">
<button role="button" class="btn btn-primary" type="submit">
Post
</button>
</div>
</div>
</form>
You can look here for displaying errors in Laravel.
Why did you put :
{{ $errors->get('name') ? 'has-error' : '' }}
inside a "div" like a attribute ?

Unable to UPDATE data in MySQL using php any suggestions?

I am building php mysql based simple inventory management system.
Also, I have no formal knowledge about the things or assigned names like arrays, functions, etc, but I can understand.
Here is the issue, I am facing right now where needs your guidance/assistance:
As far as my knowledge, my code has to work.
I like to update my products row but can't
Affecting 0 rows using these queries:
if (isset( $_POST['prod_edit'] )) {
$prodId = $_POST['prodId'];
$pUpdate = $con->prepare("UPDATE products SET prodTeng = ? , prodTurd = ? , prodSKU = ? , prodBC = ? , prodPUPP = ? , prodPUSP = ? , prodCate = ? , prodQuan = ? WHERE prodId = ? ");
$pUpdate->bind_param("ssssssssi", $_POST['prodTeng'], $_POST['prodTurd'], $_POST['prodSKU'], $_POST['prodBC'], $_POST['prodPUPP'], $_POST['prodPUSP'], $_POST['prodCate'], $_POST['prodQuan'], $prodId);
$pUpdate->execute();
if ($pUpdate->affected_rows === 0) {
echo'<script> window.location.replace("home.php?p=inventory&alert=0"); </script>';
}
if ($pUpdate->affected_rows === 1) {
echo'<script> window.location.replace("home.php?p=inventory&alert=3"); </script>';
}
$pUpdate->close();
}
FORM:
<?php
$products_list = $con->query("SELECT * FROM products WHERE cid = '$cid' ");
while($row = $products_list->fetch_assoc()) {
$prodCate = $row['prodCate'];
$category_list = $con->query("SELECT * FROM categories WHERE cateId = '$prodCate' ");
while($cate = $category_list->fetch_assoc()) {
?>
<div class="modal fade modal-right" id="editProductRight<?=$row['prodId']; ?>" tabindex="-1" role="dialog" aria-labelledby="editProductRight<?=$row['prodId']; ?>" style="display: none;" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Product Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="home.php?p=inventory" method="post">
<div class="modal-body">
<div class="form-group mb-2">
<input type="text" class="form-control" name="prodTeng" placeholder="Name in English" required value="<?=$row['prodTeng']; ?>">
</div>
<div class="form-group mb-2">
<input type="text" class="form-control" name="prodTurd" placeholder="اردو میں نام" dir="rtl" value="<?=$row['prodTurd']; ?>">
</div>
<div class="form-group mb-2">
<input type="text" class="form-control" name="prodSKU" placeholder="SKU" required value="<?=$row['prodSKU']; ?>">
</div>
<div class="form-group mb-2">
<input type="text" class="form-control" name="prodBC" placeholder="Bar Code" value="<?=$row['prodBC']; ?>">
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">PKR</div>
</div>
<input type="number" class="form-control" name="prodPUPP" id="inlineFormInputGroupUsername2" placeholder="Per Unit Purchase Price" value="<?=$row['prodPUPP']; ?>">
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">PKR</div>
</div>
<input type="number" class="form-control" name="prodPUSP" id="inlineFormInputGroupUsername2" placeholder="Per Unit Sell Price" value="<?=$row['prodPUSP']; ?>">
</div>
<div class="form-group mb-2">
<input type="number" class="form-control" name="prodQuan" placeholder="On-Hand Quantity" value="<?=$row['prodQuan']; ?>">
</div>
<div class="form-group">
<select class="form-control" name="prodCate" required>
<option value="<?=$cate['cateId']; ?>"><?=$cate['cateTeng']; ?> | <?=$cate['cateTurd']; ?></option>
<?php
$stmt = $con->query("SELECT * FROM categories WHERE cid = '$cid' ");
while($row = $stmt->fetch_assoc()) {
?>
<option value="<?=$row['cateId']; ?>"><?=$row['cateTeng']; ?> | <?=$row['cateTurd']; ?></option>
<?php
}
$stmt->close();
?>
</select>
</div>
</div>
<hidden style="visibility:hidden;"><input type="text" value="<?=$row['prodId']?>" name="prodId" ></hidden>
<div class="modal-footer">
<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Cancel</button>
<button type="submit" name="prod_edit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
<?php
}
$category_list->close();
}
$products_list->close();
?>
If there is any suggestion or other way to do that, then please guide!
I did use print_r($_POST); and found that the prodId was in the end as shown in the question.
Then I just changed the position/location of prodId <input> tag at the top & It Works (-_-).
Results of prodId <input> tag in the end was:
Array ( [prodTeng] => asdasd [prodTurd] => Aasd [prodSKU] => asd [prodBC] => [prodPUPP] => 3 [prodPUSP] => 3 [prodQuan] => 2 [prodCate] => 1 [prodId] => 3 [prod_edit] => )
Which end up effecting 0 rows
Results of prodId tag at top was:
Array ( [prodId] => 3 [prodTeng] => asdasd [prodTurd] => Aasd [prodSKU] => asd [prodBC] => [prodPUPP] => 3 [prodPUSP] => 3 [prodQuan] => 2 [prodCate] => 1 [prodId] => 3 [prod_edit] => )
Which successfully effecting rows.

Required form field goes through with error instead of not letting to submit

I have made edit modal for competence levels on my website. Field from the form called effective_date is required input, but after pressing submit button it goes through even if the field is empty.
I want it to stop a user from submitting if the field is empty and show an error that this field is required.
I get this error instead of what I want:
send # jquery.min.js:2395
ajax # jquery.min.js:2310
postObject # forms.js:165
update # update.js:18
(anonymous) # update.js:10
dispatch # jquery.min.js:1265
q.handle # jquery.min.js:1234
forms.js:194 Uncaught ReferenceError: errorHandling is not defined
at Object.error (forms.js:194)
at i (jquery.min.js:823)
at Object.fireWith [as rejectWith] (jquery.min.js:851)
at A (jquery.min.js:2318)
at XMLHttpRequest.<anonymous> (jquery.min.js:2387)
I am talking about this part:
<div class="j-input">
<input type="date" name="effective_date_update"
id="effective_date_update" required>
</div>
Full edit-modal:
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog"
style="z-index: 1050; display: none;"
aria-hidden="true">
<div class="modal-dialog modal-lg" style="top:1%!important;" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Competence note</h4>
<button id="edit-competence-btn" type="button"
class="btn btn-sm btn-primary waves-effect waves-light f-right">
<i style="margin-right: 0;" class="icofont icofont-edit"></i>
</button>
<button type="button" class="close competence_cancel_btn close-note" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id='display-competence'>
<div class="table-responsive" style="word-break: break-word;">
<table class="table m-0">
<tbody>
<tr>
<th scope="row">{{trans('personalData.effectiveDate')}}</th>
<td>{{$practitioner_competence_level->effective_date}}</td>
</tr>
<tr>
<th scope="row">{{trans('personalData.expiryDate')}}</th>
<td>{{$practitioner_competence_level->expiry_date}}</td>
</tr>
<tr>
<p style="margin-left: 0.6em; margin-top: 1em; margin-bottom: 2em" id="notesView"></p>
</tr>
</tbody>
</table>
</div>
</div>
<div id='edit-competence' style='display: none'>
<div class="j-wrapper">
<form action="" method="post" class="j-pro j-multistep" id="updateForm">
<div class="j-content"
style="">
<div class="j-row">
<div class="j-unit">
<label class="j-label">{{trans('settings.notes')}}</label>
<div class="j-input">
<textarea name="notes_update" id="notes_update"></textarea>
</div>
</div>
<div class="j-unit">
<label class="j-label">{{trans('personalData.effectiveDate')}}*</label>
<div class="j-input">
<input type="date" name="effective_date_update"
id="effective_date_update" class="effective_date_error form-control required">
</div>
</div>
#isset($practitioner_competence_level->expiry_date)
<div class="j-unit">
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" name="expiry_date_update" id="expiry_date_update">
</div>
</div>
#endisset
<div class="j-unit">
<h6>*{{trans('auth.requiredfield')}}</h6>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer" style="padding-bottom: 1em;">
<button type="button" class="btn btn-default btn-round waves-effect modal-btn notes_cancel_btn"
data-dismiss="modal">{{trans('buttons.close')}}
</button>
<button type="button" id="update_final_btn" class="btn btn-success btn-round modal-btn"
data-dismiss="modal">{{trans('buttons.saveChanges')}}</button>
</div>
</div>
</div>
</div>
Controller for update:
public function updatePractitioner(Request $request, $id)
{
$this->validate($request, [
'effective_date' => 'required',
]
);
$selectSpecialtyOption = $_POST['practitioner_specialty_id_update'];
$fields = $request->all();
$specialtyfields = (['effective_date'=>$request->get('effective_date_specialty'), 'expiry_date'=>$request->get('expiry_date_specialty'), 'practitioner_specialty_id' => $selectSpecialtyOption]);
$primary_key = $this->PractitionerRepository->getIdName();
$primary_key_specialty = $this->PractitionerSpecialtyRepository->getIdName();
$practitioner_specialty_id = PractitionerSpecialty::where('practitioner_id', $id)->value('practitioner_specialty_id');
$fields[$primary_key] = $id;
$this->PractitionerRepository->update($fields);
$specialtyfields[$primary_key_specialty] = $practitioner_specialty_id;
$this->PractitionerSpecialtyRepository->update($specialtyfields);
return back()->with('successUpdate', 'Practitioner has been updated!');
}
Required attribute only work when submitted by <input type="submit" value="Submit">
This one will working properly
<form>
<input type="date" name="effective_date_update" required>
<input type="submit" value="Submit">
</form>
You need to make your own validation if you're not using the <input type="submit" value="Submit">
I Guess You are Submitting through javascript. For this You Have to validate Each field manually I've created a function which will validate All your fields having class validate
function validateForm() {
var validated = true;
$('.validate').each(function() {
if ( $(this).val() === '' )
validated = false;
});
return validated;
}
$("#update_final_btn").click(function(){
if(validateForm())
{
//Form is Valid Submit from here...
}else{
//Form is Not Valid
}
});
Hope it works. :)

Php form repeater post

I want to make a form using form repeater. As a result of my efforts somehow I could not register in the database.
html code:
<div class="m-portlet__body" id="myRadioGroup">
<div id="m_repeater_1">
<div class="form-group m-form__group row" id="m_repeater_1">
<div data-repeater-list="" class="col-md-12">
<div data-repeater-item class="form-group m-form__group row align-items-center">
<div class="col-md-12 m-form__group-sub">
<label class="form-control-label">Car plate</label>
<div class="input-group">
<input type="text" class="form-control" name="plate" placeholder="34 LAA 34" maxlength="10">
<div class="input-group-append">
<button data-repeater-delete="" class="btn btn-primary" type="button"><i class="la la-trash-o"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="m-form__group form-group row" style="padding-left: 48px; margin-top: -2rem;">
<div class="col-md-12">
<div data-repeater-create="" class="btn btn btn-sm btn-brand m-btn m-btn--icon m-btn--wide">
<span>
<i class="la la-plus"></i>
<span>add plate</span>
</span>
</div>
</div>
</div>
</div>
</div>
chrome looks like this in developer tools:
How should my database registration file be?
$plate = $_POST['plate'];
$sql = $db->prepare('INSERT INTO orders (plate) VALUES (?)');
$save = $sql->execute(array(
$plate,
));
The problem is in the html code, input name should be plate[1]. One possible cause is that you have id="m_repeater_1" declared twice. Make sure you are setting the template correctly first, and then you can search in all post data by using print_r($_POST); (with your current code no POST is being sent).
<input type="number" placeholder="Amount" name="repeat[0][amount]" class="form-control">
public function add()
{
$locations = $_POST['repeat'];
foreach ($locations as $key => $subValue) {
echo $subValue['amount'];
}

How to create Drop down from database in Codeigniter

Sorry, i want the create Form input using drop down from database. but i've try to created and error like this.
My Code in controller
public function ajax_add()
{
$data = array(
'date_man_activity_ra' => $this->input->post('date_man_activity_ra',TRUE),
'dd_user' => $this->mymodel->dd_user(),
'user_selected' => $this->input->post('id_user') ? $this->input->post('id_user') : '',
'id_user' => $this->input->post('id_user',TRUE),
'note' => $this->input->post('note',TRUE),
);
$insert = $this->Man_activity->save($data);
echo json_encode(array("status" => TRUE));
}
and mymodel
public function dd_user()
{
// ambil data dari db
$this->db->order_by('id_user', 'asc');
$result = $this->db->get('ops_user');
// bikin array
// please select berikut ini merupakan tambahan saja agar saat pertama
// diload akan ditampilkan text please select.
$dd[''] = 'Please Select';
if ($result->num_rows() > 0) {
foreach ($result->result() as $row) {
// tentukan value (sebelah kiri) dan labelnya (sebelah kanan)
$dd[$row->id_user] = $row->username;
}
}
return $dd;
}
and my View
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">date_man_activity_ra</label>
<div class="col-md-9">
<input name="date_man_activity_ra" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Id User</label>
<div class="col-md-9">
<?php
$dd_user_attribute = 'class="form-control select2"';
echo form_dropdown('id_user', $dd_user, $user_selected, $dd_user_attribute);
?>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Note</label>
<div class="col-md-9">
<input name="note" placeholder="note" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
how to solve it? or Another ways?
Thank You
public function ajax_add()
{
$data = array(
'date_man_activity_ra' => $this->input->post('date_man_activity_ra',TRUE),
'dd_user' => $this->mymodel->dd_user(),
'user_selected' => $this->input->post('id_user') ? $this->input->post('id_user') : '',
'id_user' => $this->input->post('id_user',TRUE),
'note' => $this->input->post('note',TRUE),
);
$insert = $this->Man_activity->save($data);
// Load your view and pass the data that you use in dropdown
//echo json_encode(array("status" => TRUE)); // Remove it
}

Categories