Reputation: 5248
Am looping teachers relation on template CoursePage.ss
but when i try to loop that relation teachers
inside CouresePage_details.ss
does not work. Am doing somthing wrong.
I have two models Courses
and Teachers
Course
can have many teachhersTeacher
can have one courseCourses.php
class Courses extends DataObject
{
private static $many_many = array(
'Teachers' => 'Teachers',
);
}
Teachers.php
class Courses extends DataObject
{
private static $belongs_many_many = array(
'Courses ' => 'Courses ',
);
}
CoursesPage.php
class CoursesPage extends Page
{
}
class CoursesPage_Controller extends Page_Controller
{
public static $allowed_actions = array(
'details'
);
// Show specific course
public function details(SS_HTTPRequest $request)
{
$c= Courses::get()->byID($request->param('ID'));
if(!$c) {
return $this->httpError(404, "Courses not found");
}
return array(
'Courses' => $c,
);
}
// Courses list
public function CoursesList ()
{
$c = Courses::get()->sort('Featured', 'DESC');
return $c;
}
}
CoursesPage.ss
In this file i just loop courses, nothing important. Here i loop list of courses and teachers. Here teachers looping working perfect just not work on details template.
CoursesPage_details.ss
Here is problem. When i show details about specific course
i want to loop teachers
which is related with this course but i all time get NULL
return Teachers does not exist
. Looks like it is not in scope.
<section class="course-details">
<h2>$Courses.Name</h2> <!-- Work -->
<p>$Courses.Descr</p>
<ul class="teachers-list">
<% if $Teachers %> <!-- Not work here, but on CoursePage.ss work -->
<% loop $Teachers %>
$FirstName
<% end_loop %>
<% else >
Teachers does not exist
<% end_if %>
</ul>
</section>
Upvotes: 2
Views: 42
Reputation: 5875
You need to use $Courses.Teachers
instead… or you could just change the scope to Courses, by using <% with $Courses %>
. So your template would look like this:
<section class="course-details">
<% with $Courses %>
<h2>$Name</h2>
<p>$Descr</p>
<ul class="teachers-list">
<% if $Teachers %>
<% loop $Teachers %>
$FirstName
<% end_loop %>
<% else >
Teachers does not exist
<% end_if %>
</ul>
<% end_with %>
</section>
The reason for this is: You're passing your Course
DataObject to the template as a parameter named Courses
. It's this DataObject that has a relation to Teachers, therefore you need to use $Courses.Teachers
or change the scope as outlined above.
By default, you're still in the scope of CoursesPage
.
Upvotes: 4