CakePHP Form Validation Not Working - php

I've been learning how to use CakePHP using a video tutorial series, and I'm having issues with validation on forms. I've tried several different things that I've found on the CakePHP book and it doesn't seem to be working either. It's pretty simple validation, just making sure that the title isn't empty or duplicate, and that the post isn't empty, yet the form is still submitting regardless of whether it's blank or duplicate.
Here is my model:
class Post extends AppModel {
var $name = 'Post';
var $validate = array(
'title'=>array(
'title_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'This post is missing a title!'
),
'title_must_be_unique'=>array(
'rule'=>'isUnique',
'message'=>'A post with this title already exists!'
)
),
'body'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'This post is missing its body!'
)
)
);
}
Here is the controller:
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function view($id = NULL) {
$this->set('post', $this->Post->read(NULL, $id));
}
function add() {
if (!empty($this->request->data)) {
if($this->Post->save($this->request->data)) {
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('The post was not saved... Please try again!');
}
}
}
function edit($id = NULL) {
if(empty($this->data)) {
$this->data = $this->Post->read(NULL, $id);
} else {
if($this->Post->save($this->data)) {
$this->Session->setFlash('The post has been updated');
$this->redirect(array('action'=>'view', $id));
}
}
}
function delete($id = NULL) {
$this->Post->delete($id);
$this->Session->setFlash('The post has been deleted!');
$this->redirect(array('action'=>'index'));
}
}
And here is the view:
<h2>Add a Post</h2>
<?php
echo $this->Form->create('Post', array('action'=>'add'));
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Create Post');
?>
<p><?php echo $this->Html->link('Cancel', array('action'=>'index')); ?></p>
Thanks in advance!

The problem is that the rules you're trying to use aren't defined in the CakePHP framework. If you want to require something and make sure the field isn't empty you should try this:
'title' => array(
'required' => array(
'rule' => array('minLength', 1),
'allowEmpty' => false,
'message' => 'Please enter a title.'
)
),
The 'required' key tells Cake that the field is required while 'allowEmpty' => false tells Cake that the field needs to contain something and can't just be an empty string.

Related

How can I pass both id and value to the controller from my input form in cakePHP?

Here is my code
View (edit.ctp):
<?php echo $this->Form->create('Answer'); ?>
<?php echo $this->Form->input('Answer.0.value', array('class' => 'validate', 'type' => 'text', 'id' => 'Answer.0.id', 'label' => false)) ?>
<?php echo $this->Form->end('Edit Answer'); ?>
Controller:
public function edit($id) {
$this->layout = 'request_processing_edit';
$data = $this->Response->findById($id);
if ($this->request->is(array('post', 'put'))) {
$this->Response->id = $id;
if ($this->Answer->save($this->request->data)) {
$this->Session->setFlash('Answer Editted');
$this->redirect('index');
}
}
This is how $this->request->data array looks like:
I need the id to be in the same array as value upon clicking submit in the view
Is there any way to achieve this without having to build the array in the controller? Looking for a way to have both id and value passed in the request upon clicking submit from the view/form.
So, Here you can use this way
In your Controller :
$data = $this->Post->findById($id);
if ($this->request->is(array('post', 'put'))) {
$this->Answer->id = $id;
if ($this->Answer->save($this->request->data)) {
$this->Session->setFlash('Answer Editted');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('Answer Not Editted');
}
if (!$this->request->data) {
$this->request->data = $data;
In Your View File Pass Hidden Field ID :
echo $this->Form->input('id', array('type' => 'hidden'));
Found a solution by adding this line of code in my ctp file:
<?php echo $this->Form->input('Answer.0.id', array('hidden' => true)) ?>

cakephp save() creating blank entry to database

I am new to CakePHP, i am creating simple form to add/edit/delete post as it is explain on its official website, my issue, while adding post to database it is not saving data,it is creating blank entries to database
Here is Code for Postscontroller.php
<?php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public $components = array('Session');
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
//debug($this->Post->validationErrors);
$this->Session->setFlash(__('Unable to add your post.'));
}
}
}
?>
Here is Code for Model Post.php :
<?php
class Post extends AppModel {
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
?>
Here is code for View add.ctp :
<h1>Add Post</h1>
<?php
echo $this->Form->create('post');
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Save Post');
?>
can anyone suggest me what is causing blank entries to database ?
In the add.ctp :
The form name is Post not post...
<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Save Post');
?>
In config/core.php file change the debug label to 2.(Configure::write('debug', 2)) and try saving again. The model name should be Post in the form. Please check the post data before saving.
debug($this->request->data);
exit;

Add data to the database using codeigniter

I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}

