Membuat Halaman Profile
Kita akan melanjutkan pembahasan dengan membuat halaman profile user, nantinya user dapat merubah gambar profile, nama dan juga dapat merubah password. Baiklah teman-teman semua silahkan ikuti setiap bagian pada artikel ini.
Menambahkan Gambar default.png
Buatlah folder /img/profile di dalam folder public dan salin gambar dengan nama file default.png, seperti gambar berikut:
![]() |
Gambar default.png |
Meng-update Controller Profile
Karena kita pernah membuat controller profile sebelumnya, maka kita akan menambahkan beberapa fungsi di dalamnya seperti fungsi untuk mengubah profile (nama, gambar profile) dan password. Silahkan pelajari dan salin kode berikut ke dalam Controller Profile.php
Baris kode Profile.php
php
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\Modeluser;
class Profile extends BaseController
{
public function index()
{
// menuju profile/index
$data['judul'] = "Halaman Profile";
return view('profile/index', $data);
}
public function tampildata()
{
$email = session()->get('email'); //get id_role dari session
//akses database
$db = \Config\Database::connect();
$get_user = $db->query("SELECT user.id_user, user.nama, user.email, user.foto, role.role FROM user JOIN role WHERE role.id_role=user.id_role AND user.email='$email'");
$data['user'] = $get_user->getRow();
$msg = [
'data' => view('profile/dataprofile', $data)
];
echo json_encode($msg);
}
public function editdata()
{
if ($this->request->isAJAX()) {
$id_user = $this->request->getVar('id_user');
//data user
$user = new Modeluser($this->request);
$data['user'] = $user->find($id_user);
$msg = [
'sukses' => view('profile/modaledit', $data)
];
echo json_encode($msg);
} else {
exit('Maaf, tidak dapat diproses');
}
}
//update data
public function updatedata()
{
if ($this->request->isAJAX()) {
$validation = \Config\Services::validation();
$valid = $this->validate([
'nama' => [
'label' => 'Nama',
'rules' => 'required',
'errors' => [
'required' => '{field} tidak boleh kosong'
]
],
'foto' => [
'label' => 'Foto',
'rules' => ['is_image[foto]', 'mime_in[foto,image/jpg,image/jpeg,image/png]', 'max_size[foto,1024]',],
'errors' => [
'max_size' => 'Ukuran {field} maksimal 1 MB',
'is_image' => 'File {field} harus berupa gambar',
'mime_in' => 'Format {field} tidak sesuai',
]
],
]);
if (!$valid) {
$msg = [
'error' => [
'nama' => $validation->getError('nama'),
'foto' => $validation->getError('foto'),
]
];
} else {
//db user
$user = new Modeluser($this->request);
//data acuan
$id_user = $this->request->getVar('id_user');
$foto_lama = $this->request->getVar('foto_lama');
//ambil gambar baru
$fileFoto = $this->request->getFile('foto');
$fotojd = time() . "_" . $fileFoto->getName();
//cek foto jgn hapus foto default.png
$cekData = $user->find($id_user);
$cekFoto = $cekData['foto'];
//kalau file kosong
if ($fileFoto->getError() == 4) {
$namaFoto = $foto_lama;
} else if ($cekFoto == 'default.png') {
//klo file default.png proses langsung ke upload
$fileFoto->move('img/profile/');
//ambil nama file
$namaFoto = $fileFoto->getName();
} else {
//klo filenya bukan default.png file foto lama dihapus dgn perintah unlink
$fileFoto->move('img/profile/', $fotojd);
//ambil nama file
$namaFoto = $fotojd;
//hapus file foto lama
unlink('img/profile/' . $foto_lama);
}
$simpandata = [
'nama' => $this->request->getVar('nama'),
'nama_slug' => $this->request->getVar('nama_slug'),
'foto' => $namaFoto,
'date_update' => time(),
];
$user->update($id_user, $simpandata);
$msg = [
'sukses' => 'Data user telah diupdate',
];
}
echo json_encode($msg);
} else {
exit('Maaf, tidak dapat diproses');
}
}
//edit password
public function editpassword()
{
if ($this->request->isAJAX()) {
$id_user = $this->request->getVar('id_user');
//data user
$user = new Modeluser($this->request);
$data['user'] = $user->find($id_user);
$msg = [
'sukses' => view('profile/modaleditpassword', $data)
];
echo json_encode($msg);
} else {
exit('Maaf, tidak dapat diproses');
}
}
//update password
public function updatepassword()
{
if ($this->request->isAJAX()) {
$validation = \Config\Services::validation();
$valid = $this->validate([
'passwordLama' => [
'label' => 'Password Lama',
'rules' => 'required',
'errors' => [
'required' => '{field} tidak boleh kosong',
]
],
'password' => [
'label' => 'Password',
'rules' => 'trim|required|min_length[6]',
'errors' => [
'trim' => '{field} jangan ada spasi',
'required' => '{field} tidak boleh kosong',
'min_length' => '{field} minimal 6 digit',
]
],
'password2' => [
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|matches[password]',
'errors' => [
'trim' => '{field} jangan ada spasi',
'required' => '{field} tidak boleh kosong',
'min_length' => '{field} minimal 6 digit',
'matches' => '{field} tidak sama',
]
],
]);
if (!$valid) {
$msg = [
'error' => [
'passwordLama' => $validation->getError('passwordLama'),
'password' => $validation->getError('password'),
'password2' => $validation->getError('password2'),
]
];
} else {
//db user
$user = new Modeluser($this->request);
//data acuan
$id_user = $this->request->getVar('id_user');
$passwordLama = $this->request->getVar('passwordLama');
$passwordBaru = $this->request->getVar('password');
//cek data user
$cekEmail = session()->get('email'); //session login cek email
//akses database
$db = \Config\Database::connect();
$cekData = $db->query("SELECT * FROM user WHERE email='$cekEmail'");
$row = $cekData->getRow();
$dataPassword = $row->password; //password aktif di db
if (!password_verify($passwordLama, $dataPassword)) {
$msg = [
'error' => [
'passwordLama' => 'Password lama salah'
]
];
} else {
if ($passwordLama == $passwordBaru) {
$msg = [
'error' => [
'password' => 'Password baru harus berbeda dengan password lama'
]
];
} else {
$simpandata = [
'password' => password_hash($this->request->getVar('password'), PASSWORD_BCRYPT),
'date_update' => time(),
];
$user->update($id_user, $simpandata);
$msg = [
'sukses' => 'Password user telah diupdate'
];
}
}
}
echo json_encode($msg);
} else {
exit('Maaf, tidak dapat diproses');
}
}
}
Membuat View Profile
View profile ini merupakan tampilan yang akan diakses oleh user, jadi tampilan profile ini akan berinteraksi langsung dengan user dalam merubah nama, gambar profile dan ganti password.
Meng-update View index.php
File ini merupakan tampilan awal saat pertama kali halaman profile ini dibuka, perhatikan baris kode berikut:
Baris kode Views/profile/index.php
html
<?= $this->extend('template/main'); ?>
<?= $this->extend('template/menu'); ?>
<?= $this->section('konten'); ?>
<div class="col-sm-8 m-3 mx-auto">
<div class="card mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h3 class="m-0 font-weight-bold text-dark">Profile Saya</h3>
</div>
<div class="card m-b-30">
<p class="viewdata"></p>
</div>
</div>
</div>
<div class="viewmodal" style="display:none;"></div>
<script>
//tampil data
function dataprofile() {
$.ajax({
url: "<?= site_url('profile/tampildata') ?>",
dataType: "json",
success: function(response) {
$('.viewdata').html(response.data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError);
}
});
}
$(document).ready(function() {
dataprofile();
});
</script>
<?= $this->endsection(''); ?>
Membuat View dataprofile.php
dataprofile.php menampung data yang di load dari Controller Profile.php, melalui perintah ajax, yang terdapat pada file index.php. perhatikan kode berikut:
Baris kode Views/profile/dataprofile.php
html
<div class="text-center ">
<img class="rounded-circle mt-3" src="<?= base_url() ?>/img/profile/<?= $user->foto ?>" height="150" width="150" alt="Foto Profile">
</div>
<div class="card-body">
<h4 class="card-title text-center"><?= $user->nama ?></h4>
<h4 class="card-title text-center"><?= '<span class="badge badge-pill badge-danger">' . $user->role . '</span>' ?></h4>
<p class="lead text-center"><?= $user->email ?></p>
</div>
<div class="card-footer text-center">
<button type="button" title="Ubah Profile" class="btn btn-primary btn-sm" onclick="edit('<?= $user->id_user ?>')"><i class="fas fa-list"></i></button>
<button type="button" title="Ubah Password" class="btn btn-warning btn-sm" onclick="editPassword('<?= $user->id_user ?>')"><i class="fas fa-lock"></i></button>
</div>
<script>
//edit page
function edit(id_user) {
$.ajax({
type: "post",
url: "<?= site_url('profile/editdata') ?>",
data: {
id_user: id_user
},
dataType: "json",
success: function(response) {
if (response.sukses) {
$('.viewmodal').html(response.sukses).show();
$('#modaledit').modal('show');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError);
}
});
}
//edit password
function editPassword(id_user) {
$.ajax({
type: "post",
url: "<?= site_url('profile/editpassword') ?>",
data: {
id_user: id_user
},
dataType: "json",
success: function(response) {
if (response.sukses) {
$('.viewmodal').html(response.sukses).show();
$('#modaleditpassword').modal('show');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError);
}
});
}
</script>
Membuat View modaledit.php
Modal Edit merupakan tampilan untuk mengubah data user berupa gambar dan nama user. Sedangkan untuk email tidak dapat diubah untuk meminimalisir faktor keamanan. Perhatikan baris kode berikut:
Baris kode Views/profile/modaledit.php
html
<!-- Modal -->
<div class="modal fade" id="modaledit" tabindex="-1" aria-labelledby="modaleditLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary text-white">
<h5 class="modal-title" id="modaleditLabel">Edit User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<?= form_open('', ['class' => 'formuser']); ?>
<?= csrf_field(); ?>
<div class="modal-body">
<div class="row">
<!-- col 4 -->
<div class="col-4">
<div class="form-group row">
<div class="col-sm-8">
<img src="/img/profile/<?= $user['foto'] ?>" class="img-thumbnail img-preview" alt="">
</div>
<div class="col-sm-8">
<div class="custom-file">
<input type="file" class="custom-file-input" id="foto" name="foto" onchange="previewImg()">
<div class="invalid-feedback errorFoto">
</div>
</div>
</div>
</div>
</div>
<!-- col 4 -->
<!-- col-8 -->
<div class="col-8">
<div class="form-group row">
<label for="" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="id_user" name="id_user" value="<?= $user['email'] ?>" readonly>
</div>
</div>
<div class="form-group row">
<label for="" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="id_user" name="id_user" value="<?= $user['id_user'] ?>" hidden>
<input type="text" class="form-control" id="nama" name="nama" value="<?= $user['nama'] ?>">
<input type="text" class="form-control" id="nama_slug" name="nama_slug" value="<?= $user['nama_slug'] ?>" hidden>
<input type="text" class="form-control" id="foto_lama" name="foto_lama" value="<?= $user['foto'] ?>" hidden>
<div class="invalid-feedback errorNama">
</div>
</div>
</div>
<div class="form-group row">
<label for="" class="col-sm-2 col-form-label">Foto</label>
<div class="col-sm-8">
<div class="custom-file">
<div class="invalid-feedback errorFoto">
</div>
<label class="custom-file-label" for="foto">Pilih gambar</label>
</div>
</div>
</div>
</div>
<!-- col 8 -->
</div>
<?= form_close(); ?>
<div class="modal-footer">
<button type="submit" class="btn btn-success btnsimpan">Ubah</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('.btnsimpan').click(function(e) {
let form = $('.formuser')[0];
let data = new FormData(form);
e.preventDefault();
$.ajax({
type: "post",
url: "<?= site_url('profile/updatedata') ?>",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
dataType: "json",
beforeSend: function(e) {
$('.btnsimpan').attr('disabled', 'disabled');
$('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses');
},
complete: function(e) {
$('.btnsimpan').removeAttr('disabled');
$('.btnsimpan').html('Ubah');
},
success: function(response) {
//klo ada error
if (response.error) {
//error nama
if (response.error.nama) {
$('#nama').addClass('is-invalid');
$('.errorNama').html(response.error.nama);
} else {
$('#nama').removeClass('is-invalid');
$('.errorNama').html('');
}
//foto
if (response.error.foto) {
$('#foto').addClass('is-invalid');
$('.errorFoto').html(response.error.foto);
} else {
$('#foto').removeClass('is-invalid');
$('.errorFoto').html('');
}
} //sukses
else {
//pesan sukses bro
Swal.fire({
icon: 'success',
title: 'Berhasil',
text: response.sukses,
//timer: 5000, //diarah ke link dalam 5 detik
});
//hide modal tambah data
$('#modaledit').modal('hide');
//load data user
dataprofile();
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError);
}
});
return false;
});
});
</script>
<script>
function previewImg() {
const foto = document.querySelector('#foto');
const fotoLabel = document.querySelector('.custom-file-label');
const imgPreview = document.querySelector('.img-preview');
fotoLabel.textContent = foto.files[0].name;
const fileFoto = new FileReader();
fileFoto.readAsDataURL(foto.files[0]);
fileFoto.onload = function(e) {
imgPreview.src = e.target.result;
}
}
</script>
<script>
//slug
$("#nama").keyup(function() {
var str = $(this).val();
var trims = $.trim(str)
var slug = trims.replace(/[^a-z0-9]/gi, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
$("#nama_slug").val(slug.toLowerCase())
})
</script>
Membuat View modaleditpassword.php
Modal Edit Password merupakan untuk mengubah password user, user akan diminta password lama dan memasukan password baru sebanyak 2 (dua) kali, jika password baru sama lama maka sistem akan memberikan pesan, sehingga user diarahkan untuk mengisi dengan password yang berbeda. Perhatikan baris kode berikut:
Baris kode Views/profile/modaleditpassword.php
html
<!-- Modal -->
<div class="modal fade" id="modaleditpassword" tabindex="-1" aria-labelledby="modaleditpasswordLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header bg-warning text-white">
<h5 class="modal-title" id="modaleditLabel">Edit Password <?= $user['nama'] ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<?= form_open('profile/updatepassword', ['class' => 'formuser']); ?>
<?= csrf_field(); ?>
<div class="modal-body">
<div class="form-group row">
<label for="" class="col-sm-6 col-form-label">Password Lama</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="id_user" name="id_user" value="<?= $user['id_user'] ?>" hidden>
<input type="password" class="form-control" id="passwordLama" name="passwordLama">
<div class="invalid-feedback errorPasswordlama">
</div>
</div>
</div>
<div class="form-group row">
<label for="" class="col-sm-6 col-form-label">Password Baru</label>
<div class="col-sm-6">
<input type="password" class="form-control" id="password" name="password">
<div class="invalid-feedback errorPassword">
</div>
</div>
</div>
<div class="form-group row">
<label for="" class="col-sm-6 col-form-label">Ulangi Password Baru</label>
<div class="col-sm-6">
<input type="password" class="form-control" id="password2" name="password2">
<div class="invalid-feedback errorPassword2">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success btnsimpan">Ubah</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
</div>
<?= form_close(); ?>
</div>
</div>
</div>
<script>
$(document).ready(function() {
//focus pada input
$('body').on('shown.bs.modal', '#modaleditpassword', function() {
$('input:visible:enabled:first', this).focus();
})
$('.formuser').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
$('.btnsimpan').attr('disabled', 'disabled');
$('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses');
},
complete: function() {
$('.btnsimpan').removeAttr('disabled');
$('.btnsimpan').html('Ubah');
},
success: function(response) {
//klo ada error
if (response.error) {
//error password lama
if (response.error.passwordLama) {
$('#passwordLama').addClass('is-invalid');
$('.errorPasswordlama').html(response.error.passwordLama);
} else {
$('#passwordLama').removeClass('is-invalid');
$('.errorPasswordlama').html('');
}
//error password
if (response.error.password) {
$('#password').addClass('is-invalid');
$('.errorPassword').html(response.error.password);
} else {
$('#password').removeClass('is-invalid');
$('.errorPassword').html('');
}
//error password 2
if (response.error.password2) {
$('#password2').addClass('is-invalid');
$('.errorPassword2').html(response.error.password2);
} else {
$('#password2').removeClass('is-invalid');
$('.errorPassword2').html('');
}
} //sukses
else {
//pesan sukses bro
Swal.fire({
icon: 'success',
title: 'Berhasil',
text: response.sukses
});
//hide modal tambah data
$('#modaleditpassword').modal('hide');
//load data user
dataprofile();
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError);
}
});
return false;
});
});
</script>
Update File Routes.php
Selanjutnya yaitu menambahkan rute profile supaya dapat dikenali oleh sistem CodeIgniter 4, perhatikan potongan baris kode dari file Routes.php berikut ini:
Potongan baris kode Routes.php
php
....
// profile
$routes->get('/profile', 'Profile::index');
$routes->get('/profile/tampildata', 'Profile::tampildata');
$routes->post('/profile/editdata', 'Profile::editdata');
$routes->post('/profile/updatedata', 'Profile::updatedata');
$routes->post('/profile/editpassword', 'Profile::editpassword');
$routes->post('/profile/updatepassword', 'Profile::updatepassword');
....
Uji Coba
Silahkan kunjungi atau klik halaman http://localhost:8080/profile, hasil akhirnya kurang lebih seperti ini:
Tidak ada komentar untuk "Membuat Halaman Profile"
Posting Komentar
Komentarnya dong cuuuy :D