Retrieving has_many data from a different page type in Silverstripe

Hey there, I'm diving into Silver Stripe development and PHP/MySQL for the first time. So bear with me as I navigate through this new territory.

I've got a project that demands a pricing page showcasing various plans on both the pricing page and homepage. My aim is to retrieve data from my Pricing.php page type using my HomePage.ss.

To make this setup future-proof, I decided to create a ServicePlan.php. This file extends DataObject and utilizes a FieldList to establish pricing records linked to the Pricing page type via a $has_many and $has_one relationship. Based on my current knowledge, this seems like the most effective approach.

Below is the code snippet I've written:

ServicePlan.php

class ServicePlan extends DataObject {

private static $db = array (
    'PlanColor' => 'Varchar',
    'PlanName' => 'Varchar',
    'PlanPrice' => 'Varchar',
    'PlanRenewal' => 'Varchar',
);

private static $has_one = array (
    'Pricing' => 'Pricing'
);
private static $summary_fields = array (
    'PlanName' => 'Name of Plan',
    'PlanPrice' => 'Price',
    'PlanRenewal' => 'Renewal Period',
);
public function getCMSFields() {
    $fields = FieldList::create(
        TextField::create('PlanName'),
        TextField::create('PlanRenewal'),
        TextField::create('PlanPrice'),
        TextField::create('PlanColor')
    );
    return $fields;
}

public function getServicePlans() {
    return $this->Pricing();
}

Pricing.php

class Pricing extends Page {
private static $has_many = array (
    'ServicePlans' => 'ServicePlan',
);

public function getCMSFields() {
    $fields = parent::getCMSFields();


    $fields->addFieldsToTab('Root.Plans', GridField::create(
        'ServicePlans',
        'Orenda Force Service Plan Information',
        $this->ServicePlans(),
        GridFieldConfig_RecordEditor::create()
    ));

    return $fields;
    }
}

class Pricing_Controller extends Page_Controller {

}

HomePage.php

class HomePage extends Page {
}

class HomePage_Controller extends Page_Controller {
    public function ServiceTeasers($count = 2) {
        $holder = ServicesHolder::get()->First();
        return ($holder) ? ServicesPage::get()->limit($count) : false;
    }

