Why does the validation for my codeigniter website fail everytime? - php

I have a controller code like so:
$validation=service('validation');
$validation->reset();
$data = [
'validation' => $validation,
];
if ($this->request->getMethod() === 'post'){
$validation->setRules( [ 'comment' => 'required',] );
if($validation->run()) {
$CommentsModel->save(['Comment' => $this->request->getPost('comment'),]);
return redirect()->to('/someplace...');
}
}
}
return view('templates/header', $data)
. view('templates/menu')
. view('addComment', $data)
. view('templates/footer');
}
Everytime my form is posted, the validation fails... even when I have something in comment! Any idea why this would be?
This is the form:
<form action="/Add/<?= esc($book)?>/<?= esc($chapter) ?>" method="post">
<?= csrf_field() ?>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" ><?= set_value("comment")?></textarea><br />
<?php if($validation->hasError('comment')) echo '<p class="validationError">' . $validation->getError('comment') . '</p>'?>
<input type="submit" name="submit" value="Add Comment" />
</form>

Related

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>

Why updating meta from front-end needs i get old value?

The new value is sent to the db and the page refreshes on submit, but the field
becomes empty. If I then manually refresh the page again, then I see
the new value. Any idea why?
<form action="" method="POST" class="myForm" autocomplete="off">
<input id="dateChange" type="text" name="input-test" value="<?php echo str_replace('_', '', $jikuDate); ?>" autocomplete="off">
<input id="test-form" type="submit" name="updateDate" value="Update">
</form>
and then I do
<?php
if(isset($_POST['updateDate'])){
$post = array(
'ID' => $id
);
if ('Update' === ($_POST['updateDate'] ?? false)) {
update_post_meta( $post->ID, 'usp-custom-14', $_POST['input-test']);
}
}
?>
This is how I resolved it, not the most elegant probably:
First:
<?php
$jikuDate = get_post_meta($post->ID, 'usp-custom-14', true);
if (isset($_POST['updateDate'])) {
// Execute this code if the submit button is pressed.
$jikuDate = $_POST['input-test'];
}
?>
Then the html:
<form action="" method="POST" class="myForm" autocomplete="off">
<input id="dateChange" type="text" name="input-test" value="<?php echo str_replace('_', '', $jikuDate); ?>" autocomplete="off">
<input id="test-form" type="submit" name="updateDate" value="Update">
</form>
Then:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
if ('Update' === ($_POST['updateDate'] ?? false)) {
$post = array(
'ID' => $id
);
$jikuDate = $_POST['input-test'];
update_post_meta( $post['ID'], 'usp-custom-14', $_POST['input-test']);
}
}
?>

Codeigniter 3 blog application: redirecting to the updated post fails

I am working on a basic (just 2 tables: authors and posts) blog application in Codeigniter 3.1.8.
I have an edit post functionality, using an update form:
<?php echo form_open("posts/update"); ?>
<input type="hidden" name="id" id="pid" value="<?php echo $post->id; ?>">
<div class="form-group <?php if(form_error('title')) echo 'has-error';?>">
<input type="text" name="title" id="title" class="form-control" placeholder="Title" value="<?php echo $post->title; ?>">
<?php if(form_error('title')) echo form_error('title'); ?>
</div>
<div class="form-group <?php if(form_error('desc')) echo 'has-error';?>">
<input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="<?php echo $post->description; ?>">
<?php if(form_error('desc')) echo form_error('desc'); ?>
</div>
<div class="form-group <?php if(form_error('body')) echo 'has-error';?>">
<textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"><?php echo $post->content; ?></textarea>
<?php if(form_error('body')) echo form_error('body'); ?>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
In the Posts_model model I have the method responsible with updating the post:
public function update_post() {
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body')
];
$this->db->where('id', $this->input->post('id'));
return $this->db->update('posts', $data);
}
In the Posts controller, I have 2 methods, for editing and updating the post:
public function edit($id) {
$data = $this->Static_model->get_static_data();
$data['post'] = $this->Posts_model->get_post($id);
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit');
$this->load->view('partials/footer');
}
public function update() {
$this->Posts_model->update_post();
// Redirect to the updated post
}
In my update() method, I was unable to redirect to the updated post. The redirect($this->agent->referrer()); line only brings me back to the update form. Where I want to redirect to is the just updated post. How do I do that?
Post vars should be handled in your controller:
public function update() {
$id = $this->input->post('id');
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body')
];
// Update post
$this->Posts_model->update_post($id, $data);
// Redirect to the updated post
redirect('posts/post/' . $id);
}
Model:
public function update_post($id, $data) {
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
Note: if you want to do it your way, then simply return the id in the model function and redirect based on the return of the function in update()

CodeIgniter not reacting to post

When I submit a form for the url example.com/index.php/topic/1/test-topic-test CodeIgniter does not recognize that a post form is submitted.
Routes:
$route["topic/(:num)/([a-z]+)"]["post"] = "forums/topic_post_reply/$1/$2";
Forums.php controller:
public function topic_post_reply($id, $name)
{
$message = $this->input->post("topic_reply_content");
if(!empty($message) && !empty($this->session->userdata('id')))
{
$data = [
"content" => $message,
"author" => $this->session->userdata('id'),
"reply_date" => time(),
"parent" => $id
];
$this->db->insert("forum_topics_replies", $data);
}
else
{
die("Something went wrong");
}
}
Form:
<form class="uk-form-stacked" action="<?php echo base_url(); ?>index.php/topic/<?php echo $this->uri->segment(2); ?>/<?php echo $this->forums_model->slug($this->uri->segment(3)); ?>" method="post">
<div class="uk-form-inline">
<textarea class="uk-textarea" name="topic_reply_content" rows="4" placeholder="Write a lovely reply..."></textarea>
</div>
<div class="laevis-reply-hidden">
<div class="uk-margin-small" style="margin-bottom:0">
<input type="submit" class="uk-button uk-button-primary uk-width-1-1" value="Post">
</div>
</div>
Why isn't this working?
I had to have the post route above all other routes for the same url or it would not work. I also had to change it to $route["topic/(:num)/:any"]["post"].

Codeigniter - Displaying page

I'm having a problem displaying my index.php in codeigniter. Can someone help me with this?
Here's my index.php:
<form id="myForm" action="<?php echo baseurl('controller/CreateUser'); ?>" method="post">
Name: <input type="text" name="name"/><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button id="sub">Save</button>
</form>
<span id="result"></span>
And here's my controller:
public function index(){
$this->load->view( 'layouts/header', [ 'title' => 'Never Stop Learning!' ] );
$this->load->view( 'NeverStopLearning/index');
$this->load->view( 'layouts/footer' );
}
public function CreateUser(){
$data = array(
"name" => $this->input->post("name"),
"username" => $this->input->post("username"),
"password" => $this->input->post("password")
);
if($this->model->Insert('table_users', $data)){
echo "Successfully Inserted";
}else{
echo "Insertion Failed";
}
}

Categories