CakePHP 2.0, Submit form redirect not rendering properly

Hi I've created a file upload form, it all works perfectly apart from when I press submit it does not re-direct me to the Uploads/add.ctp, but it does save the file to the directory and on to the database.In fact if I point the re-direct to uploads/browse it still does not take me to uploads/browse.
This is my controller
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else{
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
and this is my form
<div class="maincontent">
<?php echo $this->Form->create('Upload', array('type' => 'file', 'class'=>'uploadfrm'));?>
<fieldset class='registerf'>
<legend class='registerf2'>Upload a Video</legend>
<?php
echo 'Upload your video content here, there is no size limit however it is <b>.mp4</b> file format only.';
echo '<br/>';
echo '<br/>';
echo $this->Form->input('name', array('between'=>'<br />', 'class'=>'input'));
echo $this->Form->input('eventname', array('between'=>'<br />'));
echo $this->Form->input('description', array('between'=>'<br />', 'rows'=> '7', 'cols'=> '60'));
echo $this->Form->hidden('userid', array('id' => 'user_id','value' => $auth['id']));
echo $this->Form->hidden('username', array('id' => 'username', 'value' => $auth['username']));
echo $this->Form->input('file', array('type' => 'file'));
echo "<br/>"
?>
<?php echo $this->Form->end(__('Submit', true));?>
</fieldset>
<?php
class UploadsController extends AppController {
public $name = 'Uploads';
public $helpers = array('Js');
// Users memeber area, is User logged in…
public $components = array(
'Session',
'RequestHandler',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'uploads', 'action'=>'browse'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"Members Area Only, Please Login…",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
// regular user can access the file uploads area
if (isset($user['role']) && $user['role'] === 'regular') {
return true;
}
// Default deny
return false;
}
function index() {
$this->set('users', $this->Upload->find('all'));
}
// Handling File Upload Function and updating uploads database
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->redirect(array('controller' => 'Uploads', 'action' => 'add'));
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
} }else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
function browse () {
// Find all in uploads database and paginates
$this->paginate = array(
'limit' => 5 ,
'order' => array(
'name' => 'asc'
)
);
$data = $this->paginate('Upload');
$this->set(compact('data'));
}
function recentuploads () {
$uploads = $this->Upload->find('all',
array('limit' =>7,
'order' =>
array('Upload.date_uploaded' => 'desc')));
if(isset($this->params['requested'])) {
return $uploads;
}
$this->set('uploads', $uploads);
}
function watch ($id = null){
$this->set('isAjax', $this->RequestHandler->isAjax());
// Read Uploads Table to watch video
$this->Upload->id = $id;
$this->set('uploads', $this->Upload->read());
// Load Posts Model for comments related to video
$this->loadModel('Post');
$this->paginate = array(
'conditions' => array(
'uploadid' => $id),
'limit' => 4
);
$data = $this->paginate('Post');
$this->set(compact('data'));
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
}
?>
Any suggestions?
This add function is in your UploadsController, correct? And you want it to redirect to uploads/browse?
In your UploadsController, what is $name set to?
<?php
class UploadsController extends AppController {
public $name = ?; // What is this variable set to?
}
By Cake's Inflector, when you specify controllers in a redirect, it should be lowercase:
$this->redirect(array('controller' => 'uploads', 'action' => 'browse'));
Or if the action you direct from and the action you want to direct to are in the same controller, you do not even need to specify the controller. For example if you submit the form from UploadsController add() and you want to redirect to browse():
$this->redirect(array('action' => 'browse'));
Try that and see if it helps.
Also note that you are calling $this->Upload->save($this->data) twice in your add function.
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
Specifically, here:
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
...
When you call it in the if condition, it still saves the data to the database. It is fine to remove the second one.
If I add the following line in the function add
$this->render();
everything works perfectly, I'm struggling for the life of me to work out why I have to render the view if surely all other views are rendered by default.
But anyway got it working!
Hope this helps others :)

