/** * Handle ajax submissions of comments * @param Models\Comment $commentForm */ protected function handleCommentAddition(\GGS\Models\Comment $commentForm) { $formName = \GGS\Helpers\FormHelper::getName(get_class($commentForm)); // ensure its ajax, ensure its ajax and ensure form is set if (WebApplication::$request->isAjaxRequest() && WebApplication::$request->isPostRequest() && ($attributes = WebApplication::$request->getPostParameter($formName))) { $response = array(); // get the comment populated $commentForm->setAttributes($attributes); if ($commentForm->validate()) { // so its valid? lets populate some defaults for response $response['status'] = 'success'; $response['message'] = 'Comment successfully added.'; // already validated so no need to revalidate in save(), also do not throw exception, we need to handle // errors using ajax's error() if ($pk = $commentForm->save(false, false)) { // saved? add the id to response. $response['id'] = $pk; } else { // unable to save record even though its valid? $response['status'] = 'error'; $response['message'] = 'Failed to save Comment record.'; } } else { // invalid form? compiler errors in respo,se. $response['errors'] = $commentForm->getQualifiedErrorMessageWithInputIds(); $response['status'] = 'error'; $response['message'] = 'Please check form for invalid data.'; } // json encode the response and bail out echo json_encode($response); exit; } }
/** * Get all validation errors against the current model object but qualify the keys to be form input ids * @return array */ public function getQualifiedErrorMessageWithInputIds() { // get the form name $formName = \GGS\Helpers\FormHelper::getName(get_class($this)); $qualifiedErrorMessages = array(); foreach ($this->getErrors() as $attribute => $error) { // qualify the key to be input id $inputId = FormHelper::resolveInputId($formName, $attribute); $qualifiedErrorMessages[$inputId] = $error; } return $qualifiedErrorMessages; }