Skip to content

9.4. Filter on term name

Dane Rossenrode edited this page Apr 9, 2016 · 1 revision

Problem:

You know the machine name of a term, but you do not know the term ID. Currently, you can only filter on term ID

Works: [site]/api/v1.0/[resource-name]?filter[issues]=[tid]

Does Not Work: [site]/api/v1.0/[resource-name]?filter[issues]=[term-name]

Background:

You have a publication website. The publication website has issues, with a vocabulary name publication_issue You have setup and endpoint @ [site]/api/v1.0/publication_issues

Say you have a URL alias of http://[site]/issues/[term-name] and you want to load the load the term. Right now you you only know the term's name. You sent an API call to http://[site]/api/v1.0/publication_issues?filter[issue]=[term-name] with the following code inside your publication_issues class.

  /**
   * Overrides RestfulEntityBaseNode::publicFieldsInfo().
   */
  public function publicFieldsInfo() {
    $public_fields['issue'] = array(
      'property' => 'field_issue',
    );
  ....

  }
  /**
   * Overrides parent filter the query for list.
   *
   * @param \entityfieldquery $query
   *   the query object.
   *
   * @throws \restfulbadrequestexception
   *
   * @see \restfulentitybase::getqueryforlist
   */
  protected function queryforlistfilter(\entityfieldquery $query) {
    foreach ($this->parserequestforlistfilter() as $filter) {
      if ($filter['public_field'] == 'issue' && !is_numeric($filter['value'][0])) {
        // Issue is the url friend machine name.  Replace it with its tid.
        $request = $this->getRequest();
        $term = taxonomy_term_machine_name_load(str_replace('-', '_', $filter['value'][0]), 'publication_issue');
        $request['filter']['issue'] = $term->tid;
        $this->setRequest($request);
      }
    parent::queryforlistfilter($query);;
  } 

This is dependent on having https://www.drupal.org/project/taxonomy_machine_name installed and enabled.

If you have a url http://[site]/issues/report-on-giving then it returns the term with a machine name match of report_on_giving.

Note: The term's machine name does not always match the URL. By default if a term name is "Report on Giving", then the machine name will be "report_on_giving" however the url pattern will strip the "on" out, and the url alias will be "http://[site]/issues/report-giving". To get around this you have to do one of the follow:

  • make the machine different from the term name.
  • Create a custom hook on term_save() where you strip out the path alias patterns from the machine name.
  • Disable stripping of common words from the url alias.
Clone this wiki locally