I'm trying to pass a temporary data from my form to my model. My form has a hidden data in it, but it does not get any values from my model.
My form is
<?php echo $form->hiddenField($model, 'fieldName'); ?>
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
I threw in the data for my hidden field using JQuery, and then I proceeed to validate my form.
public function rules()
{
return array(
array('name, email, subject, phone, body', 'required','message' => '{attribute} Required'),
array('resume', 'file', 'types'=>'txt,pdf,doc,docx', 'maxSize'=>2097152, 'tooLarge'=>'File has to be smaller than 2MB','allowEmpty'=>false),
array('email', 'email'),
);
}
Whenever the validation hits an exception, it returns all of the $_POST data I inputted except the data I sent from the hidden form.
How do I get the $_POST so it gets back to the hidden form?
First:
The attribute must be declared as public in the model.
public $fieldName;
Add in rules() of Model the field with a safe mode array('fieldName','safe') :
public function rules()
{
return array(
array('name, email, subject, phone, body', 'required','message' => '{attribute} Required'),
array('resume', 'file', 'types'=>'txt,pdf,doc,docx', 'maxSize'=>2097152, 'tooLarge'=>'File has to be smaller than 2MB','allowEmpty'=>false),
array('email', 'email'),
array('fieldName','safe'), // Add the custom field to 'safe' mode.
);
}
Is 'fieldName' part of the model/table? If not and it is just a custom property declared in the model, then try setting it as 'safe'
Related
Here i have two inputs field as name and age.
I wanna validate name but not age.
How can i send both value to store.
request()->validate([
'name' => 'required',
]);
//Here i wanna add 'age' along with 'name' in $request
//Then i must store.
Pastor::create($request->all());
The $request->all() already sends whatever is in your request. But if you like you can specifically pass request values to create method like this:
Pastor::create([
'name'=> $request->name,
'age' => $request->age
//any other fields
]);
I assume you have named your inputs like i have passed into create method and it should work.
use the Validator class Laravel has. lets say you have UserController
Use Validator;
Use App\User;
class UserController extends Controller
{
// Your Validator
protected function yourValidatorName(array $data)
{
$rules = ['name'=>'required'];
return Validator::make($data,$rules);;
}
// Your Main Function
public function yourFunctionName(Request $request)
{
$isValid = $this->yourValidatorName($request->all());
if(!isValid->fails())
{
// your code here (validation passed)
}
else
{
// your code here (validation failed)
}
}
}
You simply put a check on name field only
$this->validate($request,[
'name' => 'required|min:3|max:200',
],[
'name.required' => 'name is a required field.', // custom messages you can omit them
'name.min' => ' Name must be at least 3 characters.', // custom message for minimum characters
'name.max' => ' Name should not be greater than 200 characters.', // custom message for maximum characters
]);
Pastor::create($request->all());
Without custom messages
$this->validate($request,[
'name' => 'required|min:3|max:200',
]);
Pastor::create($request->all());
I have a field set as required in the model, yet I have seen users saving it as an empty string (ie. ''). When I tested it, I do receive the "Cannot be blank" message properly, so don't know how to prevent this in the future. Do I have to specify all scenarios in the rule (eg, 'insert', 'update')? By the way, I tried updating the field, and it doesn't let me save it empty (I even tries spaces).
These are the rules applied on the field (model):
public function rules()
{
return array(
array('field', 'required'),
array('field', 'length', 'max'=>4096),
array('field', 'safe', 'on'=>'search'),
);
}
For #RiggsFolly :) the controller action:
public function actionUpdate($id)
{
$model = Model::model()->findByPk($id);
$formData = Yii::app()->request->getPost('Model');
if ($formData)
{
$model->attributes = $formData;
$model->save();
}
$this->render('update',array(
'model'=>$model
));
}
... and the view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'form'
)); ?>
<?php echo $form->textArea($model,'text',array( 'rows'=>5 ')); ?>
<?php $this->endWidget(); ?>
Can you imagine any scenario this field could be saving an empty string in the database?
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()],
}
I have an email field in my model registration form and other fields like name, country, age.
and I have to do an ajax validation onChange event only for email field .
I was set my view to enable ajax validation.
my problem is the ajax validation applied for all field not only for email, I need to do this action only for one field onChange event.
this my view
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'Login-Form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
echo $form->errorSummary($loginForm);
echo $form->textFieldRow($loginForm, 'email');
echo $form->textFieldRow($loginForm, 'name');
echo $form->textFieldRow($loginForm, 'age');
echo $form->textFieldRow($loginForm, 'country');
and this is my model
public function rules()
{
return array(
array('email, country, name', 'required'),
array('email', 'checkEmail')
);
}
// custom function to check email
public function checkEmail($attribute, $params)
{
$this->addError($attribute,strtr('email exsit before',$params));
}
how can enable ajax validation only for email and the other filed (country, name, age) on client side without ajax validation.
Please help I send a lot of time to do that.
Thanks
Set the form clientOption on change like this:
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'Login-Form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
So that on change it can trigger the validation
This can be done by setting the 4th parameter to false on validate trigger.
<?php echo $form->error($model,'email', array(), false); ?>
In your model set this
public function rules()
{
return array(
array('email, country, name', 'required'),
array('email', 'unique'), //check if email already exist
array('email', 'email'),
);
}
in your controller
<?php
class SiteController extends CController {
.... // Other functions
public function actionLogin(){ // Your corresponding action
$model= new LoginForm(); // Your actual model name
$_POST['ajax'] === 'Login-form' make sure that login form is the same as your form name in view
if (isset($_POST['ajax']) && $_POST['ajax'] === 'Login-form') {
echo CActiveForm::validate($model,);
Yii::app()->end();
}
... // Remaining action logic
in your view
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'Login-Form',
'enableClientValidation'=>false,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>false,
'validateOnChange'=>false,
'validateOnType' => true,
To perform validation via ajax you first need to call a helper function in your controller in addition to you enabling the enableAjaxValidation in your form view
In your Controller ( I am assuming the SiteController since this a login form )
<?php
class SiteController extends CController {
.... // Other functions
public function actionLogin(){ // Your corresponding action
$model= new LoginForm(); // Your actual model name
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
echo CActiveForm::validate($model,array('email'));
Yii::app()->end();
}
... // Remaining action logic
see Validate and enableAjaxValidation api docs for full details how this works
Im try working with Yii framework. I have 5 inputs like this
<div class="field">
<?php echo $form->label($model, 'name') ?>
<?php echo $form->textField($model, 'name'); ?>
<?php echo $form->error($model, 'name', array('class' => 'label label-important')); ?>
</div>
And this is my rules in model
public function rules() {
return array(
array('email, message', 'required', 'message' => 'Заполните поле'),
array('email', 'email', 'message' => 'Некорректный емаил')
);
}
If user does not pass validate, all values of inputs delete except email and message. Because i have 'method' required. How me save all values of form without required?
If you want to have input saved without any rules, you should define it as safe attribute, here is very good article about that: http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/