Monday, September 22, 2014

cant add new record in HABTM table

  I want to add a new record in a table called TutorsSubject. This table is created from HABTM relationship of Tutor and Subject. Anyway I load the subject names in a text box and I can select a subject name but I cant add a new record. I need to set the id of the tutor_id.
There are 3 fields in the tutorsSubject table called id,tutor_id and subject_id. I only need to select  in 1 field which is the subject_id from a list of names found in the subject table, and then set the tutor_id manually.

Currently I am able to select from a list of subject names but I cant add a new record with the subject name and set tutor_id.

Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

class TutorsSubjectsController extends AppController {
  
 public function tutoradd() {

     $this->loadModel('Subject'); 
             
             $options['recursive']=-1;
               $options['fields']=array('Subject.name');
              $te2= $this->Subject->find('list',$options);
         debug($te2);
        $this->set( 'te',$te2);
          
          
 
            
    //put is for edit and post for new record
        if ($this->request->is('post')) {
       
              $this->request->data['TutorsSubject']['tutor_id']=2;
            debug($this->request->data);
            if ($this->TutorsSubject->save($this->request->data)) {
                $this->Session->setFlash(__('Your post has been updated.'));
                return $this->redirect(array('controller' => 'tutors','action' => 'tutordetails'));
            }
            $this->Session->setFlash(__('Unable to update your post.'));
        }


       //View which works fine as it displays the list
               echo $this->Form->create('TutorsSubject', array('type' => 'post'));
           
           
                echo $this->Form->input('tutorsSubject.subject_id', array('options' => $te));
                 echo $this->Form->end('Save Post');

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: