Hi,

I want to add additional data based on response generated, for example if login successful add "repCode:1001", if login failed add "repoCode:1002".

I'm using hook_services_endpoint_response_alter but it is not working, let know if there is any other way to do this.

Thanks

Comments

rakesh falke’s picture

Hi Sharique,
This might help you to add custom formatter.

/**
 * Allows alteration of the response when just the endpoint is requested.
 *
 * @param string $response
 *   The text displayed to the user.
 *
 * @see RESTServer->handle()
 */
function <module-name>_rest_server_response_formatters_alter(&$formatters) {
  $formatters['<formatter-name>']['mime types'][] = 'application/xml';
  $formatters['<formatter-name>']['mime types'][] = 'text/xml';
  $formatters['<formatter-name>']['formatter class'] = 'Services<formatter-name>XMLFormatter';
}

class Services<formatter-name>XMLFormatter implements ServicesFormatterInterface {
  public function render($data) {
    $doc = new DOMDocument('1.0', 'utf-8');
    $root = $doc->createElement('response');
    $doc->appendChild($root);
    $this->xml_recursive($doc, $root, $data);
    return $doc->saveXML();
  }

  private function xml_recursive(&$doc, &$parent, $data) {
    if (is_object($data)) {
      $data = get_object_vars($data);
    }

    if (is_array($data)) {
      $assoc = FALSE || empty($data);
      foreach ($data as $key => $value) {
        if (is_numeric($key)) {
          $key = 'item';
        }
        else {
          $assoc = TRUE;
          $key = preg_replace('/[^A-Za-z0-9_]/', '_', $key);
          $key = preg_replace('/^([0-9]+)/', '_$1', $key);
        }
        $element = $doc->createElement($key);
        $parent->appendChild($element);
        $this->xml_recursive($doc, $element, $value);
      }

      if (!$assoc) {
        $parent->setAttribute('is_array', 'true');
      }
    }
    elseif ($data !== NULL) {
      $parent->appendChild($doc->createTextNode($data));
    }
  }
}

P.S. User < formatter-name > as camelcase for Class name.

kylebrowning’s picture

Status: Active » Closed (fixed)