示例#1
0
 /**
  * If current form was submitted, validate and save it
  *
  * Note: This callback can abort script execution if save does redirect
  *
  * @return bool|null
  * @internal
  */
 public function _validate_and_save()
 {
     if ($this->validate_and_save_called) {
         trigger_error(__METHOD__ . ' already called', E_USER_WARNING);
         return null;
     } else {
         $this->validate_and_save_called = true;
     }
     if (!$this->is_submitted()) {
         return null;
     }
     $this->validate();
     if ($this->is_ajax()) {
         $json_data = array();
         if ($this->is_valid()) {
             $json_data['save_data'] = $this->save();
         } else {
             $json_data['errors'] = $this->get_errors();
         }
         $flash_messages = array();
         foreach (FW_Flash_Messages::_get_messages(true) as $type => $messages) {
             $flash_messages[$type] = array();
             foreach ($messages as $id => $message_data) {
                 $flash_messages[$type][$id] = $message_data['message'];
             }
         }
         $json_data['flash_messages'] = $flash_messages;
         /**
          * Important!
          * We can't send form html in response:
          *
          * ob_start();
          * $this->render();
          * $json_data['html'] = ob_get_clean();
          *
          * because the render() method is not called within this class
          * but by the code that created and owns the $form,
          * and it's usually called with some custom data $this->render(array(...))
          * that it's impossible to know here which data is that.
          * If we will call $this->render(); without data, this may throw errors because
          * the render callback may expect some custom data.
          * Also it may be called or not, depending on the owner code inner logic.
          *
          * The only way to get the latest form html on ajax submit
          * is to make a new ajax GET to current page and extract form html from the response.
          */
         if ($this->is_valid()) {
             wp_send_json_success($json_data);
         } else {
             wp_send_json_error($json_data);
         }
     } else {
         if (!$this->is_valid()) {
             return false;
         }
         $this->save();
     }
     return true;
 }