Items custom filters
We've just seen how to retrieve very simple lists of Item objects from the database, but what about when you need to filter the results, join tables, specify extra SQL statements or get an ordered list of Items?
To do so, you can overload the fillFromParameters
method of your Items
class to take care of any additional filtering, ordering or querying you might need for your Item listings.
The Items::fillFromParameters method is in charge of requesting the database and loading the Item objects in the list. It is called internally whenever you create your Items object with the
fillMethod
key set asfromParameters
.
For example, let's say we wanted a way to get movie listings containing only movies released on a specific year. We would overload the fillFromParameters
method of our Movies
object like this:
There are three important things we did here:
Treat parameters: We use the BasicObject::treatParameters helper method to treat the parameters passed via
$p
. In this case, we simply set up a default value offalse
for theyear
parameter. This way of treating parameters might come specially in handy when you have many parameters with default values and requisites.Modify $p accordingly: Because we'll be sending the
$p
parameters array to the parent fillFromParameters method that does all the work, we compose it now according to our special parameters. In this case, if we've got ayear
parameter, we add a newwhere
statement to$p
that will cause the final SQL statement to only request movies from the specified year.Call the parent fillFromParameters: Because we're overloading the fillFromParameters method to add our own Movie-specific logic, we now call the parent fillFromParameters method, which is the one that does the actual work.
With this in place, our Movies
object can now work with movies from a specific year, like this:
See this example working in the Cherrycake documentation examples site.
Last updated