/**
  * Returns the appropriate response up the controller chain
  * if {@link validate()} fails (which is checked prior to executing any form actions).
  * By default, returns different views for ajax/non-ajax request, and
  * handles 'application/json' requests with a JSON object containing the error messages.
  * Behaviour can be influenced by setting {@link $redirectToFormOnValidationError},
  * and can be overruled by setting {@link $validationResponseCallback}.
  *
  * @return HTTPResponse|string
  */
 protected function getValidationErrorResponse()
 {
     $callback = $this->getValidationResponseCallback();
     if ($callback && ($callbackResponse = $callback())) {
         return $callbackResponse;
     }
     $request = $this->getRequest();
     if ($request->isAjax()) {
         // Special case for legacy Validator.js implementation
         // (assumes eval'ed javascript collected through FormResponse)
         $acceptType = $request->getHeader('Accept');
         if (strpos($acceptType, 'application/json') !== FALSE) {
             // Send validation errors back as JSON with a flag at the start
             $response = new HTTPResponse(Convert::array2json($this->validator->getErrors()));
             $response->addHeader('Content-Type', 'application/json');
         } else {
             $this->setupFormErrors();
             // Send the newly rendered form tag as HTML
             $response = new HTTPResponse($this->forTemplate());
             $response->addHeader('Content-Type', 'text/html');
         }
         return $response;
     } else {
         if ($this->getRedirectToFormOnValidationError()) {
             if ($pageURL = $request->getHeader('Referer')) {
                 if (Director::is_site_url($pageURL)) {
                     // Remove existing pragmas
                     $pageURL = preg_replace('/(#.*)/', '', $pageURL);
                     $pageURL = Director::absoluteURL($pageURL, true);
                     return $this->controller->redirect($pageURL . '#' . $this->FormName());
                 }
             }
         }
         return $this->controller->redirectBack();
     }
 }
 /**
  * Returns a json array of a search results that can be used by for example Jquery.ui.autosuggestion
  *
  * @param GridField $gridField
  * @param HTTPRequest $request
  * @return string
  */
 public function doSearch($gridField, $request)
 {
     $dataClass = $gridField->getModelClass();
     $allList = $this->searchList ? $this->searchList : DataList::create($dataClass);
     $searchFields = $this->getSearchFields() ? $this->getSearchFields() : $this->scaffoldSearchFields($dataClass);
     if (!$searchFields) {
         throw new LogicException(sprintf('GridFieldAddExistingAutocompleter: No searchable fields could be found for class "%s"', $dataClass));
     }
     $params = array();
     foreach ($searchFields as $searchField) {
         $name = strpos($searchField, ':') !== FALSE ? $searchField : "{$searchField}:StartsWith";
         $params[$name] = $request->getVar('gridfield_relationsearch');
     }
     $results = $allList->subtract($gridField->getList())->filterAny($params)->sort(strtok($searchFields[0], ':'), 'ASC')->limit($this->getResultsLimit());
     $json = array();
     Config::nest();
     SSViewer::config()->update('source_file_comments', false);
     $viewer = SSViewer::fromString($this->resultsFormat);
     foreach ($results as $result) {
         $title = html_entity_decode($viewer->process($result));
         $json[] = array('label' => $title, 'value' => $title, 'id' => $result->ID);
     }
     Config::unnest();
     return Convert::array2json($json);
 }
 /**
  * REST endpoint to get a list of campaigns.
  *
  * @return HTTPResponse
  */
 public function readCampaigns()
 {
     $response = new HTTPResponse();
     $response->addHeader('Content-Type', 'application/json');
     $hal = $this->getListResource();
     $response->setBody(Convert::array2json($hal));
     return $response;
 }
 public function getAttributes()
 {
     return ['data-editor' => 'tinyMCE', 'data-config' => Convert::array2json($this->getConfig())];
 }
 public function Field($properties = array())
 {
     $config = array('showcalendar' => $this->getConfig('showcalendar'), 'isoDateformat' => $this->getConfig('dateformat'), 'jquerydateformat' => DateField_View_JQuery::convert_iso_to_jquery_format($this->getConfig('dateformat')), 'min' => $this->getConfig('min'), 'max' => $this->getConfig('max'));
     // Add other jQuery UI specific, namespaced options (only serializable, no callbacks etc.)
     // TODO Move to DateField_View_jQuery once we have a properly extensible HTML5 attribute system for FormField
     $jqueryUIConfig = array();
     foreach ($this->getConfig() as $k => $v) {
         if (preg_match('/^jQueryUI\\.(.*)/', $k, $matches)) {
             $jqueryUIConfig[$matches[1]] = $v;
         }
     }
     if ($jqueryUIConfig) {
         $config['jqueryuiconfig'] = Convert::array2json(array_filter($jqueryUIConfig));
     }
     $config = array_filter($config);
     foreach ($config as $k => $v) {
         $this->setAttribute('data-' . $k, $v);
     }
     // Three separate fields for day, month and year
     if ($this->getConfig('dmyfields')) {
         // values
         $valArr = $this->valueObj ? $this->valueObj->toArray() : null;
         // fields
         $fieldNames = Zend_Locale::getTranslationList('Field', $this->locale);
         $fieldDay = NumericField::create($this->name . '[day]', false, $valArr ? $valArr['day'] : null)->addExtraClass('day')->setAttribute('placeholder', $this->getConfig('dmyplaceholders') ? $fieldNames['day'] : null)->setMaxLength(2);
         $fieldMonth = NumericField::create($this->name . '[month]', false, $valArr ? $valArr['month'] : null)->addExtraClass('month')->setAttribute('placeholder', $this->getConfig('dmyplaceholders') ? $fieldNames['month'] : null)->setMaxLength(2);
         $fieldYear = NumericField::create($this->name . '[year]', false, $valArr ? $valArr['year'] : null)->addExtraClass('year')->setAttribute('placeholder', $this->getConfig('dmyplaceholders') ? $fieldNames['year'] : null)->setMaxLength(4);
         // order fields depending on format
         $sep = $this->getConfig('dmyseparator');
         $format = $this->getConfig('dateformat');
         $fields = array();
         $fields[stripos($format, 'd')] = $fieldDay->Field();
         $fields[stripos($format, 'm')] = $fieldMonth->Field();
         $fields[stripos($format, 'y')] = $fieldYear->Field();
         ksort($fields);
         $html = implode($sep, $fields);
         // dmyfields doesn't work with showcalendar
         $this->setConfig('showcalendar', false);
     } else {
         $html = parent::Field();
     }
     return $html;
 }
 /**
  * Tests {@link Convert::xml2raw()}
  */
 public function testArray2JSON()
 {
     $val = array('Joe' => 'Bloggs', 'Tom' => 'Jones', 'My' => array('Complicated' => 'Structure'));
     $encoded = Convert::array2json($val);
     $this->assertEquals('{"Joe":"Bloggs","Tom":"Jones","My":{"Complicated":"Structure"}}', $encoded, 'Array is encoded in JSON');
 }