How to loop 2 function in template?

Silverstripe Version: 4.2

How to loop 2 different functions in the template ?

Two functions are,

  1. fnProduct
  2. fnProductType
    How to loop 1 function in 2 functions? I want to access fnProductType ID in fnProduct to filter the products.
<% loop fnProductType %>
    <% loop fnProduct %>
   		<% if TypeID == $Up.ID %>
   		    Filter Products here...
   		 <% end_if %> 
	<% end_loop %>
<% end_loop %>

I try to access fnProductType ID using $Up, but it does not give any result.

Hi @Amit_Gajare

fnProductType is either a DataList or an ArrayList, therefore $Up.ID won’t give you anything (for these two types don’t have IDs by default)

So I suppose that what you are seeking is the ID of the current page? (If the current controller binds to a page), then try $Top.ID


Hi @leochenftw,
Thank you for your suggestion.

  1. fnProductType and fnProduct both are DataList.
  2. I want to use fnProductType ID in fnProduct to compare TypeID of Product and get those product which is match.

If you have the dataobjects set up, and linked via relations, you shouldn’t need to call any additional functions. Similar to your previous question, the ORM does most of the hard work for you.

Assuming ProductType -> many_many -> Product

Then you can just loop then in the template:

<!--  Loop through all the ProductType objects -->
<% loop $ProductTypes %>
  <!-- For each ProductType, you can automatically access the related Product objects -->
  <% loop $Products %>
   <!-- This is now in the Product scope, so you can access the data defined on those objects -->
    <p>Product name: $Title</p>
    <p>SKU: $SKU</p>
  <% end_loop %>
<% end_loop %>

Depending on how your pages are structured, you’d need a function which returns the ProductType objects… that could be as simple as:

public function getProductTypes() {
  return ProductType::get()->order('Title');