1
votes

I have a problem using Silverstripe CMS. I have basic SQL query of which results I would like to display in <ul><li> menu. It should be really easy but I failed while browsing documentation. I found some more complex examples (Project, Students), but it seems to me that should exists some easier way to do this. Can anyone help or please give me a hint?

To sum up: I would like to run a db sql query and display data as list.

My WishPage.php

class WishPage extends Page {
    // some code which is irrelevant for this matter, but works fine
}

class WishPage_Controller extends Page_Controller {

    private static $allowed_actions = array('AddNewWishForm');

    public function AddNewWishForm() {
        // here you can add data to db
    }

    // Now I would like to show it; and here is the problem.
    public function ShowWishList() {
    $records = DB::query ("SELECT Title FROM Wishes;");
    return $records;
    }

}

My template WishPage.ss

<% include SideBar %>
<div class="content-container unit size3of4 lastUnit">

<div id="WishForm">
    <h2>Try it</h2>
    $AddNewWishForm
</div>

</div>

Update
My Wishes.php

<?php
class Wishes extends DataObject {
    private static $db = array(
        'Name' => 'Text',
        'Comment' => 'Text'
    );
}
2

2 Answers

2
votes

You can just use the SS built-in functionality to fetch the entries from the DB:

// returns the list of all wishes
public function ShowWishList() {
    return Wishes::get();
}

and in the frontend you can just:

<ul>
<% loop $ShowWishList %><li>$Name: $Comment</li><% end_loop %>
</ul>

This requires that you have a list of DataObjects of course.

1
votes

Decision of spekulatius should work well.

If you wont try with SQLQuery

public function getWishes(){
    $query = new SQLQuery();
    $query->setFrom('Wishes')->setSelect('"Name", "Comment"');
    //$query->addWhere('');
    $result = $query->execute();
    //Debug::show($result);
    $list = ArrayList::create();
    foreach($result as $row) {
        $list->push($row);
    }
    return $list;
}

in theme

<ul>
    <% loop $getWishes %><li>$Name: $Comment</li><% end_loop %>
</ul>