public function process(Request $request) { // Ajax-validation is only possible, if the _formID was submitted (automatically done by the FormBuilder). if (\Request::has('_formID')) { // The FormBuilder should have saved the requestObject this form uses inside the session. // We check, if it is there, and can continue only, if it is. $sessionKeyForRequestObject = 'htmlBuilder.formBuilder.requestObjects.' . \Request::input('_formID'); if (Session::has($sessionKeyForRequestObject)) { // Normally we assume a successful submission and return just an empty JSON-array. $returnCode = 200; $return = []; // We instantiate the requestObject. $formRequest = FormBuilderTools::getRequestObject(Session::get($sessionKeyForRequestObject)); // We instantiate a controller with the submitted request-data // and the rules and messages from the requestObject. $validator = Validator::make(\Request::all(), $formRequest->rules(), $formRequest->messages()); // Perform validation, extract error-messages for all fields on failure, put them inside a $return['errors']-array, and return status code 422. if ($validator->fails()) { $errors = []; foreach (array_dot(\Request::all()) as $fieldName => $fieldValue) { $fieldErrors = FormBuilderTools::extractErrorsForField($fieldName, $validator->errors()->getMessages(), \Request::all()); if (count($fieldErrors) > 0) { $errors[FormBuilderTools::convertArrayFieldDotNotation2HtmlName($fieldName)] = $fieldErrors; } } $return['errors'] = $errors; $returnCode = 422; } return new JsonResponse($return, $returnCode); } } }
/** * If no rules were stated with the rules()-method and stored in the FormBuilder, * but the name of a form request object was stated with the requestObject()-method, * we try getting the rules directly from the form request object. */ protected function task_10_fetchRulesFromRequestObject() { if (count(app()['formbuilder']->rules) === 0 && app()['formbuilder']->requestObject !== null) { $requestObject = FormBuilderTools::getRequestObject(app()['formbuilder']->requestObject); $this->rules($requestObject->rules()); } }