I have 3 models using validation messages. 2 of them work perfectly for all messages, including _external messages. The third never returns the custom _external message. The folder structure and way in which I get the errors are identical for each model.
Folder Structure
messages\models\verify
Catching the Errors
catch (ORM_Validation_Exception $e)
{
return $e->errors('models/verify');
}
Errors Passed to View
array(1) { ["_external"]=> array(1) { ["activation_hash"]=> string(33) "activation hash must not be empty" } }
Output External Error
<?= Arr::path($errors, '_external.activation_hash'); ?>
messages\models\verify_external.php
return array(
'activation_hash' => array(
'not_empty' => 'The email fields did not match'
),
);
Validation
$extra_rules = Validation::factory($values)
->rule('activation_hash', 'not_empty');
$email->check($extra_rules);
There that should be everything. Again, everything is exactly the same amongst 3 models so I assume its a typo or a bug. Either way I pasted everything here from the code, do you see something I missed? In a debug attempt I put the _external.php file in every directory along the path to the verify folder but got no where so I dont think its my folder structure.
My solution was to include the validation messages in an existing message file. The purpose of the verify action in my example above was to verify a users email address. I added the external verify messages to the external email array and it worked as intended.
Related
I'm trying to set a custom error message for a particular field on some particular rule as per codeigniter's doc, and I'm running into issues. My code looks like the following
function start(){
$this->form_validation->set_message('rule1', 'Rule 1 Error Message');
$this->form_validation->set_rules('amount', lang('users amount'), 'required|trim|numeric|greater_than[0]', array('rule1' => 'Error Message on rule1 for this field_name'));
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else{
$amount =$this->input->post("amount", TRUE);
}
I've tested the rules for each field and they work fine, the problem starts when I add a custom error message for each form field. Previously, if there was an error I'd redirect and display a generic message for the entire form.
$this->session->set_flashdata('error', "Please provide correct data about the transfer");
With the custom message it doesn't throw the custom message at all when I enter data that doesn't obey the rules, however it does throw an error for a pre-defined rules like min_length or max length.
I've followed the docs to a tee, and I don't seee why this issues is happening. I'm aware that there is a way to throw custom messages using callback functions, but preferably I'd like to use this method.
Please try the following steps:
$this->session->set_flashdata('field_name', "Any custom error message");
redirect('page_URL');//use url to be redirected upon.
OR
$this->form_validation->set_message('is_unique', 'The %s is already taken');
The form_validation changes %s with the label seted for the field.
I hope one of these will helps!
I have adopted a CakePhp 2 project. We get to the project from another project, linking to the CakePhp project with a "token" and a conference ID as a parameter in the URL. Using that token, we authorize the user, and using the conference ID get the information from the database. The session value "auth" is set to true.
We have it running on 2 "platforms" locally on my system using a vagrant machine, and on a production server. Locally the session value dies really quick and at random times. On the production server not as often, but the issues we have where Ajax calls don't seem to do what are expected, we believe are being caused by a similar issue. We have many different projects, all Laravel, with zero issues where the session values clear. This issue is strictly with the CakePhp project.
All the authentication magic happens in the beforeFilter method. The code:
public function beforeFilter() {
$session = new CakeSession();
/**
*
* We will check if the current user is authorized here!
*
*/
// If the visitor is coming for the first time, there should be a parameter in
// the URL that is the auth code to check against the database.
if ( ( isset($_GET['conf']) && is_numeric($_GET['conf']) ) && isset($_GET['token']) ) {
$getConference = ClassRegistry::init('Conference')->find('first', ["conditions" => ["conference_id"=>$_GET['conf'] ]]);
$checkToken = ClassRegistry::init('User')->find('first', ["conditions" => ["remember_token"=>$_GET['token'] ]]);
if ($getConference && $checkToken) {
$checkToken['User']['remember_token'] = $this->generateToken();
if ( ClassRegistry::init('User')->save( $checkToken ) ) {
$session->write('auth', true);
$session->write('conferenceId', $_GET['conf']);
$this->redirect('/');
}
}
else {
$session->write('auth', false);
$session->write('conferenceId', null);
}
}
if (! $session->read('auth') || $session->read('conferenceId') == null ) {
echo "No permission!";
exit;
}
}
At the top of the controller:
App::uses('CakeSession', 'Model/Datasource');
When the URL parameters are present, it traps them, does the work, and redirects to the home route without the parameters.
$this->generateToken();
Creates a new token, and overwrites the old one in the database.
There are 2 main controllers. The controller with this code is the main projects controller. The only time it is really hit is the first time you go to the project, and we hit the index method. From there everything else is AJAX calls to the other controller. There is one link, a "home" type link that will hit that index method.
Sometimes these Ajax calls stop working, and clicking that home link will output "No Permission" instead of the expected html in the container the Ajax call outputs too.
Steps to troubleshoot led me to putting this beforeFilter method on the top of the second controller. Now, randomly I'll get no permission. Sometimes, when I'm on the main project that links to this CakePhp project, I click that link, I get no permission right off the bat.
I found this page: cakephp takes me to login page on multiple request and have tried to set the session details like this:
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => '300' // <- added this element
));
And I have tried:
Configure::write('Session.timeout', '300');
Additionally, I have tried cookieTimeout in both of those cases.
I've also tried
Configure::write('Security.level', 'low');
and included
Configure::write('Session.autoRegenerate', true);
In any order, any of these cause the session to bomb out immediately. I get "No permission on page load, and never get anywhere.
The code for this project is honestly crap. The developer who wrote it had mistakes and errors all over the place. On top of that, we are a Laravel shop. We are just trying to keep the project limping along until sometime in the future when we can nuke it from orbit. So we just need to get this working. Any thoughts on what could be causing this? Any other details I am forgetting to include that would help troubleshoot this issue?
Thanks
Reading & writing session data
You can read values from the session using Set::classicExtract() compatible syntax:
CakeSession::read('Config.language');
$key should be the dot separated path you wish to write $value to:
CakeSession::write('Config.language', 'eng');
When you need to delete data from the session, you can use delete:
CakeSession::delete('Config.language');
You should also see the documentation on Sessions and SessionHelper for how to access Session data in the controller and view.
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.
I have just started zend framework 2. I just want to know how to customize message in form for elements having require ON(true). Right now its showing "Please fill out this field" (If the particular textbox is empty and I click the submit button).
I just want to change this message. Initially I thought this message is coming from library
but I was wrong. Can this possible?
Please provide the method how you are creating your form. Ultimately you should simply overwrite the messages of the Validators. Each validator has the option to overwrite messages. The basic syntax is as follows:
// This assumes to be INSIDE a Validator
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => "Dude, it's empty. It shouldn't be!"
)
)
The example overwrites the NotEmpty validator message if no input is given. Furthermore you should know, that if you use the HTML5 Attribute required then some browsers will add a pre-submit-validation to your form and the error-message displayed by the browser cannot be changed.
$username = $this->createElement('text', 'username');
$username->addErrorMessage('The username is required!');
How to log our own error messages(for ex: error due to invalid user date entry) which is generated in php program to drupal error log.
You can use the watchdog function :
watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL)
Quoting the manual, the parameters are :
$type The category to which this message belongs.
$message The message to store in the log.
$variables Array of variables to replace in the message on display or NULL if message is already translated or not possible to translate.
$severity The severity of the message, as per RFC 3164
$link A link to associate with the message.
And the error levels can be found on the page of watchdog_severity_levels. For an error, you'll most probably use WATCHDOG_ERROR, or maybe even something more "critical", depending on the kind of error.
Drupal 8+
// Logs a notice
\Drupal::logger('my_module')->notice($message);
// Logs an error
\Drupal::logger('my_module')->error($message);
See more examples at How to Log Messages in Drupal 8.
1) Indeed, watchdog is a standard way to record own PHP errors.
2) Alternatively, if you need to immediately see error messages while debugging your Drupal pages, you may want to see them logged/printed right at the related page - in FireBug console.
Sometimes is this very convenient when you can see page-related just-in-time logs.
This requires - Devel module, Firebug extension to FireFox and possibly Firephp.
You can use the dfb() function to write log messages directly to the general Firebug console.
dfb($input, $label = NULL)
If you want to keep your Drupal-related log messages out of the normal Firebug console, you can write messages to the Drupal for Firebug log with the firep() function:
firep($item, $optional_title)
Watchdog is the way to go for a production system no doubt but during debugging I find the drupal_set_message function useful.
It outputs the message to the screen where the 'Operation Successful'-type messages are normally displayed (so make sure you remove them before making the site Live).
http://api.drupal.org/api/function/drupal_set_message/6
In drupal 7 we can log message by following method:
drupal watchdog function we can use to log message in database , make sure we have enabled optional core module for Database Logging at /admin/build/modules.
watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL)
$type:
The category to which this message belongs , Example: PHP,cron.., we can filter message by type.
$message :
The message to store in the log,Example: 'The following module is missing from the file system: security_review'
$variables :
Array of variables to replace in the message on display or NULL if message is already translated or not possible to translate.
to make message translated , do not pass dynamic value pass variables in the message should be added by using placeholder strings.
Example:
watchdog('cg_volunteer', 'cg in form_alter %formly', array('%formly' => $form['#id']), WATCHDOG_NOTICE, $link = NULL);
$severity
The severity of the message,logs can be filter by severity as per RFC 3164. Possible values are WATCHDOG_ERROR, WATCHDOG_WARNING, etc.
For more example see https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/watchdog/7.x
$link:
A link to associate with the message.
Example
// for logs notices
watchdog('my_module', $message, array());
// for Loging Error
watchdog('my_module', $message, array(), WATCHDOG_ERROR);
In drupal 8 we used following method:
// For Logs a notice.
\Drupal::logger('my_module')->notice($message);
// For Logs an error.
\Drupal::logger('my_module')->error($message);
// For Alert, action must be taken immediately.
\Drupal::logger('my_module')->alert($message);
// For Critical message.
\Drupal::logger('my_module')->critical($message);
// For Debug-level messages.
\Drupal::logger('my_module')->debug($message);
//For Emergency, system is unusable.
\Drupal::logger('my_module')->emergency($message);
//For Warning
\Drupal::logger('my_module')->warning($message);
//For Informational messages.
\Drupal::logger('my_module')->info($message);
Also for translate we should not use t() function.
\Drupal::logger('my_module')->alert('Message from #module: #message.', [
'#module' => $module,
'#message' => $message,
]);
this will be translated on run time.
Example :
\Drupal::logger('content_entity_example')->notice('#type: deleted %title.',
array(
'#type' => $this->entity->bundle(),
'%title' => $this->entity->label(),
));
Both watchdog for D7 & \Drupal::logger for D8 will write log in watchdog table (in your database), and with HUGE data logged, you can imagine performance impact.
You can use error_log php function to do it (see PHP manual).
error_log("Your message", 3, "/path/to/your/log/file.log");
You need to have permission to write in your log file (/path/to/your/log/file.log)
drupal-8drupalphplog
// Get logger factory.
$logger = \Drupal::service('logger.factory');
// Log a message with dynamic variables.
$nodeType = 'Article';
$userName = 'Admin';
$logger->get($moduleName)->notice('A new "#nodeType" created by %userName.', [
'#nodeType' => $nodeType,
'%userName' => $userName,
]);
Source