- Correct internal links between documentation pages - Delete defunct links to documentation removed during documentation reorganization - Restore testing glossary - Verify by crawling site locally
3.0 KiB
title: Scaffolding with SearchContext summary: Configure the search form within ModelAdmin using the SearchContext class.
SearchContext
[api:SearchContext] manages searching of properties on one or more [api:DataObject] types, based on a given set of input parameters. [api:SearchContext] is intentionally decoupled from any controller-logic, it just receives a set of search parameters and an object class it acts on.
The default output of a [api:SearchContext] is either a [api:SQLQuery] object for further refinement, or a [api:DataObject] instance.
Usage
Defining search-able fields on your DataObject.
:::php
<?php
class MyDataObject extends DataObject {
private static $searchable_fields = array(
'Name',
'ProductCode'
);
}
Customizing fields and filters
In this example we're defining three attributes on our MyDataObject subclass: PublicProperty
, HiddenProperty
and MyDate
. The attribute HiddenProperty
should not be searchable, and MyDate
should only search for dates
after the search entry (with a GreaterThanFilter
).
:::php
<?php
class MyDataObject extends DataObject {
private static $db = array(
'PublicProperty' => 'Text'
'HiddenProperty' => 'Text',
'MyDate' => 'Date'
);
public function getCustomSearchContext() {
$fields = $this->scaffoldSearchFields(array(
'restrictFields' => array('PublicProperty','MyDate')
));
$filters = array(
'PublicProperty' => new PartialMatchFilter('PublicProperty'),
'MyDate' => new GreaterThanFilter('MyDate')
);
return new SearchContext(
$this->class,
$fields,
$filters
);
}
}
Generating a search form from the context
:::php
<?php
..
class Page_Controller extends ContentController {
public function SearchForm() {
$context = singleton('MyDataObject')->getCustomSearchContext();
$fields = $context->getSearchFields();
$form = new Form($this, "SearchForm",
$fields,
new FieldList(
new FormAction('doSearch')
)
);
return $form;
}
public function doSearch($data, $form) {
$context = singleton('MyDataObject')->getCustomSearchContext();
$results = $context->getResults($data);
return $this->customise(array(
'Results' => $results
))->renderWith('Page_results');
}
}
Related Documentation
API Documentation
- [api:SearchContext]
- [api:DataObject]