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.
Related
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)) ?>
i am developing with cakephp (2.4.7) and i have a problem with a form action link.
I'm having a usersController with edit action.
public function edit($id = null, $slug = null) {
if (!$id) {
throw new NotFoundException(__('Invalid User'));
}
$user = $this->User->findById($id);
if (!$user) {
throw new NotFoundException(__('Invalid User'));
}
if ($this->request->is(array('post', 'put'))) {
// Do stuff here
}
// Fill the form
if (!$this->request->data) {
$this->request->data = $user;
}
}
with this code the form ($this->create->('User')); in the edit view get filled correctly. But i have another form in the edit view.
Like:
echo $this->Form->create(null, array(
'url' => array('controller' => 'useraddresses', 'action' => 'add')
));
echo $this->Form->input('searchvalue');
echo $this->Form->hidden('country');
echo $this->Form->hidden('city');
echo $this->Form->end('save');
When i click the send button from this form, the page links to /useraddresses/add/2 (2 is the id of the user)
I have debuged the form with firebug and in the action parameter is also /useraddresses/add/2.
How can i get arround this? I will to send the form to /useraddresses/add without any parameters.
If i delete this piece of code in my edit action, the action link is correctly but my first form does not get filled.
// Fill the form
if (!$this->request->data) {
$this->request->data = $user;
}
Use following
if(empty($this->data) )
{
if (!$this->request->data) {
$this->request->data = $user;
}
}
Instead of ur
if (!$this->request->data) {
$this->request->data = $user;
}
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.
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');
}
I've noticed that their is many different ways to pass an ID to a form when editing a database entry. So for example for a edit user profile form I have the following code:
function edit($id = null)
{
$this->layout = 'page';
// this line isn't needed?
//$this->User->id = $id;
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your profile has been updated', 'flash', array('header' => 'Announcement', 'myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'view', $id));
}
}
}
Now the function expects an id passing in the url e.g. /users/edit/2 But let's say I wanted it to be something more user friendly like /profile/edit (rewrote by routing) I would no longer be passing in the ID as part of the url. As you can see in my code I have a line I have commented out because it isn't needed?
Also in the form I ALSO Need <?php echo $this->Form->input('id', array('type' => 'hidden')); ?> why?
Basically this is more of what are the options available to me to build various types of edit forms and passing data to the form. And what is the need for the hidden field in the form if the data is being passed either via the URL or some other way
I've also noticed on some sites that they have things like Form Keys and the username stored in meta tags in the page header???
EDIT:
public function beforeFilter()
{
$this->set('authUser', $this->Auth->user());
//
$user = $this->Auth->user();
if (!empty($user))
{
Configure::write('User', $user[$this->Auth->getModel()->alias]);
}
}
public function beforeRender()
{
$user = $this->Auth->user();
if (!empty($user))
{
$user = $user[$this->Auth->getModel()->alias];
}
$this->set(compact('user'));
}
// NEW VERSION
function settings()
{
$this->layout = 'page';
$this->set('title_for_layout', 'Edit Profile');
$this->User->id = $user['id'];
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your settings have been updated', 'flash', array('myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'settings'));
}
}
}
Also in the form I ALSO Need Form->input('id',
array('type' => 'hidden')); ?> why?
Having the id hidden in the form removes the need for your controller action to grab the $id from the uri (aka passed as parameter). When in the form, it will automatically be placed into your $data array.
what is the need for the hidden field
in the form if the data is being
passed either via the URL or some
other way
It's not needed in the form if it's available from the uri. You'd simply grab the $id and assign it to the User model (as the commented out code does).
let's say I wanted it to be something
more user friendly like /profile/edit
I assume that would be when the user is editing his own profile. In that case, your system should be able to retrieve the user's id via the session.