Query builder update() codeigniter 4 not updateing my password - php

i'd like to ask some question. I want to make a change password feature in codeigniter 4, so i have to updateing my old password, but when i do that, the password it's not updated, but all my flashdata works perfectly. I also try a normal sql query but not work too.
Where is my mistake?
When i var_dump the new hash password, the new password is hashed, but again not updating my database.
This is my model
protected $user = 'user';
public function EditKataSandi($password_hash = null){
$session = \Config\Services::session();
$id = $session->get('id');
$db = \Config\Database::connect();
$builder = $db->table($this->user);
//$queryB = "UPDATE `user` SET `sandi` = $password_hash WHERE `id` = $id
//";
// $menu = $db->query($queryB);
// return $menu;
$builder->set('sandi', $password_hash);
$builder->where('id', $id);
return $query = $builder->update();
}
my controller
protected $helpers = ['form', 'url', 'array'];
public function katasandi($page = 'katasandi'){
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$model = new Model_all();
$email = $this->session->get('email');
if (!$email){
return redirect()->to(base_url('/auth'));
}else{
$userAccess = $model->Tendang();
if ($userAccess < 1) {
return redirect()->to(base_url('/auth/blokir'));
}
}
if (! is_file(APPPATH.'/Views/admin/admin-katasandi/v_katasandi.php'))
{
// Whoops, we don't have a page for that!
throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
}
if($request->getMethod() == 'post'){
$validation->setRules([
'katasandi_sebelum' => [
'label' => 'Kata sandi sebelum',
'rules' => 'required|trim',
'errors' => [
'required' => 'Harus diisi harus diisi!'
]
],
'katasandi_baru' => [
'label' => 'Sandi Baru',
'rules' => 'required|trim|min_length[6]|matches[katasandi_baru1]',
'errors' => [
'required' => 'Harus diisi!',
'matches' => '',
'min_length' => 'Terlalu pendek!'
]
],
'katasandi_baru1' => [
'label' => 'Sandi Ulangi',
'rules' => 'required|trim|min_length[6]|matches[katasandi_baru]',
'errors' => [
'required' => 'Harus diisi!',
'matches' => 'Harus sesuai dengan kata sandi baru!',
'min_length' => ''
]
]
]);
}
$data['nama'] = $model->GetNama();
$data['title'] = ucfirst('Ubah Kata Sandi'); // Capitalize the first letter
$data['user'] = $model->UserLogin();
$data['menu'] = $model->MenuAll();
$data['attr'] = ['id' => 'katasandi', 'name'=>'katasandi'];
if($validation->withRequest($this->request)->run() == FALSE){
echo view('admin/admin-base-html/v_header', $data);
echo view('admin/admin-base-html/v_navbar', $data);
echo view('admin/admin-base-html/v_sidebar');
echo view('admin/admin-katasandi/v_katasandi', ['validation' => $validation,'session' => $this->session]);
echo view('admin/admin-base-html/v_footer');
echo view('admin/admin-base-html/v_js');
echo view('admin/admin-katasandi/v_js_katasandi');
}else{
$pass_sebelum = $request->getPost('katasandi_sebelum');
$pass_baru = $request->getPost('katasandi_baru');
if (!password_verify($pass_sebelum, $data['user']['sandi'])) {
$this->session->setFlashdata('salah', 'Kata sandi sebelumnya salah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
if ($pass_sebelum == $pass_baru) {
$this->session->setFlashdata('sama', 'Kata sandi baru tidak boleh sama dengan kata sandi sebelumnya!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
$password_hash = password_hash($pass_baru, PASSWORD_DEFAULT);
$model->EditKataSandi($password_hash);
$this->session->setFlashdata('pesan', 'Kata sandi berhasil diubah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}
}
}
}
my view
<div class="col-sm-12 col-md-12 col-lg-12">
<?php echo form_open(base_url().'/pengguna/katasandi', $attr); ?>
<?php echo csrf_field(); ?>
<div class="card card-primary">
<div class="card-header">
<h4>Ubah kata sandi</h4>
</div>
<div class="card-body">
<div class="row">
<div class="form-group col-lg-12 col-sm-12 col-md-12">
<label for="katasandi_sebelum">Kata sandi sebelumnya</label>
<input type="password" class="form-control" id="katasandi_sebelum" name="katasandi_sebelum"
placeholder="" autofocus>
<label class="text-danger"><?php echo $validation->showError('katasandi_sebelum') ?></label>
</div>
<div class="form-group col-lg-6 col-sm-12 col-md-6">
<label for="katasandi_baru">Kata sandi baru</label>
<input type="password" class="form-control" id="katasandi_baru" name="katasandi_baru" placeholder="">
<label class="text-danger"><?php echo $validation->showError('katasandi_baru') ?></label>
</div>
<div class="form-group col-lg-6 col-sm-12 col-md-6">
<label for="katasandi_baru1">Ulangi kata sandi baru</label>
<input type="password" class="form-control" id="katasandi_baru1" name="katasandi_baru1"
placeholder="">
<label class="text-danger"><?php echo $validation->showError('katasandi_baru1')?></label>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary"> Ubah Kata Sandi</button>
</div>
</div>
<?php echo form_close(); ?>
</div>
and my database structure

I found my mistake, its work when i put my update password code into a new function...
Example:
Public function updatepassword(){
$data['user'] = $model->UserLogin();
$pass_sebelum = $request->getPost('katasandi_sebelum');
$pass_baru = $request->getPost('katasandi_baru');
if (!password_verify($pass_sebelum, $data['user']['sandi'])) {
$this->session->setFlashdata('salah', 'Kata sandi sebelumnya salah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
if ($pass_sebelum == $pass_baru) {
$this->session->setFlashdata('sama', 'Kata sandi baru tidak boleh sama dengan kata sandi sebelumnya!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
$password_hash = password_hash($pass_baru, PASSWORD_DEFAULT);
$model->EditKataSandi($password_hash);
$this->session->setFlashdata('pesan', 'Kata sandi berhasil diubah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}
}

Use $allowedFields.
This array should be updated with the field names that can be set during save, insert, or update methods. Any field names other than these will be discarded. This helps to protect against just taking input from a form and throwing it all at the model, resulting in potential mass assignment vulnerabilities. protected $allowedFields = ['name', 'email'];
You can read more in the official documentation: https://codeigniter.com/user_guide/models/model.html#models

Related

am i using the password-hash/password-verify wrong on Codeigniter4

im currently learning how to make a working multi level login using code igniter using multi table because every type of user have some uniqueness and i tried to use md5 in the past but someone tell me that md5 is not save, so i try to use password-hash/password-verify but when i try to fill the login form it just telling me that the password is wrong even though i fill it with the same password "123456789" when create the account
This is my AuthController
namespace App\Controllers;
use App\Models\AdminModel;
use App\Models\GuruModel;
use App\Models\MuridModel;
use App\Models\WalimuridModel;
class Auth extends BaseController
{
public function __construct()
{
$this->adminModel = new AdminModel();
$this->guruModel = new GuruModel();
$this->muridModel = new MuridModel();
$this->walimuridModel = new WalimuridModel();
$this->validation = \Config\Services::validation();
$this->session = \Config\Services::session();
}
public function valid_login()
{
//Take data from the login form
$nama_user = $this->request->getVar('username');
$password = $this->request->getVar('password');
//Take data from database that have the same username
$admin = $this->adminModel->where('username_admin', $nama_user)->first();
$guru = $this->guruModel->where('username_guru', $nama_user)->first();
$murid = $this->muridModel->where('username_murid', $nama_user)->first();
$walimurid = $this->walimuridModel->where('username_walimurid', $nama_user)->first();
//check if username founded
if($admin){
$verify_pass = password_verify($password, $admin['password_admin']);
if($verify_pass){
$sessLogin = [
'isLogin' => true,
'username' => $admin['username_admin'],
'password' => $admin['password_admin'],
'email' => $admin['email_admin'],
'nama' => $admin['nama_admin'],
'jeniskelamin' => $admin['jenis_kelamin'],
'fotoprofil' => $admin['foto_profile'],
'level' => 'admin'
];
$this->session->set($sessLogin);
return redirect()->to('/admin/index');
}
else {
session()->setFlashdata('password', 'Password salah');
return redirect()->to('/login');
}
}
else if($guru){
if($guru['password_guru'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'username' => $guru['username_guru'],
'password' => $guru['password_guru'],
'email' => $guru['email_guru'],
'nama' => $guru['nama_guru'],
'jeniskelamin' => $guru['jenis_kelamin'],
'fotoprofil' => $guru['foto_profile'],
'level' => 'guru'
];
$this->session->set($sessLogin);
return redirect()->to('/guru/index');
}
}
else if($murid){
if($murid['password_murid'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'nisn' => $murid['nisn'],
'username' => $murid['username_murid'],
'password' => $murid['password_murid'],
'email' => $murid['email_murid'],
'nama' => $murid['nama_murid'],
'jeniskelamin' => $murid['jenis_kelamin'],
'fotoprofil' => $murid['foto_profile'],
'level' => 'murid'
];
$this->session->set($sessLogin);
return redirect()->to('/murid/index');
}
}
else if($walimurid){
if($walimurid['password_walimurid'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'username' => $walimurid['username_walimurid'],
'password' => $walimurid['password_walimurid'],
'email' => $walimurid['email_walimurid'],
'nama' => $walimurid['nama_walimurid'],
'nisnanak' => $walimurid['nisn_murid'],
'jeniskelamin' => $walimurid['jenis_kelamin'],
'fotoprofil' => $walimurid['foto_profile'],
'level' => 'walimurid'
];
$this->session->set($sessLogin);
return redirect()->to('/walimurid/index');
}
}
else{
//jika username tidak ditemukan, balikkan ke halaman login
session()->setFlashdata('username', 'Username tidak ditemukan');
return redirect()->to('/login');
}
}
this is my Admin Model
<?php
namespace App\Models;
use CodeIgniter\Model;
class AdminModel extends Model
{
protected $table = 'admin';
protected $primaryKey = 'id_admin';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ["id_admin","username_admin","password_admin","email_admin","nama_admin","jenis_kelamin","foto_profile"];
}
every model is basically the same
this is my login.php (login form)
<form method="post" action="/auth/valid_login">
<div class="wrap">
<input type="username" name="username" class="input" placeholder="username">
<span class="underline"></span><br>
<?php if($username){ ?>
<div class="alert alert-danger" role="alert">
<?php echo $username?>
</div>
<?php } ?>
</div>
<div class="wrap">
<input type="password" name="password" class="input" placeholder="Password">
<span class="underline"></span><br>
<?php if($password){ ?>
<div class="alert alert-danger" role="alert">
<?php echo $password?>
</div>
<?php } ?>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn-a">Login</button>
</div>
</form>
this is my create admin form
<form method="post" action="/admin/save_admin">
Username: <br>
<input type="text" name="username" required><br>
Password: <br>
<input type="password" name="password" required><br>
Email: <br>
<input type="email" name="email" required><br>
Nama: <br>
<input type="text" name="nama_admin" required><br>
Jenis Kelamin: <br>
<input type="text" name="jenis_kelamin" required><br>
Foto Profil: <br>
<input type="text" name="fotoprofil" required><br>
<button type="submit">Register</button>
</form>
and my create function
public function save_admin()
{
$data = $this->request->getPost();
$this->validation->run($data, 'cradmin');
$errors = $this->validation->getErrors();
if($errors){
session()->setFlashdata('error', $errors);
return redirect()->to('/admin/admin/create');
}
$password = password_hash($data['password'], PASSWORD_DEFAULT);
$this->adminModel->save([
'username_admin' => $data['username'],
'password_admin' => $password,
'email_admin' => $data['email'],
'nama_admin' => $data['nama_admin'],
'jenis_kelamin' => $data['jenis_kelamin'],
'foto_profile' => $data['fotoprofil'],
]);
session()->setFlashdata('add', 'Data Admin berhasil dibuat');
return redirect()->to('/admin/admin/index');
}
i have tried to change the requirement of login like if the password same as the database it will make session or if password wrong go to login form and make session and none of it work sorry if my english is bad

Codeigniter: Cannot upload files, Undefined Index : avatar

I cannot seem to upload files in codeigniter. I don't know if the issue lies with the if ($_FILES['avatar']['name'] == "").
My controller
private function upload_avatar($file)
{
$newName = $file->getRandomName();
$upload = $file->move(ROOTPATH . 'public/assets/avatar', $newName);
if ($upload) {
return $newName;
} else {
return false;
}
}
public function change_data()
{
helper(['form', 'url']);
$userModel = new UserModel();
if ($this->request->getMethod() == 'post') {
if ($_FILES['avatar']['name'] == "")
{
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]'
];
} else {
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]',
'avatar' => [
'uploaded[avatar]',
'mime_in[avatar,image/jpg,image/jpeg,image/png]',
'max_size[avatar,4096]'
]
];
}
if ($this->validate($rules)) {
if ($_FILES['avatar']['name'] == "") {
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
];
} else {
//get data user by session email
$user = $userModel->where('email', session()->get('email'))
->first();
if ($user) {
$deleteFile = unlink('./assets/avatar/' . $$user['avatar']);
if ($deleteFile) {
$file = $this->request->getFile('avatar');
$uploadFile = $this->upload_avatar($file);
}
}
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
'avatar' => $uploadFile,
];
}
$update = $userModel->update($user['id_user'], $params);
if ($update) {
session()->setFlashdata('success', 'Berhasil Update Data. Apabila Tampilan Data Belum Berubah, Silakan Lakukan Logout dan Login Kembali');
return redirect()->route('profile');
} else {
session()->setFlashdata('danger', 'Gagal Update Data');
return redirect()->route('edit')->withInput();
}
} else {
$data['validation'] = $this->validator;
}
}
$data['title'] = 'Edit Profile';
return view('admin/users/ubah_data', $data);
}
My view
<form action="<?= base_url('admin/user/change_data') ?>" method="POST">
<?= csrf_field(); ?>
<div class="form-group">
<label for="nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" value="<?= session()->nama ?>">
</div>
<div class="form-group">
<label for="nip">NIP</label>
<input type="text" class="form-control" id="nip" name="nip" value="<?= session()->nip ?>">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="<?= session()->email ?>">
</div>
<div class="form-group">
<label for="tempat_lahir">Tempat Lahir</label>
<input type="text" class="form-control" id="tempat_lahir" name="tempat_lahir" value="<?= session()->tempat_lahir ?>">
</div>
<div class="form-group">
<label for="avatar">Foto <small>(Optional)</small></label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="avatar" name="avatar">
<label class="custom-file-label" for="avatar">Choose file</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info" />
</div>
</form>
After i push the upload button Undefined index: avatar message appeared.
Any help will be greatly appreciated. I cannot seem to figure out why ($_FILES['avatar']['name'] == "") has problem
I think you miss to include enctype="multipart/form-data" in form tag
<form action="url-action" method="POST" enctype="multipart/form-data">
your form
</form>

Update Error - Trying to get property 'id' of non-object in Laravel 5.8

I am using Laravel-5.8 for a Web Application. I am trying to apply Rules and Requests in Laravel Validation. I have these codes:
rules
public function rules()
{
return [
'organization_code' => [
'required',
'string',
'min:2',
'max:20',
Rule::unique('org_companies', 'organization_code')->ignore($this->route('company')->id)
],
'organization_name' => [
'required',
'string',
'min:3',
'max:100',
Rule::unique('org_companies', 'organization_name')->ignore($this->route('company')->id)
],
'website' => [
'nullable',
'url',
'max:100',
Rule::unique('org_companies', 'website')->ignore($this->route('company')->id)
],
'org_image' => 'nullable|image|mimes:jpeg,bmp,png,gif|max:2048',
'total_employees' => 'nullable|numeric|digits_between:0,10',
'registration_number' => [
'nullable',
'string',
'max:50',
Rule::unique('org_companies', 'registration_number')->ignore($this->route('company')->id)
],
'phone_number' => [
'nullable',
'numeric',
'phone:NG',
Rule::unique('org_companies', 'phone_number')->ignore($this->route('company')->id)
],
'secondary_phone' => [
'nullable',
'numeric',
'phone:NG',
Rule::unique('org_companies', 'secondary_phone')->ignore($this->route('company')->id)
],
'email' => [
'nullable',
'email',
'max:80',
Rule::unique('org_companies', 'email')->ignore($this->route('company')->id)
],
'secondary_email' => [
'nullable',
'email',
'max:80',
Rule::unique('org_companies', 'secondary_email')->ignore($this->route('company')->id)
],
];
}
Controller
public function edit($id)
{
$company = OrgCompany::where('id', $id)->first();
$countries = ConfigCountries::all();
return view('organization.companies.edit')->with('company', $company)->with('countries', $countries);
}
public function update(UpdateCompanyRequest $request, $id)
{
try {
$orgStartDate = Carbon::parse($request->org_start_date);
$company = OrgCompany::find($id);
$company->organization_code = $request->organization_code;
$company->organization_name = $request->organization_name;
$company->website = $request->website;
$company->org_description = $request->org_description;
$company->total_employees = $request->total_employees;
$company->registration_number = $request->registration_number;
$company->org_start_date = $orgStartDate;
$company->phone_number = $request->phone_number;
$company->secondary_phone = $request->secondary_phone;
$company->email = $request->email;
$company->secondary_email = $request->secondary_email;
$company->country_id = $request->country_id;
if ($request->org_image != "") {
$org_image = $request->file('org_image');
$new_name = rand() . '.' . $org_image->getClientOriginalExtension();
$org_image->move(public_path('storage/companies/image'), $new_name);
$company->org_image = $new_name;
}
$company->save();
Session::flash('success', 'Company is updated successfully');
return redirect()->route('organization.companies.index');
} catch (Exception $exception) {
Session::flash('danger', 'Action failed!');
return redirect()->route('organization.companies.index');
}
}
view blade
<div class="card-body">
<form action="{{route('organization.companies.update', ['id'=>$company->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<span style="color:blue;"><h4 class="box-title"><b>Company Information</b></h4></span>
<hr class="m-t-0 m-b-40">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3"> Company Code<span style="color:red;">*</span></label>
<div class="col-md-9 controls">
<input type="text" name="organization_code" placeholder="Enter company code here" class="form-control" value="{{old('organization_code',$company->organization_code)}}">
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3"> Company Name<span style="color:red;">*</span></label>
<div class="col-md-9 controls">
<input type="text" name="organization_name" placeholder="Enter company name here" class="form-control" value="{{old('organization_name',$company->organization_name)}}">
</div>
</div>
</div>
<!--/span-->
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('organization.companies.index')}}'" class="btn btn-default">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
When I clicked on the save button to update, I got this error:
Trying to get property 'id' of non-object
Then, in the rules this code is highlighted:
Rule::unique('org_companies', 'organization_code')->ignore($this->route('company')->id)
How do I get it resolved?
Thank you.
Change
public function update(UpdateCompanyRequest $request, $id)
to
public function update(UpdateCompanyRequest $request, OrgCompany $company)
With your current route $id is just an ID and company doesn't exist.
Your rules are looking for it to be an object.
If you put OrgCompany $company Laravel will automatically find it for you.
This also allows you to simplify your entire update method.
public function update(UpdateCompanyRequest $request, OrgCompany $company)
{
try {
$orgStartDate = Carbon::parse($request->org_start_date);
// this will already be assigned and is unnecessary ->
// $company = OrgCompany::find($id);
// your request object already contains a validated, clean array.
$validated = $request->validated();
$company->fill($validated);
$company->org_start_date = $orgStartDate;
if ($request->org_image != "") {
$org_image = $request->file('org_image');
$new_name = rand() . '.' . $org_image->getClientOriginalExtension();
$org_image->move(public_path('storage/companies/image'), $new_name);
$company->org_image = $new_name;
}
$company->save();
Session::flash('success', 'Company is updated successfully');
return redirect()->route('organization.companies.index');
} catch (Exception $exception) {
Session::flash('danger', 'Action failed!');
return redirect()->route('organization.companies.index');
}
}
You can also update the signature of your edit method to automatically inject the OrgCompany in the same way.
public function edit(OrgCompany $company)
{
// already exists now -> $company = OrgCompany::where('id', $id)->first();
$countries = ConfigCountries::all();
return view('organization.companies.edit')->with('company', $company)->with('countries', $countries);
}

Codeigniter (Inserting category data into table)

I am new to CodeIgniter, I carried out an e-commerce project left by the former developer. The case is that the category data is not inserting into my table.
The code is very long in both controller and model but I cut it out and posted only the necessary part of it.
This is my controller.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Category extends Admin_Controller {
public function create()
{
/* Breadcrumbs */
$this->breadcrumbs->unshift(2, "New Category" , 'admin/category/create');
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
/* Validate form input */
$this->form_validation->set_rules('cat_name', 'Category Name', 'trim|required');
if ($this->form_validation->run() == TRUE)
{
$config['upload_path'] = './assets/uploads/category/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'png,jpeg';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "icon";
if ( ! $this->upload->do_upload($img))
{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/category');
}
else
{
$data=$this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/category/'.$file['file_name'];
$data = array(
'category_name' => $this->input->post('cat_name'),
'category_photo' => $photo,
'category_description' => $this->input->post('cat_desc')
);
$this->category_model->insertcategory($data);
//$this->ion_auth->messages()
$this->session->set_flashdata('message', "Successfully inserted!");
redirect('admin/category', 'refresh');
}
}
else
{
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->template->admin_render('admin/category/create', $this->data);
}
}
This is my model.
class Category_model extends CI_Model
{
function insertcategory($data) {
$query = $this->db->insert('category', $data);
if ($query) {
return true;
} else {
return false;
}
}
This is my form.
<div class="box-body">
<span style="color:red"><?php echo $message;?></span>
<?php echo form_open_multipart(current_url(), array('class' => 'form-horizontal', 'id' => 'form-create_user')); ?>
<div class="form-group">
<span class="col-sm-2 control-label">Category Name</span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cat_name" placeholder="Category Name" name="cat_name" required>
</div>
</div>
<div class="form-group">
<span class="col-sm-2 control-label">Category Description</span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cat_desc" placeholder="Description" name="cat_desc" >
</div>
</div>
<div class="form-group">
<span class="col-sm-2 control-label">Category Icon</span>
<div class="col-sm-10">
<input class="input-file uniform_on" id="icon" name="icon" type="file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn-group">
<?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-primary btn-flat', 'content' => lang('actions_submit'))); ?>
<?php echo form_button(array('type' => 'reset', 'class' => 'btn btn-warning btn-flat', 'content' => lang('actions_reset'))); ?>
<?php echo anchor('admin/category', lang('actions_cancel'), array('class' => 'btn btn-default btn-flat')); ?>
</div>
</div>
</div>
<?php echo form_close();?>
</div>
Could you please replace $img = "icon"; with $img = $this->input->post('icon');
Please check with the above data.
Also please post the error message you are getting.

Codeigniter - form_validation callback function error message

View:
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<form method="post" action="<?php echo base_url();?>account/register">
<?php $form_error = $this->session->flashdata('error'); ?>
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" type="input">
<div id="form_error"><?php echo $form_error['username']; ?></div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" id="password" name="password" type="password">
<div id="form_error"><?php echo $form_error['password']; ?></div>
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password</label>
<input class="form-control" id="confirm_password" name="confirm_password" type="password">
<div id="form_error"><?php echo $form_error['confirm_password']; ?></div>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select class="form-control" id="gender" name="gender">
<option disabled selected value="">select a gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<div id="form_error"><?php echo $form_error['gender']; ?></div>
</div>
<div class="form-group">
<label for="birthdate">Birthdate</label>
<input class="form-control" id="birthdate" name="birthdate" type="date">
<div id="form_error"><?php echo $form_error['birthdate']; ?></div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="<?php echo base_url();?>pages/login_user">Already have an account?</a>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
Account Controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date');
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
echo 'aw';
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{
echo $birthdate;
$this->form_validation->set_message('valid_date', 'Invalid Birthdate');
$form_error['birthdate'] = form_error('valid_date');
$this->session->set_flashdata('error',$form_error);
return FALSE; }
}
Pages Controller:
public function login_user(){
$data['title'] = 'Login';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/login');
$this->load->view('template/footer');
}
public function register_user(){
$data['title'] = 'Register';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/registration');
$this->load->view('template/footer');
}
I tried setting flashdata inside the callback function but this is my first time using a callback function to check the validity of the birthdate given. I tested out the input and you can't input any alphabets but you can go over the maximum length. For example the format should be 'YYYY-MM-DD' you can input something like this: 555555-55-55.
All my other error prints out successfully but the valid_date callback function prints an error:
Unable to access an error message corresponding to your field name
Birthdate.(valid_date)
If what i'm asking for is impossible/wrong then i'll just add a min_length[10] and max_length[10] and just edit its error to 'invalid date'.
EDIT: Taking inspiration from my statement above about the max and min length, i also added a custom error for the valid_date there and what do you know it works.
Heres my updated controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date',
array('valid_date' => 'Invalid Date of birth'));
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{return FALSE; }
}
I'm still not sure if it really works or just by fluke.
Register code:
public function register() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
if ($this->form_validation->run() == FALSE) {
// let's see what's going on under the hood...
print_r($this->form_validation->error_array());
exit;
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
} else {
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d', time()),
'last_login' => mdate('%Y-%m-%d', time()));
if ($this->account_model->create_account($data)) {
$this->session->set_flashdata('message', 'Registration Successful');
redirect('pages/login_user');
} else {
$this->session->set_flashdata('message', 'Registration Failed');
redirect('pages/register_user');
}
}
}
Referencing a callback necessitates the function be called via callback_func_name.
Revised callback:
Note: item does not start with callback_
See: Correctly determine if date string is a valid date in that format (read: test cases)
public function valid_date($date) {
$format = 'Y-m-d';
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) == $date) {
return TRUE;
} else {
$this->form_validation->set_message('valid_date', 'Invalid Birthdate.');
return FALSE;
}
}
Doing date('YYYY-MM-DD') is wrong as it yields: 2018201820182018-FebFeb-SatSat. See date docs.
You should call this way:
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
hey try this to use callback
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_validdate',
//form_validation callback
public function validdate($birthdate){
$birthdate = $this->input->post('birthdate');
if( date('YYYY-MM-DD',strtotime($birthdate)) )
{
return true;
}
$this->form_validation->set_message('validdate','Check the birthday input to match a format like this YYYY-MM-DD');
return false;
}
Callbacks: Your own Validation Methods
The validation system supports callbacks to your own validation methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback method that does that
More Detail read https://codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

Categories