Using key `action` is deprecated, use `url` directly instead in cakephp - php

I am getting this error in CakePHP from my forgot_password method which is in UsersController.
public function forgot_password() {
$this->layout = 'signin';
if (!empty($this->data)) {
$user = $this->User->findByUsername($this->data['User']['username']);
if (empty($user)) {
$this->Session->setflash('Sorry, the username entered was not found.');
$this->redirect('/users/forgot_password');
}else{
$user = $this->__generatePasswordToken($user);
if ($this->User->save($user) && $this->__sendForgotPasswordEmail($user['User']['id'])) {
$this->Session->setflash('Password reset instructions have been sent to your email address.
You have 24 hours to complete the request.');
$this->redirect('/users/login');
}
}
}
}
Here is the forgot_password.ctp file
<header class="panel-heading text-center">
<strong>Forget Password</strong>
</header>
<h3>Enter Your Username</h3>
<?php
echo $this->Form->create('User', array('action' => 'forgot_password', 'id' => 'web-form', 'class'=>'panel-body wrapper-lg'));
echo $this->Form->input('username', array('label' => 'Username', 'between'=>'<br />', 'type'=>'text', 'div' => 'form-group','class' => 'form-control input-lg'));
?>
<div class="form-group">
<?php echo $this->Form->submit('Send Password Reset Instructions', array('class' => 'btn btn-primary btn-techuz', 'id' => 'submit')); ?>
</div>
<?php echo $this->Form->end(); ?>

It's not necessary to specify the form action if it's same as the view. In case you'd like to redirect to a different action, try this:
<?php
echo $this->Form->create('User', array(
'url' => array(
'controller' => 'users','action' => 'forgot_password'
),
'id' => 'web-form',
'class' =>'panel-body wrapper-lg'
)
); ?>
If you follow the convention and define this "url" index as an array of controller and index, you're bound to be safe and deprived of errors.
Peace! xD

Got the solution, no need to mention 'action' => 'forgot_password' in forgot_password.ctp file until it is redirect to another method.

Related

CodeIgniter, Requested URL not found on server

I'm currently developing a system in CodeIgniter that requires user authentication via login & registration as a base in order to use the rest of the system. I've been having a 404 Not Found issue on my system whenever I try to call a Controller function, this is particularly prevalent on form submissions. I've posted my related code from my Controller, Model, View, Routes and Htaccess below. I'm not entirely sure whats causing the 404 not found error, any help would be greatly appreciated.
Controller:
// handles register page
public function register() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = "Register";
$this->form_validation->set_rules('fullname','Full Name','required');
$this->form_validation->set_rules('accountid','Account ID','required');
$this->form_validation->set_rules('password','Password','required');
$this->form_validation->set_rules('type','Account Type','required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('register', $data);
} else {
$fullname = $this->input->post('fullname');
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$accounttype = $this->input->post('type');
$this->system->registeruser($username, $password, $fullname, $accounttype);
echo "User Registration Complete";
}
}
Model:
public function registeruser($accountid, $password, $fullname, $accounttype) {
$query = "INSERT INTO users VALUES($fullname','$accountid','$password','$accounttype')";
$this->db->query($query);
}
View:
<?php
echo form_open('main/register');
echo validation_errors(); ?>
<div id="name-input">
<?php
$data = array(
'name' => 'fullname',
'value' => $this->input->post('fullname'),
'placeholder' => 'Full Name',
'class' => '',
'style' => 'width:100%; padding:0.5em;' );
echo form_input($data);
echo "</p>"; ?>
</div>
<div id="username-input">
<?php
$data = array(
'name' => 'accountid',
'value' => $this->input->post('accountid'),
'placeholder' => 'User ID',
'class' => 'username',
'style' => 'width:100%; padding:0.5em;' );
echo form_input($data);
echo "</p>"; ?>
</div>
<div id="password-input">
<?php
$data = array(
'name' => 'password',
'value' => $this->input->post('password'),
'placeholder' => 'Password',
'class' => 'passwordd',
'style' => 'width:100%; padding:0.5em;' );
echo form_password($data);
echo "</p>"; ?>
</div>
<div id="account-type">
<?php
$options = array(
'student' => 'Student',
'lecturer' => 'Lecturer' );
$data = array(
'name' => 'type',
'style' => 'width:100%; padding:0.5em;' );
echo form_dropdown($data, $options);
echo "</p>"; ?>
</div>
<div id="submit-button">
<?php
$data = array(
'name' => 'register',
'value' => 'Register Account',
'class' => 'register',
'style' => 'width:100%; padding:0.5em;' );
echo form_submit($data); ?>
</div>
<?php echo form_close(); ?>
Routes:
$route['main/register'] = 'main/register';
$route['default_controller'] = 'main';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
Htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
All the code above relates to my registration page / it's related functions, I have multiple of these errors on my system currently but they all seem to be the same thing, I figured solving one may solve the rest as well.
I don't know the exact cause of your problem, but following solution should work.
Remove
echo form_open('main/register');
line and add
echo "<form action='' method='post' >";
(leave the action attribute empty, so it will submit data to the current page)
Remove
$route['main/register'] = 'main/register';
line.
Extra suggestion: Don't use md5(), because it is not secure. Use password_hash() instead.
Try removing the route $route['main/register'] = 'main/register';. Also, give method POST to the form. And input field names do not match in controller as well as model.
Edit:
Form action should be a complete URL-
echo form_open(base_url()."/controllername/mehod"); In your case it should be echo form_open(base_url()."/main/register");
If you haven't set base_url then
Step 1: Open the config.php file under application\config folder
step 2: Set the value of $config['base_url'] to your website path
$config['base_url'] = "http://localhost/foldername/index.php";
That should help. :)

