cakephp save() creating blank entry to database - php

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;

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 Form Validation Not Working

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.

yii captcha not validating properly

Im trying to add a captcha using yii to my contact form, but there is some problem with validation.
My model
class ContactForm extends CFormModel
{
public $verifyCode;
public function rules()
{
return array(
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'captchaRequired'),
array('verifyCode', 'safe'),
);
}
}
Code in my controller
public function filters()
{
return array(
'accessControl',
);
}
public function accessRules()
{
return array(
array( 'allow', //allow all users to perform advertise and index action
'actions' => array('advertise','index', 'captcha'),
'users' => array('*'),
),
);
}
public function actions() {
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha' => array(
'class' => 'CCaptchaAction',
'backColor' => 0xFFFFFF,
'testLimit'=> '2',
),
)
}
public actionAdvertise()
{ $model = new ContactForm;
$model->scenario = 'captchaRequired';
if($model->validate()){
//some code
} else {
$this->render('advertise', array('model' => $model));
}
}
}
Code in my advertise.php view
<form action="" method="post">
<?php
$form=$this->beginWidget('CActiveForm',array(
'id'=>'contact-form',
'enableAjaxValidation'=>false,
));
?>
<?php if(CCaptcha::checkRequirements()){ ?>
<div class="row">
<div class="contact_field_wrapper">
<?php echo '<b>ARE YOU HUMAN?</b><br />'.$form->labelEx($model, 'verifyCode'); ?>
<div class="captcha user-captcha">
<?php $this->widget('CCaptcha',array( 'captchaAction'=>'site/captcha' ));
?>
<?php echo $form->error($model, 'verifyCode'); ?>
<?php echo '<br />'.$form->textField($model,'verifyCode'); ?>
<div class="hint">Please enter the letters as they are shown in the image above.<br/>
Letters are not case-sensitive.
</div>
</div>
</div>
</div>
<?php } ?>
<?php $this->endWidget(); ?>
</form>
The problem is that $model->validate() returns false when correct code in inputted.
$model->getErrors() is always returning 'Verification code is incorrect'.
your model is empty , because you didn't pass any value to $model->attriburtes
Do this :
if($_POST['ContactForm'])
{
$model->attributes() = $_POST['ContactForm'];
if($model->validate())
{
//some code
}
}
$this->render('advertise', array('model' => $model));

cakephp edit action and requests?

So can someone explain this to me?
I'm trying to write an edit action and am a bit unsure of why the following does not work:
public function edit($id = null) {
if (!$id) {
throw new NotFoundException('NO ID HAS BEEN SUPPLIED');
}
$data = $this->User->findById($id);
if(!$this->request->is('post')) { $this->request->data = $data; }
if($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id;
$this->User->save($this->request->data);
$this->redirect(array('action'=>'index'));
}
}
And by not working, I mean, that while it does pre-populate the form with data gathered from findById($id).. it doesn't update the database with the new inputs after the form has been sent.
I have replaced this:
if(!$this->request->is('post'))
With the following:
if($this->request->is('get'))
And suddenly, it works fine. It updates the row with the new values gathered from the post. However, I do not understand what's happening here. Why is it that !$this->request->is('post), does NOT work, while $this->request->is('get') DOES work?
Surely, when the action is first called it is called using a GET request? Doesn't that request qualify as !$this->request->is('post')?
EDIT:
below is the ctp: app/View/Users/edit.ctp
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('edit User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role');
// echo $this->Form->input('role', array(
// 'options' => array('admin' => 'Admin', 'regular' => 'Regular')
//));//
?>
</fieldset> <?php echo $this->Form->end(__('Submit')); ?>
By default Cake uses 'PUT' method for 'edit' action and 'POST' for 'add'. so you need to check $this->request->isPut() (or $this->request->is('put')). Look for a hiiden field *_method* that automatically generated by $this->Form->create() method in your view.
If 'id' property is set in data passed to view Cake creates 'edit' form and 'add' if no 'id'.
Do it this way
public function edit() {
$id = $this->params['id'];
if (!$id) {
throw new NotFoundException('NO ID HAS BEEN SUPPLIED'); }
$data = $this->User->findById($id);
if(!$this->request->is('post')) { $this->request->data = $data; }
if($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id;
$this->User->save($this->request->data);
$this->redirect(array('action'=>'index'));}
passing id to edit from url is not safe way... $this->params['id'] will have your post id so
with it $this->request->is('put') will work.

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');
}

Categories