Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Problems with maintaining One to Many relations


Reply


2 Posts   950 Views

Avatar
PeeJay

Community Member, 8 Posts

15 June 2009 at 5:49pm

Hi,

As part of exercising tutorial-5, I have created Mentor and Student classes with one to many relation between Mentor to Student.

Every thing is working fine except that MyMentorID column in Student table always shows 0. It beleive it should store the ID of Mentor object which it beongs to. Is that correct? Any idea where the problem lies?

The code for Mentor and Student classes is shown below:

Mentor.php:
-------------
<?php
class Mentor extends Page {
   public static $db = array(
      'FirstName' => 'Text',
      'LastName' => 'Text',
      'Nationality' => 'Text'
   );

   static $has_many = array(
      'Students' => 'Student'
   );

   function getCMSFields() {
      $fields = parent::getCMSFields();
      $fields->addFieldToTab( 'Root.Content.Main', new TextField( 'FirstName', 'First Name' ) );
      $fields->addFieldToTab( 'Root.Content.Main', new TextField( 'Lastname' ) );
      $fields->addFieldToTab( 'Root.Content.Main', new TextField( 'Nationality' ) );
      $tablefield = new HasManyComplexTableField(
         $this,
         'Students',
         'Student',
         array(
            'FirstName' => 'FirstName',
            'Lastname' => 'Family Name',
            'Nationality' => 'Nationality'
         ),
         'getCMSFields_forPopup'
      );
      $tablefield->setAddTitle( 'A Student' );   
      $fields->addFieldToTab( 'Root.Content.Students', $tablefield );
      return $fields;
   }   
}
class Mentor_Controller extends Page_Controller {
}
?>

Student.php:
-------------
<?php
class Student extends DataObject {
   public static $db = array(
      'FirstName' => 'Text',
      'LastName' => 'Text',
      'Nationality' => 'Text'
   );
   static $has_one = array (
      'MyMentor' => 'Mentor'
   );
   function getCMSFields_forPopup() {
      $fields = new FieldSet();
      $fields->push( new TextField( 'FirstName', 'First Name' ));
      $fields->push( new TextField( 'LastName', 'Last Name' ));
      $fields->push( new TextField( 'Nationality', 'Nationality' ));
      return $fields;
   }
}
?>

Regards
PeeJay

Avatar
Hamish

Community Member, 712 Posts

15 June 2009 at 9:55pm

Once you've added the student, you might also have to tick the checkbox next to their name in the tablefield from the Mentor page.