Cannot submit form with a hidden input in Cakephp

so I have a form that contains a hidden input.
<?= $this->Form->create(null, [ 'class' => '', 'templates' => 'Inspinia.form_basic']) ?>
<?php
echo $this->Form->control('name');
echo $this->Form->control('description', ['type' => 'text']);
echo $this->Form->control('chart_type', [ 'options' => $this->App->availableCharts() ] );
echo $this->Form->control('frequency', [ 'options' => ['monthly' => 'Monthly','quarterly'=>'Quarterly','snapshot' =>'Snapshot','monthly/quarterly' => 'Monthly/Quarterly'] ] );
echo $this->Form->control('public', [ 'options' => ['1' => 'Public','0' => 'Private'] ] );
// $this->Form->unlockField('deleted');
echo $this->Form->hidden('deleted',['value' => 0]);
?>
<?= $this->Form->button(__('Save'), ['class' => 'btn btn-sm btn-primary pull-right m-t-n-xs']) ?>
<?= $this->Form->end() ?>
Whenever I try to submit the form, it throws me this error
Missing field 'deleted' in POST data
I know I can bypass this by just doing
$this->Form->unlockField('deleted');
but I don't want to bypass the security component in Cakephp, so is there any other way I can get CakePhp to allow me to submit this hidden field?
this is my controller nothing too much but here just in case you guys are wondering
public function test() {
if ($this->request->is('post')) {
debug($this->request->data);
}
}
It should like below
<?php
echo $this->Form->input('nameoffield',array('type'=>'hidden'));
?>
or passing a hidden value
<?php
$hidden_value = 0;
echo $this->Form->input('nameoffield',array('type'=>'hidden','value' => $hidden_value));
?>

stdClass error on CodeIgniter Comment System

