I currently have a form which includes a drop down menu that has menu items taken from a database.
What I'm looking to achieve is to allow the user to select one of these values and add it to the database.The form is currently submitting and inserting properly except for the database. When I try to add the drop down value to the database all input comes back as null. If I take it out, it works fine though.
<form name = "form1" id = "form1" method ="post"> <!--action="<?php echo base_url()."index.php/Admin/create_user"; ?>"-->
<?php echo validation_errors(); ?>
<label for="first_name" class = "labelForm">First Name:</label>
<input type="text" id="first_name" name="first_name" class = "input2">
<label for="last_name" class = "labelForm">Last Name:</label>
<input type="text" id="last_name" name="last_name" class = "input2">
<label for="username" class = "labelForm">Username:</label>
<input type="text" id="username" name="username" class = "input2" onblur="check_if_exists();">
<label for="password" class = "labelForm">Password:</label>
<input type="password" id="password" name="password" class = "input2" onblur="validatePassword();">
<label for="passconf" class = "labelForm">Password:</label>
<input type="password" id="passconf" name="passconf" class = "input2" onblur="checkPasswords();">
<label for="email" class = "labelForm">Email:</label>
<input type="text" id="email" name="email" class = "input2">
<!-- <label for="hospital" class = "labelForm">Hospital:</label>
<select name="product" class = "input2" id = "hospitals">
<option selected disabled hidden style='display: none' value=''></option>
<?php foreach($hospital_dropdown as $option){?>
<option id = "hospitals" name="hospitals" value="<?php $option->hospitalName;?>"> <?php print_r($option->hospitalName); ?> </option>
<?php }?>
</select>-->
<label for="hospitals" class = "labelForm">Hospital:</label>
<select name="product" class = "input2" id = "hospitals">
<?php foreach($hospital_dropdown as $index => $option):?>
<option id = "hospitals_<?=$index?>"
name="hospitals"
value="<?=$option->hospitalName;?>"
><?=$option->hospitalName;?></option>
<?php endforeach;?>
</select>
<button type="button" id = "new_user_submit">Add New User</button>
</form>
Controller:
function create_user(){
$this->load->model('User_model');
$password = $this->input->post('password');
$hash = $this->bcrypt->hash_password($password);
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'username' => $this->input->post('username'),
'password' => $hash,
'class' => $this->input->post('userclass'),
'hospital' => $this->input->post('hospitals'),
'email' => $this->input->post('email'),
);
$this->User_model->create_user($data);
$username = $this->session->userdata('username');
$data['hospital_dropdown'] = $this->User_model->hospital_dropdown();
$data['main_content'] = 'admin';
$this->load->view('includes/admin/template', $data);
}
Model:
function create_user($data){
$insert = $this->db->insert('users', $data);
return $insert;
}
If I take out the hospital part in the controller it submits fine but when I leave it in , all the fields come back as null and won't submit.
Any Ideas?
Thanks!
You have several mistakes in your php part of the mark-up:
create a unique id: <option id = "hospitals" > is not unique
you need to echo out the option value, right now it is empty
you use print_r() to echo out your hospitalName. Normally, in your scenario you do that with echo(). print_r is useful to test variable content, see more here
there are other syntax to mix php with your mark-up, CodeIgniter suggest these:
the <select></select> tag has missing/wrong name attribute, see here. You are using the name attribute "product" instead, but in you controller you write 'hospital' => $this->input->post('hospitals')
resuming: below should fix your issue(s)
<select name="hospitals" id="hospitals">
<?php foreach($hospital_dropdown as $index => $option):?>
<option value="<?=$option->hospitalName;?>">
<?=$option->hospitalName;?>
</option>
<?php endforeach;?>
</select>
Related
In my controller, I have my create record method, but I want to edit existing records, but only update the fields that are filled out. I try to only fill out one or two fields on the edit property file, but no matter what field I fill out, it returns the same error:
Attempt to assign property "property_title" on null
Update method in my controller:
public function update(Request $request, $id)
{
// Find the record
$prop = Property::find($id);
if ($request->hasFile('prop_img')) {
$file = $request->file('prop_img');
$filenameWithExtension = $file->getClientOriginalName();
$Extension = $file->getClientOriginalExtension();
$filenameOnly = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
$filename = $filenameOnly . time() . '.' . $Extension;
$file->move('property_images', $filename);
$prop->property_image = $filename;
}
$prop->property_title = $request->input('prop_title');
$prop->property_description = $request->input('prop_desc');
$prop->bedrooms = $request->input('prop_beds');
$prop->bathrooms = $request->input('prop_baths');
$prop->square_feet = $request->input('prop_ft');
$prop->finished_basement = $request->input('prop_basement');
$prop->prop_tax = $request->input('prop_tax');
$prop->heat_type = $request->input('prop_heat');
$prop->water_heater = $request->input('prop_waterheater');
$prop->year_built = $request->input('prop_year');
$prop->save();
return view('admin.properties');
}
Routes:
Route::group(['prefix' => 'admin'], function() {
Route::get('/', function() {
return view('admin.dashboard');
})->name('admin')->middleware('auth');
Route::get('/properties', [PropertiesController::class, 'index'])->name('all-properties')->middleware('auth');
Route::get('/properties/create', [PropertiesController::class, 'create'])->middleware('auth');
Route::post('/properties/store-property', [PropertiesController::class, 'store'])->name('admin.store_properties')->middleware('auth');
Route::get('/properties/delete/{id}', [PropertiesController::class, 'destroy'])->middleware('auth');
// Edit property
Route::get('/properties/edit/{id}', [PropertiesController::class, 'edit'])->name('admin.edit')->middleware('auth');
Route::post('/properties/update/{id}', [PropertiesController::class, 'update'])->middleware('auth');
});
Edit properties blade file:
#extends( 'layouts.admin' )
#section( 'content' )
<h1 class="admin-header">Edit Listing</h1>
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
<form method="POST" action="/admin/properties/update/{id}" class="add_edit_property_form" enctype="multipart/form-data">
#csrf
<div>
<label for="prop_title">Property Title</label>
<input type="text" name="prop_title" id="prop_title" />
</div>
<div>
<label for="prop_desciption">Property Description</label>
<textarea name="prop_desc" id="prop_desc"></textarea>
</div>
<div>
<label for="prop_img">Property Image</label>
<input type="file" name="prop_img" id="prop_img" />
</div>
<div>
<label for="prop_beds">Number of Bedrooms</label>
<input type="number" name="prop_beds" id="prop_beds" steps="1" min="1" />
</div>
<div>
<label for="prop_baths">Number of Bathrooms</label>
<input type="number" name="prop_baths" id="prop_baths" />
</div>
<div>
<label for="prop_ft">Sqaure Feet</label>
<input type="number" name="prop_ft" id="prop_ft" />
</div>
<div>
<label for="props_basement">Finished Basement?</label>
<select name="prop_basement" id="prop_basement">
<option value="" selected disabled>Select an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label for="prop_tax">Property Tax</label>
<input type="number" name="prop_tax" id="prop_tax" />
</div>
<div>
<label for="props_heat">Heat Type</label>
<select name="prop_heat" id="prop_heat">
<option value="" selected disabled>Select an option</option>
<option value="gas">Gas</option>
<option value="oil">Oil</option>
<option value="electric">Electric</option>
</select>
</div>
<div>
<label for="props_waterheater">Finished Basement?</label>
<select name="prop_waterheater" id="prop_waterheater">
<option value="" selected disabled>Select an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label for="prop_year">Year Built</label>
<input type="number" name="prop_year" id="prop_year" />
</div>
<button type="submit">Add New Listing</button>
</form>
#endsection
Edit method code:
public function edit($id)
{
return view('admin.edit_property');
}
Results of var_dump
var_dump($id):
string(5) "{$id}"
var_dump($request::all()):
array(8) { ["_token"]=> string(40) "9QOxw20xoy1mEDD6BTWZEJtMpgl3rC16ACejvtcU" ["prop_title"]=> string(4) "Test" ["prop_desc"]=> NULL ["prop_beds"]=> NULL ["prop_baths"]=> NULL ["prop_ft"]=> NULL ["prop_tax"]=> NULL ["prop_year"]=> NULL }
$prop = Property::find($id);
var_dump($prop):
NULL
this error means that this line
$prop = Property::find($id);
returns null, almost because a null value passed to the $id variable
due to the missing $ sign at the action of the edit form, also the variables at the blade should be with double curly braces
So
1- you need to change this line
<form method="POST" action="/admin/properties/update/{id}" class="add_edit_property_form" enctype="multipart/form-data">
to this and it should work with you
<form method="POST" action="/admin/properties/update/{{$id}}" class="add_edit_property_form" enctype="multipart/form-data">
i just added $ sign and in double curly-braces {{$id}}
2- you need to update your edit method, you need to pass the $id parameter to the view
so, you need to update this method
public function edit($id)
{
return view('admin.edit_property');
}
to
public function edit($id)
{
return view('admin.edit_property')->with('id',$id);
}
or to
public function edit($id)
{
return view('admin.edit_property')->with(compact('id'));
}
I'm using form_open() for open form but form method is always showing get.
echo $this->request->getMethod() showing always get.
generated HTML is:
<form action="http://darkadmin.com/admin" method="post" accept-charset="utf-8">
<input type="hidden" name="_csrf" value="45435e3abd2d067883dacd6f62280fa7" />
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>
View:
<?php if(isset($validation)) { ?>
<?php echo $validation->listErrors(); ?>
<?php } ?>
<?php echo form_open(current_url().'admin'); ?>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<?php echo form_close(); ?>
Controller:
<?php
namespace App\Controllers;
class Login extends BaseController
{
public function __construct(){
helper(['form', 'url']);
}
public function index()
{
$rules = [
'fname' => 'required',
'lname' => 'required'
];
echo $this->request->getMethod();
if($this->request->getMethod() == 'post' && $this->validate($rules)){
echo 'Success';
} else {
$this->data['validation'] = $this->validator;
}
return view($this->data['config']->theme.'login_view',$this->data);
}
}
How can I solve this problem? Please help me
I have form where I am planning to insert data into units table .. it has fields course_id | unit_number | unit_title
relationship defined : course has many units .. units belongs to course.
the form is working fine, in case I'm inserting only one unit. but when I insert multiple rows it only stores the last row.
#include('admin.messages')
<form action="{{ route('adminSendCreateUnits')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="row col-12">
<div class="col-sm">
<div class="form-group">
<label style="width:100%; background-color:grey; color:white; padding:15px;" for="course_id">Course</label>
<select name="course_id" class="form-control">
<option>Select Course</option><!--selected by default-->
#foreach ($courses as $course)
<option value="{{$course->id}}">
{{ $course->id}}-{{ $course->crs_title}}
</option>
#endforeach
</select>
</div>
</div>
</div><br>
<label for="unit_number">Unit Number</label>
<select name="unit_number[]" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="10">10</option>
</select>
<label for="unit_title">Unit Title</label>
<input type="text" class="form-control" name="unit_title[]" id="unit_title" placeholder="Unit Title" required>
my unitscontroller.php [ I'm sure this is wrong .. since I was trying stuff and i lack the knowledge]
public function adminSendCreateUnit(Request $request){
$course_id = $request->input('course_id');
$unit_number = $request->input('unit_number', []);
$unit_title = $request->input('unit_title', []);
$newCategoryArray = array(
"course_id"=>$course_id,
"unit_number"=>$unit_number,
'created_at' => \Carbon::now(),
"unit_title"=> $unit_title);
$created = DB::table("units")->insert($newCategoryArray);
if($created){
return redirect()->route("adminAllUnits")->withSuccess('Unit Created successfully!');
}else{
return "Unit was not Created";
}
}
I would like to have the course ID same in all rows .. only Unit number and titles change. would appreciate any input :)
Solved by trying this out.
public function adminSendCreateUnit(Request $request){
$course_id = $request->input('course_id');
$unit_number = $request->input('unit_number', []);
$unit_title = $request->input('unit_title', []);
$units = [];
foreach ($unit_number as $index => $unit) {$units[] = [
"course_id" => $course_id, // change this
"unit_number" => $unit_number[$index],
'created_at' => \Carbon::now(),
"unit_title" => $unit_title[$index]
];
}
$created = Unit::insert($units);
if($created){
return redirect()->route("adminAllUnits")->withSuccess('Unit Created successfully!');
}else{
return "Unit was not Created";
}
}
I have prepared the form to be inputted to the database, but specifically for multiple checkboxes. I've found a similar case with the solutionbut not with the algorithm that I use
Here it is my controller
class Ruang extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model("m_ruang");
$this->load->library('form_validation');
if($this->session->userdata('status') != "login"){
redirect(base_url("login"));
}
}
public function index()
{
$data["ruang"] = $this->m_ruang->getAll();
$this->load->view('admin/ruang/index.php', $data);
}
public function add()
{
$ruang = $this->m_ruang;
$validation = $this->form_validation;
$validation->set_rules($ruang->rules());
if ($validation->run()) {
$ruang->save();
$this->session->set_flashdata('success', 'Berhasil ditambahkan');
}
$this->load->view("admin/ruang/add_ruang");
}
Here it is my models
class M_ruang extends CI_Model
{
private $_table = "ruang";
public $id_ruang;
public $ruang;
public $kapasitas_kuliah;
public $kapasitas_ujian;
public $layout;
public $fasilitas;
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["id_ruang" => $id])->row();
}
public function save()
{
$post = $this->input->post();
$this->id_ruang = uniqid();
$this->ruang = $post["ruang"];
$this->kapasitas_kuliah = $post["kapasitas_kuliah"];
$this->kapasitas_ujian = $post["kapasitas_ujian"];
$this->layout = $post["layout"];
$this->fasilitas = $post["fasilitas"];
$this->db->insert($this->_table, $this);
}
and here part of form view
<form action="<?php base_url('ruang/add') ?>" method="post" enctype="multipart/form-data" >
<div class="form-group">
<label for="ruang">Nama Ruang</label>
<input class="form-control <?php echo form_error('ruang') ? 'is-invalid':'' ?>"
type="text" name="ruang" placeholder="Masukkan nama ruangan" />
<div class="invalid-feedback">
<?php echo form_error('ruang') ?>
</div>
</div>
<div class="form-group">
<label for="kapasitas_kuliah">Kapasitas Kuliah</label>
<input class="form-control <?php echo form_error('kapasitas_kuliah') ? 'is-invalid':'' ?>"
type="number" name="kapasitas_kuliah" min="0" placeholder="Tentukan kapasitas kuliah" />
<div class="invalid-feedback">
<?php echo form_error('kapasitas_kuliah') ?>
</div>
</div>
<div class="form-group">
<label for="kapasitas_ujian">Kapasitas Kuliah</label>
<input class="form-control <?php echo form_error('kapasitas_ujian') ? 'is-invalid':'' ?>"
type="number" name="kapasitas_ujian" min="0" placeholder="Tentukan kapasitas ujian" />
<div class="invalid-feedback">
<?php echo form_error('kapasitas_ujian') ?>
</div>
</div>
<div class="form-group">
<label for="layout">Layout</label>
<input class="form-control"
data-inputmask="'mask': ['99 x 99']" data-mask
type="text" name="layout" placeholder="Tentukan layout ruangan" />
</div>
<div class="form-group">
<label for="fasilitas">Fasilitas Tersedia</label> <br>
<input type="checkbox" name="fasilitas[]" value="Proyektor"> Proyektor
<br>
<input type="checkbox" name="fasilitas[]" value="Papan Tulis"> Papan Tulis
<br>
<input type="checkbox" name="fasilitas[]" value="Jam Dinding"> Jam Dinding
<br>
<input type="checkbox" name="fasilitas[]" value="AC"> AC
<br>
<input type="checkbox" name="fasilitas[]" value="Kipas Angin"> Kipas Angin
<br>
<input type="checkbox" name="fasilitas[]" value="Tong Sampah"> Tong Sampah
<div class="invalid-feedback">
<?php echo form_error('fasilitas') ?>
</div>
</div>
<input class="btn btn-success" type="submit" name="btn" value="Save" />
</form>
This really hinders my project, I hope someone can help
You can use the following line too :
$fasilitas = implode(',', $this->input->post( 'fasilitas' , TRUE ) );
If you can save fasilitas in your database as string. Then you can implode fasilitas array with comma separated as shown below:
$this->fasilitas = implode(',',$post["fasilitas"]);
it will stored in back-end side(Database) something like that.
Proyektor,Papan Tulis
I hope this will works for you.
You Can Use This to Get fasilitas as array :
$fasilitas = $this->input->post('fasilitas'); // Like array('AC','Proyektor','Kipas Angin');
In order for you to get all the checked boxes store in database, write this code.
$values = $post['fasilitas'];
$fasilitas = "";
foreach($values as $val)
{
$fasilitas .= $val . ", ";
}
Then store $fasilitas to db.
$data = array(
'fasilitas' => $fasilitas,
);
$this->db->insert('table_name', $data);
Hope that helps :)
I have a users table and a services table. I made a many-many pivot table to store which user offers which services. When I try to check or uncheck a service checkbox in my profile blade to modify the user the data is not inserted or removed in the pivot table.
User Model:
public function services(){
return $this->belongsToMany(Service::class);
}
Service Model:
public function user(){
return $this->belongsToMany(User::class);
}
My code in store function in ProfileController:
$user = Auth::user();
if(isset($request->services)){
foreach($request->services as $service_id){
$service=Service::find($service_id);
$service->user()->syncWithoutDetaching($user->id);
}
}
Blade:
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right">Type de services</label>
<label for="peinture">Peinture</label>
<input type="checkbox" id="peinture" name="services[]" value="1"
<?php if (in_array(1, $services->toArray())) echo "checked" ?> >
<label for="neige">Déneigement</label>
<input type="checkbox" id="neige" name="services[]" value="2"
<?php if (in_array(2, $services->toArray())) echo "checked" ?> >
<label for="gardiennage">Gardiennage</label>
<input type="checkbox" id="gardiennage" name="services[]" value="3"
<?php if (in_array(3, $services->toArray())) echo "checked" ?> >
<label for="entretien">Entretien paysager</label>
<input type="checkbox" id="entretien" name="services[]" value="4"
<?php if (in_array(4, $services->toArray())) echo "checked" ?> >
</div>
If I do dd($request); everything seems in it. No clue what I'm doing wrong, thanks for any help.
you don't need to iterate the services in your controller. just do this:
$user = Auth::user();
$user->services()->sync($request->services);
this will first clean the pivot table, then will attach the new values all at once.
i really encourage you not to use $request values without validating them. in this case run this before start syncing the pivot table:
$this->validate($request, [
'services' => 'required|array',
'services.*' => 'exists:services,id',
]);