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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

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

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

Problems with maintaining One to Many relations


Go to End


2 Posts   1527 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.