CakePHP 2.x Translate Behavior Not Saving to i18n Table

I've followed the instructions in the manual for setting up Translate Behavior with CakePHP 2.1, as well as this question here on Stack. I am not getting any errors, but my translated posts are not saving to my i18n table.
Here is my PostModel.php:
class Post extends AppModel {
public $title = 'Post';
public $name = 'Post';
public $body = 'Post';
public $actAs = array(
'Translate' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation'
)
);
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
And here are my add and edit functions in PostsController.php:
public function add() {
if ($this->request->is('post')) {
$this->Post->locale = 'fre';
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.', true));
$this->redirect(array('action' => 'admin'));
} else {
$this->Session->setFlash(__('Unable to add your post.', true));
}
}
}
public function edit($id = null) {
$this->Post->id = $id;
if ($this->request->is('get'))
{
$this->Post->locale = 'fre';
$this->request->data = $this->Post->read();
}
else
{
if ($this->Post->save($this->request->data))
{
$this->Post->locale = 'fre';
$this->Session->setFlash(__('Your post has been updated.', true));
$this->redirect(array('action' => 'admin'));
}
else
{
$this->Session->setFlash(__('Unable to update your post.', true));
}
}
}
I initialized the i18n table using Console. Should I drop the table and try reinitializing? Not sure why there would be a problem there.
More reusable solution is to add to your AppModel:
class AppModel extends Model {
public $actsAs = array('Containable');
/**
* Converts structure of translated content by TranslateBehavior to be compatible
* when saving model
*
* #link http://rafal-filipek.blogspot.com/2009/01/translatebehavior-i-formularze-w.html
*/
public function afterFind($results, $primary = false) {
if (isset($this->Behaviors->Translate)) {
foreach ($this->Behaviors->Translate->settings[$this->alias] as $value) {
foreach ($results as $index => $row) {
if (array_key_exists($value, $row)) {
foreach($row[$value] as $locale) {
if (isset($results[$index][$this->alias][$locale['field']])) {
if (!is_array($results[$index][$this->alias][$locale['field']])) {
$results[$index][$this->alias][$locale['field']] = array();
}
$results[$index][$this->alias][$locale['field']][$locale['locale']] = $locale['content'];
}
}
}
}
}
}
return $results;
}
}
This code automatically converts what returns TranslateBehavior to be able to create multi-language form like:
echo $this->Form->input('Category.name.eng');
echo $this->Form->input('Category.name.deu');
echo $this->Form->input('Category.name.pol');
Tested on CakePHP 2.3. And I discovered that now Model->saveAssociated() is required instead of Model->save().
Try to add this in your form on add.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('Post.title.fre');
echo $this->Form->input('Post.body.fre');
//Something more...
echo $this->Form->end(__('Submit'));
?>
in your edit.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('id');
echo $this->Form->input('Post.title.fre', array('value'=>$this->request->data['titleTranslation'][0]['content'));
echo $this->Form->input('Post.body.fre', array('value'=>$this->request->data['bodyTranslation'][0]['content'));
//Something more...
echo $this->Form->end(__('Submit'));
?>
assuming index of data['titleTranslation'][0] is in French, to easily see an array in the view I recommend to use DebugKit https://github.com/cakephp/debug_kit
I hope this will help
Use saveMany instedof save. it's working fine for me.
For those who have the same problem: the correct variable is $actsAs, not $actAs.

Categories