    public function MembershipPlans() {
        $Pricing = Pricing::get();
        return $plan;
    }
}

Layout/HomePage.ss

...//

<% loop $MembershipPlans %>
    <div class="col-1-3 card pricing">
        <div class="pricing__header  primary $PlanColor">
            <p class="pricing__plan-name">$PlanName</p>
            <p class="pricing__price">$PlanPrice<sub>$PlanRenewal</sub></p>
        </div>
        <div class="card__contents">
            <h3 class="title-06">Plan details</h3>
            <ul>
                <li>unlimited training</li>
                <li>individual nutrition/meal plans</li>
            </ul>
        </div>
    </div>
    $Content
<% end_loop %>

...//

Currently, I have no trouble accessing the content.

Layout/Pricing.ss

<section class="body pricing">
    <div class="content">
    <h2 class="title-02 text-monochrome">Pricing</h2>
        <% loop $ServicePlans %>
            <div class="col-1-3 card pricing">
                <div class="pricing__header $PlanColor">
                    <p class="pricing__plan-name">$PlanName</p>
                    <p class="pricing__price">$PlanPrice<sub>$PlanRenewal</sub></p>
                </div>
                <div class="card__contents">
                    <h3 class="title-06">Plan details</h3>
                    <ul>
                        <li>unlimited training</li>
                        <li>individual nutrition/meal plans</li>
                    </ul>
                </div>
            </div>
        <% end_loop %>
    </div>
</section>

Your guidance means the world to me. I've been wrestling with this challenge for days now, but I keep hitting roadblocks. Any insights on where I might be going wrong?

This question sheds some light on similar issues, but it didn't quite solve mine. Do you think moving the FieldList to the Pricing.php page could be a solution?

Answer №1

It appears that the homepage already contains most of the necessary elements. The only thing missing is the loop for the has_many relationship similar to what the Price page has. By utilizing the MembershipPlans() function in the HomePage_Controller which returns all price pages as a DataList, you can access related objects by iterating through the relation name, like <% loop $ServicePlans %>.

HomePage.ss

<% loop $MembershipPlans %><!-- loop Price pages -->
<% loop $ServicePlans %><!-- this is where you iterate through ServicePlans related to a specific Price page -->
<div class="col-1-3 card pricing">
    <div class="pricing__header primary $PlanColor">
        <p class="pricing__plan-name">$PlanName</p>
        <p class="pricing__price">$PlanPrice<sub>$PlanRenewal</sub></p>
    </div>
    <div class="card__contents">
        <h3 class="title-06">Plan details</h3>
        <ul>
            <li>unlimited training</li>
            <li>individual nutrition/meal plans</li>
        </ul>
    </div>
</div>
<% end_loop %><!-- end ServicePlans relation loop -->
$Content<!-- Content specific to the Price page -->
<% end_loop %><!-- end Price pages loop -->

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Command for optimizing tables

Looking for some advice on optimizing tables in a database while running a code. Each table takes between 3-5 minutes to execute, so I need the next table to start once the previous one is done. Any recommendations? const optimizeQuery = 'OPTIMIZE TAB ...

Retrieve the boolean value associated with a checkbox

I inherited a project from another developer. The code is able to retrieve data from the text input fields in the form, but not from the checkbox inputs. The previous developer implemented these functions (among others): protected function getObjectStrin ...

Modify the address fields settings for Checkout and My Account based on the country in Woocommerce

I've implemented code to adjust checkout address fields for more accurate formats in various countries. The segment that updates the labels for UK and New Zealand states is not functioning properly though. In the UK, the County (optional) field retain ...

Incorporating the MVC architecture into Rails framework is essential

Before diving into my project, I want to clarify something to avoid bad coding practices. As someone who has experience with Ruby on Rails, I am wondering if PHP can achieve similar functionality without the need for frameworks like Zend or Yii. In my und ...

Storing dropdown selection as a variable in a PHP Ajax form

I have created a PHP form that allows the user to select an option from a dropdown menu in order to view a specific data set. The data is refreshed on the screen using an AJAX call and I am utilizing the 'html' datatype to update the output withi ...

Sending data from a Chrome extension to a PHP script via a form

In the process of developing a straightforward extension, I am attempting to extract data from an HTML form and transmit it to a PHP file followed by storing it in a database. Here is a snippet of my manifest.json: { "manifest_version": 2, "name": "S ...

What is causing Apache to not start after PHP7 installation?

After encountering issues with the PHP version on my macOS Sierra system, I decided to upgrade to PHP 7.1.4 by building it from the source. To do this, I performed a fresh install by first removing the old PHP and then downloading the source code from php. ...

Two concurrent Ajax requests are not executing simultaneously

I have implemented two ajax calls using jQuery. The first call takes a bit longer to complete, so I decided to make another ajax request (second) to get the progress status in returns. However, I noticed that the second ajax requests are getting stuck in a ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

Query Laravel 5 Eloquent to fetch records from Table 1 that do not have a corresponding relationship in Table 2 where the Table 2 id is equal to x

I am in search of a method similar to has() that will allow me to accomplish the following: Retrieve all users from the users table who do not have a link with the subscriptions table when subscriptions.id = x For example, a user may be linked to subscri ...

Accessing data from FTP servers in WordPress

Searching for a solution to retrieve a file from an FTP server within a WordPress shortcode. Prior to working on the WP shortcode, I tested my code in a non-WP setting and it functioned correctly. After transferring the code into the WP shortcode, issues ...

Error in MySQL: The column 'variable' is not recognized in the 'field list'

I'm facing an issue with a function that returns a constant value. Below is the code snippet of my class and function: class Backlinks extends GoogleSearch { const ROBOTS_NOINDEX_NOFOLLOW = 606; function robotsNoIndexNoFollow(){ $crawler = n ...

Should I incorporate PHP/HTML code or opt for using a function instead?

I'm currently exploring the most effective method for integrating HTML/PHP code into various pages, such as headers, footers, and other repetitive sections. Would it be better to use include_once(php file) (even if it's used multiple times on a ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Efficiently storing data with AJAX and PHP

I have a unique form structure: <form action="" method="post" id="myForm"> <?php foreach ($array as $value) { ?> <input type="text" name="myInput[]" id="myInput" value="<?php $value->data1 ?>"/> <textarea name="myTe ...

Challenges encountered while implementing Shippo API in Laravel: Unable to retrieve any data, only

I am currently working on integrating Shippo to calculate shipping costs within the order process. My tech stack includes Laravel 5.4 with shippo-php. This pertains to a test environment where I have activated a Purolator Carrier in "Test-Mode". Upon ent ...

File remains visible after deletion upon refreshing the page, but disappears after using the Ctrl + F5

After deleting a file on the server, I noticed that it still appeared when I refreshed the page. However, when I tried to do a hard refresh by pressing ctrl+F5, it resulted in a 404 error. This behavior is puzzling to me - shouldn't a simple refresh s ...

Executing SQL queries simultaneously

Currently, I have this code that contains 3 SQL queries running one after the other. However, the query execution time is quite high. So, I've been wondering if there's a way to run all these queries in parallel and then return the results altoge ...

Executing a PHP command within the Symfony framework

I have recently transitioned from using Symfony 1 and NetBeans IDE to wanting to learn Symfony 2. In Netbeans, I was able to use Symfony commands with just a click. Now, I am eager to begin my journey with Symfony 2. You can find more information on Symf ...