I am new to moodle and trying to customize my course creation in moodle.
I validated by moodle_form data in a function and from there I need to throw an error which will be displayed after the form (course/edit_form.php) is submitted. I tried the moodle way, as they have done:
throw new moodle_exception('refresher_value_less_than_one', '', '', $data->refresh_value);
I expected it to receive the error at the form page. It showed be the error string but not inside the form, but on a blank page.
Any idea, how to catch this exception in form.?
If you want to show an error within the form, then you need to create a function within your form class called 'validation($data, $files)'. Within this form, you need to check the values in the array $data, then return an array of error messages, indexed by the form field that the error should display beside.
For example, if you had a field called 'myfield', you could check the contents of $Data['myfield'] and, if there was a problem, return array('myfield' => get_string('myfielderror', 'myplugin')).
Throwing an exception will immediately halt the execution of the page and output only that error message.
Related
I have a set of custom fields as part of the user that need to be validated by an API before being saved. For this I am using the user_profile_update_errors hook. The errors are correctly returned to the admin, but the fields are saved regardless of the errors. According to the description of this hook the fields should only be saved if the error array is empty, but this does not seem to be the case.
I have created a very simple script to test this. It contains the following code:
if (!function_exists("testEditUser")) {
function testEditUser(WP_error $errors, bool $update, stdClass $user) {
$errors->add("test_error", "A test error occured");
}
}
add_action('user_profile_update_errors', 'testEditUser', 20, 3);
This script seems to work fine as when I update a user an error is shown after the page loads again
But when I look at the fields that I "tried to change" they actually changed. Not only on the frontend, but also in the database. When I reload the page I am shown this:
I am unsure if this is related.
I am using Woocommerce and Jet Engine for some of the custom fields. Could these plugins be the source of the problem? Should I use a different hook? Any form of help would be appreciated!
Hopefully this makes sense to someone.
I'm using Kartik-V Select2 widgets in a ActiveForm, with 'multiple' and 'tags' enabled. I'm using this elsewhere in my application and it is working fine there, and on submission the array data is sent as I would expect in the appropriate form field. From there I can easily implode the array and save to database in the controller action.
However in a different section of my app, with exactly the same configuration in the view, model and controller, the array is being posted as an additional form field (as can be seen watching the post event in the firefox console).
What I'm seeing in the firefox console is:
-----------------------------366976194315951562394252057249
Content-Disposition: form-data; name="Notes[notes_to]"
-----------------------------366976194315951562394252057249
Content-Disposition: form-data; name="Notes[notes_to][]"
admin
-----------------------------366976194315951562394252057249
Content-Disposition: form-data; name="Notes[notes_to][]"
kennettm
So where I would expect to receive the array in Notes[notes_to], it is actually coming through in Notes[notes_to][] but I can't for the life of me figure out how to access and handle these values in my controller, or how to get the array of tags submitted in Notes[notes_to] where I want it.
Thanks in advance.
***** EDIT *******
Thanks #Muhammed. I am expecting to received an array ['admin','kennettm'] (as with other areas of my app where I've used this setup), however in this instance that is not what is happening.
I've got the model and CRUD generated by Gii for the Notes section, so it does have its own MVC setup however the notes _form file in this case is rendered on the site index, so in this case the model is being loaded in the Site controller and is handled there. I can confirm that the same issue is occurring regardless of where I render the _form file, be it in the index or in the Notes section view.
I would expect that the data be returned in $notesmodel->notes_to as an array as mentioned above, which is then easily imploded and saved to db. However the data is not there on form submission, and "Public" is being saved every time. For the sake of testing, I removed the if statement, set the controller to implode the array and ensure that I add tags (so the array is sure to be there), however then I am receiving an error exception "implode(): Argument must be an array".
Snippet of my intended controller code is below. The controller checks to see if any tags have been added to the field. If tags are present, there should be an array which can be imploded and saved. Otherwise if no tags are present, it will revert back to a simple string "Public' and save that instead.
$notesmodel = new Notes();
if ($notesmodel->load(Yii::$app->request->post())) {
$notesmodel->notes_user = Yii::$app->user->identity->username;
$notesmodel->notes_created = date("Y-m-d H:i:s");
if (!empty($notesmodel->notes_to)) {
$notesmodel->notes_to = implode($notesmodel->notes_to);
} else {
$notesmodel->notes_to = 'Public';
}
I have the following form,
public function ContactForm()
{
$fields = FieldList::create(
TextField::create('Nombre', 'Tu nombre')
->setCustomValidationMessage('Por favor coloca tu nombre.')
);
$actions = FieldList::create(
FormAction::create('sendContactForm', 'Send')
);
$required = [
'Nombre',
];
$validator = new RequiredFields($required);
$form = Form::create($this, 'ContactForm', $fields, $actions, $validator);
// I'm using this novalidate for testing
$form->setAttribute('novalidate', 'novalidate');
$form->setFormMethod('POST', true);
return $form;
}
And it's not giving me errors, nor success message on submit.
If I complete the field with a string, the form submits successfully and saves my data to a model, and sends an email as well, but I get no success message.
I have another page type with another form defined the same way and it works fine, I don't know why this one doesn't show me errors.
If I leave the field empty, the sendContactForm function is not called, the page reloads with a clean form and no errors. This makes me think the validation is working correctly because it doesn't reach the submit function, but the fact the form is coming back empty even if I add data to some fields is very strange to me, because the other form comes back with the errors and with the data previously entered.
I've also tried with no JS or CSS to make sure is not a front end interference.
They are both shown in the template using $ContactForm and $MessageForm respectively.
For reference, here are some links to the full files used for both forms/pages.
Contact page
Contact page controller
Working fine form
Working fine form controller
This has been driving me nuts for hours, and I have no idea what could be wrong.
I'm trying to use "Bootstrap File-input" plugin for JQuery in order to upload files using AJAX. The plugin expects error messages being recieved in a JSON key called "error" as following:
{error: 'You are not allowed to upload such a file.'}
So I wrote my own code for exception handling in the "Render" method of "Handler" class:
public function render($request, Exception $exception){
$err_code = $this->getExceptionHTTPStatusCode($exception);
$data = [
"error" => "Internal Server error.",
"exception" => $exception->getMessage()
];
if ($exception instanceof ValidationException){
$data['error'] = "Wrong input data";
$data['error_list'] = $exception->getResponse()-> getOriginalContent();
$err_code = 422;
}
if ($request->expectsJson()) {
return response()->json(
$data,
$err_code
);
}
return parent::render($request, $exception);
}
But instead of recieving the data as expected, it puts array's content in the "responseText" key value (and also it's escaped as a string):
{"readyState":4,"responseText":"{\"error\":\"Wrong input data\",\"exception\":\"The given data failed to pass validation.\",\"error_list\":{\"logotipo\":[\"Logotipo field is mandatory\"]}}","responseJSON":{"error":"Wrong input data","exception":"The given data failed to pass validation.","error_list":{"logotipo":["Logotipo field is mandatory."]}},"status":422,"statusText":"Unprocessable Entity"}
I'm wondering if I can put another key and value in the same level as "responseText", just as "JSONResponse" (I don't know how it works, but it appears to be appended by the Laravel's Validator) but as a JSON Object, instead of a String. I know that I can parse the string with JQuery, but "Bootstrap File Input" plugin expects it as a JSON and I can't modify its code.
I also tried to use Vue.js resources plugin, but it appears that it reads the response in a different way, so that my "responseText" object is called "body" and "bodyText", which have the same content. I don't know why I'm getting duplicated responses, one as a escaped string and one as a JSON.
Thank you.
If I am not wrong you are trying to submit your form with file input using ajax. For this, I can share these following links for you and these guys have already solved the same problem.
Laravel 5 Ajax File/Image Upload
AJAX file upload in laravel
Laravel 5 Ajax File/Image Upload
May be this can provide you some help.
I have a drupal form for save details, I wrote validation for each element in the form. Following method is using for display errors. Then it automatically highlighted the required fields.
form_set_error('field_athletes_male', 'Athletes Male field is required.');
My problem is there is nested element names like as follows
field_coaching_programme[und][0][field_organisation_delivered_by][und][0][value]
Validation message is shown successfully but element is not highlighted
The answer you are looking for may already be in the documentation.
Here is the relevant part:
$name: The name of the form element. If the #parents property of your
form element is array('foo', 'bar', 'baz') then you may set an error
on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error
for every element where the #parents array starts with 'foo'.
Therefore you should try to do the following:
form_set_error("field_coaching_programme][field_organisation_delivered_by", t("Error Message"))
Tried following code and working as expected
form_set_error('field_coaching_programme][und][0][field_organisation_delivered_by', 'Organisation delivered by field is required.');