Cakephp 2.x set custom validation message in Controller without Model - php

Code in View
<?= $this->Form->input('ProductGroupImage.image', array("class" => "", "type" => "file")); ?>
Here ProductGroupImage is just alias not a actual model.
In Controller
$this->validationErrors['ProductGroupImage']['image'] = "File not Valid"
Above Code does not show Error message in view.

i assume that you are triggering the validation on model and then you updating your validationErrors array.
if (!$this->ProductGroupImage->validates()) {
$errors = $this->ProductGroupImage->validationErrors;
}
You can then update the errors variable and the reassign it to the validationErrors.
if (isset($this->ProductGroupImage->validationErrors['execused_referral_by'])) {
$errors['execused_referral_by'] = "Please Select Excused By";
}
$this->Tardy->validationErrors = $errors;

Related

How to set validation message for field having ajax validation in scenarios? - Yii2

I'm using one model file for 2 forms. One for SIGNUP & Other for Adding members.
I didn't set any scenario for SIGNUP form. But, scenario for Adding members form is set.
Model
public function rules() {
return [
//Add Members
['first_name', 'required','message'=>'Please enter first name.','on'=>'addteammembersidebar'],
['email', 'required','message'=>'Please enter email address.','on'=>'addteammembersidebar'],
['mobile','required','message'=>'Please enter mobile number.','on'=>'addteammembersidebar'],
//Common
['first_name', 'required','message'=>'Please enter your first name.'],
['email', 'required','message'=>'Please enter your email address.'],
['mobile','required','message'=>'Please enter your mobile number.'],
];
}
View
Here, I set scenario like $modelTeamMembers->scenario = 'addteammembersidebar';.
<?php foreach ($modelsTeamMembers as $indexMember => $modelTeamMembers):
$modelTeamMembers->scenario = 'addteammembersidebar';
?>
<tr class="house-item">
<td class="vcenter">
<?php
// necessary for update action.
if (! $modelTeamMembers->isNewRecord) {
echo Html::activeHiddenInput($modelTeamMembers, "[{$indexMember}]id");
}
?>
<?php
$modelTeamMembers->first_name = $first_name;
echo $form->field($modelTeamMembers, "[{$indexMember}]first_name")->label(false);
?>
</td>
<td>
<?php
$modelTeamMembers->last_name = $last_name;
echo $form->field($modelTeamMembers, "[{$indexMember}]last_name")->label(false);
?>
</td>
<td>
<?php
$modelTeamMembers->email = $email;
echo $form->field($modelTeamMembers, "[{$indexMember}]email",['enableAjaxValidation' => true])->label(false);
?>
</td>
<td>
<?php
$modelTeamMembers->mobile = $mobile_number;
echo $form->field($modelTeamMembers, "[{$indexMember}]mobile",
['inputOptions' => ['class' => 'form-control', 'maxlength'=>"10"]])->label(false);
?>
</td>
</tr>
<?php endforeach; ?>
All validation error message working except for email field. If, I remove 'enableAjaxValidation' => true from field, it works. But, for me 'enableAjaxValidation' => true is required.
Image
As in image, it is clearly visible that error message coming "Please enter your email address." Which should be "Please enter email address.". Only email field validation error message not coming correct. Except all are fine.
How to set validation message for email field for scenarios? Any help/hint/suggestions are appreciable.
May I know why exactly do you need to use email validation with AjaxValidation in here? For this type it is enough to write without it since AjaxValidation is more suitable when you want to search and retrieve data from database or other models, not model itself.
However, if you feel you need AjaxValidation, you must set up a few different things since you're current code won't work.
Setting up AjaxValidation in View:
// Set to: index.php?r=profile/email-validation
$form = ActiveForm::begin(['validationUrl' => ['profile/email-validation']]);
// This is set correctly (no changes are needed comparing to your attempt)
echo $form->field($modelTeamMembers, "[{$indexMember}]email", ['enableAjaxValidation' => true])->label(false);
Why this needed? You have set AjaxValidation to be active, but you haven't set URL that this Ajax will work on. It is set in ActiveForm::begin() in most cases.
Setting up AjaxValidation in Controller (required):
// Method that renders your view file
public function actionSomethingThatRendersView()
{
// Code here
$user->scenario = 'addteammembersidebar'; // Custom scenario name
return $this->render(/* the remaining code goes here */);
}
// This is the method that Ajax will send request to ($_POST[])
public function actionEmailValidation()
{
$post = Yii::$app->request->post();
if (!empty($post))
{
Yii::$app->response->format = Response::FORMAT_JSON; // Must be in JSON format
$profile = new User(); // Edit your class name in here
// Custom scenario (must be the same as above otherwise you might get unexpected response)
$profile->scenario = 'addteammembersidebar';
$profile->load($post);
return ActiveForm::validate($profile);
}
}
Why this needed? Ajax will send a request but request without any actions will do nothing. This will "create new" object with same rules and attributes and will attempt to validate with new set of data. For rendering method, $obj->scenario must also be set because otherwise it would use default scenario.
There are no changes to Model. Everything should remain the same as in your example.
In case you want to make it unique email, you have to make changes to Model as well:
public function rules()
{
// ...
['email', 'unique', 'message' => 'Email must be unique'],
// If your attribute is not in the same table as defined in class, then:
['email', 'unique', 'message' => 'Email must be unique', 'targetClass' => User2::className()],
}

CakePHP 2.x: How to manually set validationErrors without a model?

