Versions:

This document contains information for an outdated version (3.1) and may not be maintained any more. If some of your projects still use this version, consider upgrading as soon as possible.

SearchContext

SearchContext manages searching of properties on one or more DataObject types, based on a given set of input parameters. 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 SearchContext is either a SQLQuery object for further refinement, or a DataObject instance.

SearchContext is mainly used by [ModelAdmin](en/3.1/developer_guides/customising_the_admin_interface/modeladmin/).

Usage

Defining search-able fields on your DataObject.

<?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

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
        );
    }
}

See the SearchFilter documentation for more information about filters to use such as the GreaterThanFilter.

In case you need multiple contexts, consider name-spacing your request parameters by using FieldList->namespace() on the $fields constructor parameter.

Generating a search form from the context

<?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');
    }
}

API Documentation

Was this article helpful?