I'm working on a comment section for my blog post in CodeIgniter, I based myself on a tutorial by Brad Traversy and I followed each step carefully but somehow it does not work within my template.
This is show method in my Post Controller:
public function show($slug)
{
// Get Posts by Slug
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Get Comments per Post
$post_id = $data['posts']['id']; // Here is where I get the error
$data['comments'] = $this->Post_model->get_comments($post_id);
// If empty show a 404 error
if(empty($data['posts'])){
show_404();
}
// Load template
$this->template->load('public', 'default', 'posts/show', $data);
}
I created a variable $post_id in order to get the comments for the current post that is being visited by an user. All this should come from my Post_model:
public function get_comments($post_id){
$this->db->select('username,email,website,body');
$this->db->from('comments');
$query = $this->db->get_where('comments', array('post_id' => $post_id));
return $query->result_array();
}
This is where I'm creating the form to add the comment:
<!-- Form -->
<h4>Add a comment</h4>
<?php echo validation_errors('<p class="alert alert-danger">'); ?>
<?php echo form_open('public/comments/add_post_comment/'.$post['id']); ?>
<!-- Username -->
<div class="form-group">
<?php echo form_label('Username', 'username'); ?>
<?php
$data = array(
'id' => 'username',
'name' => 'username',
'class' => 'form-control',
'placeholder' => 'John Doe',
'value' => set_value('username')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Email -->
<div class="form-group">
<?php echo form_label('E-mail', 'email'); ?>
<?php
$data = array(
'id' => 'email',
'name' => 'email',
'class' => 'form-control',
'placeholder' => 'JohnDoe#demo.com',
'value' => set_value('email')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Website -->
<div class="form-group">
<?php echo form_label('Website', 'website'); ?>
<?php
$data = array(
'id' => 'website',
'name' => 'website',
'class' => 'form-control',
'placeholder' => 'https://www.example.com',
'value' => set_value('website')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Comments Body -->
<div class="form-group">
<?php echo form_label('Body', 'body'); ?>
<?php
$data = array(
'id' => 'body',
'name' => 'body',
'class' => 'form-control',
'placeholder' => 'Write here',
'value' => set_value('body')
);
?>
<?php echo form_textarea($data); ?>
</div>
<!-- Hidden Input -->
<?php
$data = array(
'name' => 'slug',
'value' => $posts->slug,
);
?>
<?php echo form_hidden($data); ?>
<!-- Submit Button -->
<?php echo form_submit('mysubmit', 'Add Comment', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
<?php endif; ?>
This is the Controller I'm using to add comments to the specific $post_id:
public function add_post_comment($post_id)
{
// Field Rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[3]');
$this->form_validation->set_rules('body', 'Body', 'trim|required|min_length[3]');
if ($this->form_validation->run() == FALSE) {
// Set Message
$this->session->set_flashdata('error', 'There was an error in proccessing the comment. Please, try again.');
// Redirect to current page
redirect(site_url() . 'posts/show/'.$post_id);
} else {
// Get Post by Slug
$slug = $this->input->post('slug');
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Create Post Array
$data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'user_id' => $this->session->userdata('user_id'),
'email' => $this->input->post('email'),
'website' => $this->input->post('website'),
'body' => $this->input->post('body'),
);
// Insert Comments
$this->Comments_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Your comment has been posted');
// Redirect to same page if form was not successful or submitted
redirect(site_url() . 'posts/show/'.$post_id);
}
}
All this should work according to some tutorials that I have seen before but this time is not.
The error comes from my function show. Any idea on how to fix this?
Thanks for helping.
Ok well as you would have read in the codeigniter users guide - $query->row() will return an object.
So you would use $data['posts']->id. Which may or may not work with your current PHP Version. I'm open to be corrected on that point.
If you want an associative array, as you are attempting to use, then you would use $query->row_array();
If you had performed a var_dump like...
public function show($slug)
{
// Get Posts by Slug
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Quick Debug to Eyeball what is actually being returned.
var_dump($data['posts']);
exit();
// Get Comments per Post
$post_id = $data['posts']['id']; // Here is where I get the error
$data['comments'] = $this->Post_model->get_comments($post_id);
// If empty show a 404 error
if(empty($data['posts'])){
show_404();
}
// Load template
$this->template->load('public', 'default', 'posts/show', $data);
}
You would see ( and its always a good check when validating your code ) what is being returned by $this->Post_model->get_by_slug($slug);
It's a very good idea to know how to "look" at what your variables are and check they are what you think they should be.

function show in url after submit form in codeigniter

When I submit this form all things are well n good but I want the controller function not shows in url. I want all things are done in same page. Still the url show
localhost/Naveen/CodeIgniter/welcome/insertform
but I don't want the form_open('') show's in url so how it is possible?
controller welcome.php
public function insertform()
{
if (isset($_POST['mysmt']))
{
$this->form_validation->set_rules('fname', 'Name', 'required');
$this->form_validation->set_rules('femail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('fmobile', 'Mobile', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_view');
}
else
{
$_POST['fname'];
$_POST['femail'];
$_POST['fmobile'];
if($this->test_model->insert('user_accounts',array('',$_POST['fname'],$_POST['femail'],$_POST['fmobile'])))
{
$success['success']="Thanks For Join Us";
$this->load->view('welcome_view',$success);
}
}
}
else
{
$this->load->view('welcome_view');
}
}
view welcome_view.php
<?php echo form_open('welcome/insertform'); // ?>
<div class="form-group">
<?php
if(isset($success))
{?>
<input type="button" class="form-control btn-success" value="<?php echo $success; ?>">
<?php }
else
{
echo "";
}?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Name <?php echo form_error('fname'); ?></label>
<?php
$entername = array(
'name' => 'fname',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Name',
'class' => 'form-control',
);
echo form_input($entername); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Email <?php echo form_error('femail'); ?></label>
<?php
$enteremail = array(
'name' => 'femail',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Email',
'class' => 'form-control',
);
echo form_input($enteremail); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Mobile <?php echo form_error('fmobile'); ?></label>
<?php
$entermobile = array(
'name' => 'fmobile',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Mobile',
'class' => 'form-control',
);
echo form_input($entermobile); ?>
</div>
<div class="form-group">
<?php
$f_formsmt = array(
'name' => 'mysmt',
'value' => 'Submit Form',
'class' => 'form-control btn btn-success',
);
echo form_submit($f_formsmt); ?>
</div>
<?php echo form_close(); ?>
You handle it through applications/config/routes.php
consider you url: localhost/Naveen/CodeIgniter/welcome/insertform
$route['add'] = 'welcome/insertform';
now you can use localhost/Naveen/CodeIgniter/add
You can change whatever the string you want for any controller/function using routes.
Hope you understood :)
You need to add the url in route and add link to your link href
In route.php add:
$route['custom_url'] = 'controller/method';
I used Header("location:../{whatever-filename}")
Then gave that "whatever-filename" the proper routing in the config/routes.php.
Routing without using the redirect function would load the appropriate page but the url would still show the controller and method you're using.
Hope it helps

Validation messages are not showing in cakephp 2.4.x

Here is my validation rule in User.php
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'User name is required'
),
'alphaNumeric'=>array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
)
))
and this is my view page code
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username'));
echo $this->Form->input('email', array('label' => 'Email'));
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->submit('Sign Up');
echo $this->Form->end();
?>
Here is my controller code
public function register() {
$this->layout = 'starter';
//debug($this->validationErrors);
if ($this->request->is('post')) {
if ($this->User->validates()) {
$this->User->save($this->request->data);
$this->Session->setFlash(__('Please login your account'));
$this->redirect('/users/login');
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
but validation message is not showing. What is wrong in my code?...
Your code is wrong.
if ($this->request->is('post')) {
if ($this->User->validates()) {
$this->User->save($this->request->data);
this is not how it could ever work as the data is not passed prior to validation.
You need to first pass the data, then validate, then optionally save (or save and validate together):
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {}
or, careful not to retrigger validation twice:
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
$success = $this->User->save(null, array('validate' => false));
But that is documented.
The latter only makes sense if you really need to do this in two steps.
In your comment you have written you have changed layout page.It may you miss
<?php echo $this->Session->flash(); ?>
this line.Add this line in your view/layouts/yourlayout.ctp file.
Disable HTML5 required in your view page code
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username','required'=>'false'));
echo $this->Form->input('email', array('label' => 'Email','required'=>'false'));
echo $this->Form->input('password', array('label' => 'Password','required'=>'false'));
echo $this->Form->submit('Sign Up');
echo $this->Form->end();
?>

Categories