After reading cakePHP: how set error validation to input field manually in controller, I was wondering how to show a validationError from a controller if we use a form without a model?
So for example, we have a view checkSomething.ctp, with a Form that we can submit.
echo $this->Form->create(false); // If we put "SomeModel" here, it would work.
echo $this->Form->input("myField");
And say we are on /Home/CheckSomething/.
class HomeController extends AppController{
public function CheckSomething(){
// So manually validate a field
if(strlen($this->request->data["myField"]) < 5){
// myField is not valid, so we need to show an error near that field
$this->SomeModel->invalidateField("myField", "You must enter at least 5 characters");
// How to do this?
}
}
}
We cannot use a model here... How to set a validationError for a field without a model? How to manually invalidate a field that comes from such a form?
The easiest way would be to send the error to the view directly:
$errors = [];
if (strlen($this->request->data["myField"]) < 5) {
$errors['myField'] = 'You must enter at least 5 characters';
}
$this->set('errors', $errors);
And in your view:
echo $this->Form->create(false);
echo $this->Form->input('myField', [
'error' => isset($errors['myField']) ? $errors['myField'] : false
]);

Drupal Form API : How to pass additional data back to the form after it is been submitted

I have created a form in Drupal using its API. The theme is overridden by a template. In the template, I want to show errors where the form exists, I do not want to show the error using drupal's form_set_error() because it shows the error in a fixed default area of the page.
This is my implementation of hook_form()
function newsletter_box($form, &$form_state)
{
$form = array();
$form["newsletter-email"] = array(
"#type" => "textfield",
"#maxlength" => 32,
"#title" => "Your Email"
);
$form['send-email'] = array(
"#type" => "submit",
"#value" => t("Join Our Newsletter!")
);
return $form;
}
And this is my implementation of hook_submit()
function newsletter_box_submit($form, &$form_state)
{
if( !filter_var($form_state['values']["newsletter-email"], FILTER_VALIDATE_EMAIL) )
{
$form_state['build_info']['args'] = ['form-error' => t("Email not formatted correctly.") ];
// NOTE: here is the place where the error is set, rather I use to set a new variable, but this variable is not available in my template. Why?
}
$form_state['rebuild'] = TRUE;
drupal_form_submit("newsletter_box", $form_state);
}
Suggest adding the variable by implementing a hook_preprocess, and add the error message into form rather than form_state.
Example:
// Set in newsletter_box_submit or newsletter_box_validate
$form['#form_error'] = t("Email not formatted correctly.");
/**
* Implements hook_preprocess_HOOK().
*/
function [module_name]_preprocess_newsletter_box(&$vars) {
$form = $vars['form'];
$error_message = $form['#form_error'];
// Use $error_message in template.
}
It feels like a hack though, strongly recommend theming the form the Drupal way.

No query results for model [modelName], laravel redirect error

I'm having a problem where any input errors in my edit form is returning "No query results for model [modelName]" instead of generating validator messages like it should. Here are my codes:
PetController.php
public function update($id)
{
//omited the validator messages cause it's too long, but it works cause I have an add function that uses the same thing.
try {
$pet = Pet::findOrFail(Input::get('id'));
}
catch(exception $e) {
return Redirect::to('/pet')->with('flash_message', 'Error Editing Pet.');
}
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$breed = filter_var($_POST["breed"], FILTER_SANITIZE_STRING);
$birthday = filter_var($_POST["birthday"], FILTER_SANITIZE_STRING);
$pet->name = $name;
$pet->breed = $breed;
$pet->birthday = Pet::saveDateFmt($birthday);
$pet->save();
return Redirect::to('/pet')->with('flash_message','Your changes have been saved.');
}
So any input error with name, breed, or date will redirect me to /pet with the errors messages from this function:
public function edit($id){
try {
$pet = Pet::findOrFail($id);
}
catch(exception $e) {
return Redirect::to('/pet')
->with('flash_message', $e->getMessage());
//this is where I get the error msg
}
return View::make('edit_pet', ['vet_list' => Vet::lists('name','id')])->with('pet', $pet);
}
I mean, I'm glad it's catching input errors but I don't want to redirect users back to the index page every time. I need to understand why is it redirecting this way to understand how to fix it.
So Update redirects you to Edit? If that is correct then you aren't passing in an id when you redirect causing it to try and find an id of null, try catching if id is null in your edit function.
Ok I just fixed it myself, so apparently I got the form wrong, I changed it to:
{{ Form::open(array('action' => array('PetController#update', $pet->id), 'method' => 'put')) }}

Yii - updating a model and using the model to echo data in the view

I have the following code for updating a Yii model:
public function actionSettings($id) {
if (!isset($_POST['save_hostname']) && isset($_POST['Camera']) && isset($_POST['Camera']['hostname'])) {
$_POST['Camera']['hostname'] = '';
}
$model = $this->loadModel($id);
$model->setScenario('frontend');
$this->performAjaxValidation($model);
if (isset($_POST['Camera'])) {
$model->attributes = $_POST['Camera'];
unset($model->api_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Camera settings has been saved!");
} else {
Yii::app()->user->setFlash('error', "Unable to save camera settings!");
}
}
$this->render('settings', array(
'model' => $model,
));
}
This works fine, except in my model I have code like this:
<h1>Settings For: <?php echo CHtml::encode($model->name); ?></h1>
The problem is that, even when the user input fails validation, the h1 tag is having bad input echoed out into it. If the input fails the validation, the h1 attribute should stay the same.
I can 'reset' the $model variable to what is in the database before the view is returned, but this then means I don't get any error feedback / validation failed messages.
Is my only option to have 2 $models ($model and $data perhaps), one used for handling the form and the other for sending data to the page? Or does someone have a more elegant solution?
performAjaxValidation assigns all save attributes to the model so this behavior is normal.
I would reload model if save fails.
$model->refresh();

Categories