Basic CakePHP: Edit Post Method become Add Post Method

95 views Asked by At

Currently following the blog tutorial however my database and their variable are different.

I was looking through the "Edit Post" method and follow the step they given however they turn into "Add Post" method.

What is the reason that cause it ? (I have set the hidden field at view pass to controller however they will show the error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '45' for key 'PRIMARY' because they doing insert statement instead of update).

DateOfEventController.php

public function edit($id = null) {
    //Retrieve from database
    $post = $this->dateofevent->findByeventdateId($id);
    debug($post);    

    //Without Id
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    //If  Not Exist the id
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }

    //After press the submit
    if ($this->request->is(array('post','put'))) {
        echo "yo";
        $this->dateofevent->eventDate_id = $id;
        if ($this->dateofevent->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been updated.'));
           // return $this->redirect(array('action' => 'index'));
        }

        else{$this->Session->setFlash(__('Unable to update your post.'));}
    }

    //Set the data same as retrieved
    if (!$this->request->data) { $this->request->data = $post;}
}

edit.ctp

<?php
echo $this->Form->create('dateofevent');
//echo $this->Form->input('eventDate_id', array('type' => 'hidden'));
echo $this->Form->hidden('eventDate_id');
echo $this->Form->input('event_date',array(
    'label' => 'Event Date',
    'type' => 'text',
    'id' => 'datepicker'));
echo $this->Form->end('Save Post');
?>

Sql Query

SQL Query: INSERT INTO fyp_seatmanagment.dateofevent (eventDate_id, event_date, modified) VALUES (45, '2015-06-10', '2015-06-17 10:19:45')

1

There are 1 answers

1
drmonkeyninja On BEST ANSWER

You're not using Cake's standard naming conventions so you need to make sure you override model attributes that Cake would normally auto-generate. Cake expects the primaryKey to be id which it uses to determine whether to insert or update a record. As you're using eventDate_id you need to tell Cake this in your model:-

class DateOfEvent extends AppModel {
    public $primaryKey = 'eventDate_id';
}

Unless there is a specific reason why you can't use Cake's naming convention you should do. Using your own naming convention will create considerable more work for you and problems.

I've also noticed you're incorrectly camel casing methods and variable names in your controller that may cause problems. For example $post = $this->dateofevent->findByeventdateId($id) should be:-

$post = $this->DateOfEvent->findByEventdateId($id);