I want to optimize the code to make it more efficient and scalable.
So I want to merge this part into one:
if($request->input('logintype') == 'register'){
$validator = Validator::make($request->all(), [
'option.*' => 'required|integer',
'quantity.*' => 'required|integer',
'conditions' => 'required',
'comission' => 'required',
],[
'option.integer' => 'Debe introducir una opción válida',
'quantity.required' => 'Introduzca una cantidad a comprar',
'quantity.integer' => 'Debe introducir una cantidad válida',
'quantity.*.max' => 'Se ha superado el límite máximo de tickets por persona',
'conditions.required' => 'Debe aceptar los Términos y Condiciones',
'comission.required' => 'Debe seleccionar el método de pago',
]);
}
else{
$validator = Validator::make($request->all(), [
'option.*' => 'integer',
'quantity.*' => 'required|integer',
'comission' => 'required',
],[
'option.integer' => 'Debe introducir una opción válida',
'quantity.required' => 'Introduzca una cantidad a comprar',
'quantity.integer' => 'Debe introducir una cantidad válida',
'quantity.*.max' => 'Se ha superado el límite máximo de tickets por persona',
'comission.required' => 'Debe seleccionar el método de pago',
]);
}
I've check that this is possible with this code:
$validator->sometimes('conditions', 'required', function($request){
return $request->input('logintype') == 'register';
});
But I'm unsure how to deal with the custom error messages.
You can achieve this by adding the extra comment to the validator.
Just do like this
$validator = Validator::make($request->all(), [
'option.*' => 'required|integer',
'quantity.*' => 'required|integer',
'comission' => 'required',
],[
'option.integer' => 'Debe introducir una opción válida',
'quantity.required' => 'Introduzca una cantidad a comprar',
'quantity.integer' => 'Debe introducir una cantidad válida',
'quantity.*.max' => 'Se ha superado el límite máximo de tickets por persona',
'conditions.required' => 'Debe aceptar los Términos y Condiciones',
'comission.required' => 'Debe seleccionar el método de pago',
]);
$validator->sometimes('conditions', 'required', function($request){
return $request->input('logintype') == 'register';
});
It will validated your input fields and give your define error message check this
And you can also add multiple field by array
$validator->sometimes(['conditions','option'], 'required', function($request){
return $request->input('logintype') == 'register';
});
Check this https://laravel.com/docs/5.5/validation#conditionally-adding-rules
You may use required_if to conditionally add the required rule.
In this scenario required_if rule is added to the fields option and conditions.
FormRequest is used for separating validation logic from controller.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class YourRequestClassName extends FormRequest
{
public function authorize()
{
return true;
}
public function messages()
{
return [
'option.integer' => 'Debe introducir una opción válida',
'quantity.required' => 'Introduzca una cantidad a comprar',
'quantity.integer' => 'Debe introducir una cantidad válida',
'quantity.*.max' => 'Se ha superado el límite máximo de tickets por persona',
'conditions.required_if' => 'Debe aceptar los Términos y Condiciones',
'comission.required' => 'Debe seleccionar el método de pago',
];
}
public function rules()
{
return [
'option.*' => [
'required_if:logintype,register',
'nullable',
'integer',
],
'quantity.*' => [
'required',
'nullable',
'integer',
],
'conditions' => [
'required_if:logintype,register',
'nullable',
],
'comission' => [
'required',
],
];
}
}
In your controller, you can inject the App\Http\Requests\YourRequestClassName to the method.
use App\Http\Requests\YourRequestClassName;
public function registerAction(YourRequestClassName $request)
{
//rest of the controller code
As Kyslik said, adding this logic to a Request would make things a little neater in your controller.
I tend to go with the following style of a Request containing the validation rules and custom validation messages. In your case it could look something like this:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Validator;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
if ($this->input('logintype') == 'register') {
return [
'option.*' => 'required|integer',
'quantity.*' => 'required|integer',
'conditions' => 'required',
'comission' => 'required',
];
}
return [
'option.*' => 'integer',
'quantity.*' => 'required|integer',
'comission' => 'required',
];
}
public function messages()
{
if ($this->input('logintype') == 'register') {
return [
'option.integer' => 'Debe introducir una opción válida',
'quantity.required' => 'Introduzca una cantidad a comprar',
'quantity.integer' => 'Debe introducir una cantidad válida',
'quantity.*.max' => 'Se ha superado el límite máximo de tickets por persona',
'conditions.required' => 'Debe aceptar los Términos y Condiciones',
'comission.required' => 'Debe seleccionar el método de pago',
];
}
return [
'option.integer' => 'Debe introducir una opción válida',
'quantity.required' => 'Introduzca una cantidad a comprar',
'quantity.integer' => 'Debe introducir una cantidad válida',
'quantity.*.max' => 'Se ha superado el límite máximo de tickets por persona',
'comission.required' => 'Debe seleccionar el método de pago',
];
}
public function validate()
{
return Validator::make(parent::all(), $this->rules(), $this->messages());
}
}
And in the controller use like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Requests\LoginRequest;
class LoginController extends Controller
{
public function search(LoginRequest $request)
{
$status_code = 200;
$response = [];
try {
$validator = $request->validate();
if ($validator->fails()) {
// throw new ValidationException or something similar
}
} catch (Exception $e) {
// Deal with it
} finally {
return response()->json($response, $status_code);
}
}
}
As you can see it makes the controller tidier.
In your LoginRequest you can customise it heavily, change rules depending on some of the inputs or the HTTP method used, e.g. different between POST and GET, etc.
Hope this helps.
Related
I am implementing a registration section for a site, using CodeIgniter 4.0.4.
I implemented the following rules in my Validation configuration file.
public $registro = [
'registro.nombre' => [
'rules' => 'required',
'errors' => [
'required' => 'El nombre es un campo obligatorio.'
]
],
'registro.apellido' => [
'rules' => 'required',
'errors' => [
'required' => 'El apellido es un campo obligatorio.'
]
],
'registro.email' => [
'rules' => 'required|valid_email',
'errors' => [
'required' => 'El correo electrónico es un campo obligatorio.',
'valid_email' => 'Por favor, revisa el formato de tu correo electrónico, no parece ser válido.'
]
],
'registro.password' => [
'rules' => 'required|min_length[6]',
'errors' => [
'required' => 'La contraseña es un campo obligatorio.',
'min_length' => 'La contraseña debe ser de al menos 6 caracteres.'
]
],
'registro.verificar_password' => [
'rules' => 'required|matches[registro.password]|min_length[6]',
'errors' => [
'required' => 'Verificar contraseña es un campo obligatorio.',
'matches[registro.password]' => 'Las contraseñas no coinciden, por favor revisa.',
'min_length' => 'Verificar contraseña es un campo que debe ser de al menos 6 caracteres.'
]
]
];
Everything works fine, except the matches[registro.password] option. The problem is that I am not sure how to add it in the errors message. Inside the documentation there isn't a specific example for this.
My inputs (reduced code) for the passwords are these:
<input type="password" name="registro[password]" minlength="6" id="registro_password" placeholder="Contraseña (mínimo 6 caracteres)" required />
<input type="password" name="registro[verificar_password]" minlength="6" data-equalto="registro_password" id="registro_verificar_password" placeholder="Verificar contraseña" required />
So, basically when I send the info to my controller I get an array with those two indexes. I make sure that the passwords are the same, but I keep getting that error. I tried to change the errors index for matches to these two versions:
// Version 1
'matches[registro.password]' => 'Las contraseñas no coinciden, por favor revisa.'
// Output
// The registro.verificar_password field does not match the registro.password field.
// This is not a message I have defined as you can see above
// Version 2
'matches' => 'Las contraseñas no coinciden, por favor revisa.'
// Output
// Las contraseñas no coinciden, por favor revisa.
// This is the message I have defined above.
For this example I am literally using 123456 as a password.
I tried doing this and here are the results:
var_dump($post['registro']['password'] == $post['registro']['verificar_password']);
// Output
// bool(true)
if(!$validation->run($post, 'registro')) {
echo $validation->listErrors();
}
// Output
// Las contraseñas no coinciden, por favor revisa.
Am I doing something incorrectly, or is this a validation library bug?
Ok, I checked this with the CodeIgniter 4 team, creating an issue report.
This was indeed a bug, which by when people read this would be fixed. Just to clear up my own question, the correct way of using the errors message for the matches index would be:
'registro.verificar_password' => [
'rules' => 'required|matches[registro.password]|min_length[6]',
'errors' => [
'required' => 'Verificar contraseña es un campo obligatorio.',
'matches' => 'Las contraseñas no coinciden, por favor revisa.',
'min_length' => 'Verificar contraseña es un campo que debe ser de al menos 6 caracteres.'
]
]
Basically the index should be only matches in the errors array.
I have this behaviors in SiteController
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
//El administrador tiene permisos sobre las siguientes acciones
'actions' => ['logout'],
//Esta propiedad establece que tiene permisos
'allow' => true,
//Usuarios autenticados, el signo ? es para invitados
'roles' => ['#'],
//Este método nos permite crear un filtro sobre la identidad del usuario
//y así establecer si tiene permisos o no
'matchCallback' => function ($rule, $action) {
//Llamada al método que comprueba si es un administrador
return User::isUserAdmin(Yii::$app->user->identity->rutProfesor);
},
],
[
//Los usuarios simples tienen permisos sobre las siguientes acciones
'actions' => ['logout'],
//Esta propiedad establece que tiene permisos
'allow' => true,
//Usuarios autenticados, el signo ? es para invitados
'roles' => ['#'],
//Este método nos permite crear un filtro sobre la identidad del usuario
//y así establecer si tiene permisos o no
'matchCallback' => function ($rule, $action) {
//Llamada al método que comprueba si es un usuario simple
return User::isUserSimple(Yii::$app->user->identity->rutProfesor);
},
],
],
],
//Controla el modo en que se accede a las acciones, en este ejemplo a la acción logout
//sólo se puede acceder a través del método post
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
But I don't know how to implement that the guests must need to login to access any action, even when they enter the main page. I know I have to put BeforeRequest before the rules, but I think it will affect the actions for the multiple logged users' roles. I need help, please.
Try This code i will work
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
//'only' => ['logout', 'signup','index'],
'rules' => [
[
'actions' => ['signup', 'login'],
'allow' => true,
'roles' => ['?'],///guest user//
],
[
'actions' => ['logout', 'index','test'],
'allow' => true,
'roles' => ['#'],///login user///
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
// 'logout' => ['post'],
],
],
];
}
I have a problem translating the laravel messages. I have created a folder called es inside lang folder and I have translated the messages from English to Spanish. Also I have set 'locale' => 'es' on config/app.php. But English messages continues appearing.
I have used the default views for login provided by laravel, to generate it (and routes) I used the command (as says in https://laravel.com/docs/5.2/authentication)
php artisan make:auth
I have changed the default routes by the following:
Route::get('/login', 'UserController#getLogin');
Route::post('/login', 'UserController#postLogin');
And in UserController I have:
public function getLogin(){
return view('auth.login');
}
public function postLogin(Request $request){
$input = $request->all();
if (Auth::attempt(['email' => $input["email"], 'password' => $input["password"]], true))
{
return redirect()->intended('/tables');
}
}
Here are two screenshots of the messages that appears in English
http://i64.tinypic.com/if4k83.png
http://i64.tinypic.com/51zhnp.png
How can I transate these messages?
Thanks
Edit:
resources/lang/en/validation.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'exists' => 'The selected :attribute is invalid.',
'filled' => 'The :attribute field is required.',
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'json' => 'The :attribute must be a valid JSON string.',
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'numeric' => 'The :attribute must be a number.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values is present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'url' => 'The :attribute format is invalid.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
resources/lang/es/validation.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => ':attribute debe ser aceptado.',
'active_url' => 'El campo :attribute no es una URL válida.',
'after' => 'El campo :attribute debe ser una fecha posterior a :date.',
'alpha' => 'El campo :attribute debe contener solo letras.',
'alpha_dash' => 'El campo :attribute debe contener solo letras números y guiones.',
'alpha_num' => 'El campo :attribute debe contenterdebe contenter letras y números.',
'array' => 'El campo :attribute debe ser un array.',
'before' => 'El campo :attribute debe ser una fecha anterior a :date.',
'between' => [
'numeric' => 'El campo :attribute debe estar entre :min y :max.',
'file' => 'El campo :attribute ebe estar entre :min y :max kilobytes.',
'string' => 'El campo :attribute ebe estar entre :min y :max carácteres.',
'array' => 'El campo :attribute debe tener entre :min y :max elementos.',
],
'boolean' => 'El campo :attribute debe ser verdadero o falso.',
'confirmed' => 'El campo :attribute confirmación no coincide.',
'date' => 'El campo :attribute no es una fecha válida.',
'date_format' => 'El campo :attribute does not match the format :format.',
'different' => 'El campo :attribute y :other deben ser diferentes.',
'digits' => 'El campo :attribute debe ser de :digits dígitos.',
'digits_between' => 'El campo :attribute debe estar entre :min y :max dígitos.',
'distinct' => 'El campo :attribute tiene un valor duplicado.',
'email' => 'El campo :attribute debe ser una dirección de correo válida.',
'exists' => 'El campo :attribute no es válido.',
'filled' => 'El campo :attribute es obligatorio.',
'image' => 'El campo :attribute debe ser una imagen.',
'in' => 'El campo :attribute no es válido',
'in_array' => 'El campo :attribute no existe en :other.',
'integer' => 'El campo :attribute debe ser un entero.',
'ip' => 'El campo :attribute debe ser una dirección IP válida.',
'json' => 'El campo :attribute debe ser una cadena JSON válida.',
'max' => [
'numeric' => 'El campo :attribute no debe ser mayor que :max.',
'file' => 'El campo :attribute no debe ser mayor que :max kilobytes.',
'string' => 'El campo :attribute no debe ser mayor que :max carácteres.',
'array' => 'El campo :attribute no debe contener más de :max elementos.',
],
'mimes' => 'El campo :attribute debe ser un archivo del tipo: :values.',
'min' => [
'numeric' => 'El campo :attribute debe ser de al menos :min.',
'file' => 'El campo :attribute debe ser de al menos :min kilobytes.',
'string' => 'El campo :attribute debe ser de al menos :min carácteres.',
'array' => 'El campo :attribute debe tener al menos :min elementos.',
],
'not_in' => 'El campo selected :attribute no es válido.',
'numeric' => 'El campo :attribute debe ser un número.',
'present' => 'El campo :attribute debe estar presente.',
'regex' => 'El formatp del campo :attribute no es válido.',
'required' => 'El campo :attribute es obligatorio.',
'required_if' => 'El campo :attribute es obligatorio cuando :other es :value.',
'required_unless' => 'El campo :attribute es obligatorio a menos que :other esté en :values.',
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_with_all' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.',
'required_without_all' => 'El campo :attribute es obligatorio cuando ninguno de :values está presente.',
'same' => 'Los campos :attribute y :other deben coincidir.',
'size' => [
'numeric' => 'El campo :attribute debe ser de :size.',
'file' => 'El campo :attribute debe ser de :size kilobytes.',
'string' => 'El campo :attribute debe ser de :size carácteres.',
'array' => 'El campo :attribute debe contenter :size elementos.',
],
'string' => 'El campo :attribute debe ser una cadena de texto.',
'timezone' => 'El campo :attribute debe ser una zona válida.',
'unique' => 'El campo :attribute debe ser único.',
'url' => 'El campo :attribute tiene un formato no válido.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
The begining of my config/app.php
return [
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', true),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'es',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'es',
Define your language in .env (you can always check what language you are running on with app()->getLocale())
Copy resource/lang/validation.php to resources/lang/{YOUR_LANG}/validation.php
Find and edit this array:
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
Example:
'custom' => [
'mensagem' => [
'required' => 'O campo mensagem é obrigatório.',
],
],
I'm having this error:
Fatal error: Call to undefined function CDbExpression() in C:\wamp\www\yii-related\agroplasticos\protected\models\Cliente.php on line 73
Being that file as follows (this is the exploding part in the code):
public function rules()
{
return array(
#la identificación solo podrá elegirse durante la creación y la actualización privilegiada.
array('identificacion', 'required', 'on' => 'insert, updateAdmin'),
array('identificacion', 'numerical', 'integerOnly' => true, 'on' => 'insert, updateAdmin'),
array('identificacion', 'length', 'max'=>15, 'on' => 'insert, updateAdmin'),
#el asesor solo podrá elegirse durante la actualización privilegiada.
#(durante la inserción se tomará el administrador actual como asesor)
array('id_asesor', 'filter', 'filter' => array($this, 'defaultAdministrator'), 'on' => 'insert'),
array('id_asesor', 'required', 'on' => 'updateAdmin'),
array('id_asesor', 'length', 'max'=>10, 'on' => 'updateAdmin'),
#la contraseña será requerida solamente en la inserción.
#no estará presente en la actualización (se usará otro form).
array('clave', 'filter', 'filter' => array($this, 'passwordUpdate'), 'on' => 'insert, passwordUpdate'),
array('clave', 'required', 'on' => 'insert, passwordUpdate'),
#el email será siempre requerido (y en formato de email).
array('email', 'filter', 'filter' => 'strtolower'),
array('email', 'required'),
array('email', 'email'),
array('email', 'length', 'max'=>255),
#el nombre será siempre requerido (restringiendo longitudes).
array('nombre', 'filter', 'filter' => 'strtoupper'),
array('nombre', 'required'),
array('nombre', 'match', 'pattern' => '/^([\p{L}\'\d.-]+\s*)*[\p{L}\'\d.-]+$/u'),
array('nombre', 'length', 'max'=>60, 'min'=>5),
#la ciudad será siempre requerida (solo permitimos null a las entradas ya existentes).
array('id_ciudad', 'required'),
array('id_ciudad', 'numerical', 'integerOnly' => true),
array('id_ciudad', 'length', 'max'=>10),
#la habilitacion será booleana. solamente va poder cambiarse durante actualización privilegiada.
#(durante la inserción se debe poner en 1)
array('habilitado', 'required', 'on' => 'updateAdmin'),
array('habilitado', 'boolean', 'on' => 'updateAdmin'),
array('habilitado', 'default', 'value' => 1, 'on' => 'insert'),
#la fecha va a tener un valor predeterminado durante la inserción
array('registrado_en', 'default', 'value' => CDbExpression('NOW()'), 'on' => 'insert'),
// The following rule is used by search().
array('identificacion, email, nombre, habilitado, registrado_en, id_ciudad, id_asesor', 'safe', 'on'=>'search'),
);
}
Are not those expressions (i.e. native, like CDbExpression) '__autoload'ed?
What must I do to fix it? (yii version: 1.1.14)
They are autoloaded, but only if called correctly.
This is a function call (inside an array definition):
'value' => CDbExpression('NOW()')
This creates an object:
'value' => new CDbExpression('NOW()')
I'm new to this and I have a problem lares from making a long time, I have the following code.
<?php
class RegistroUsuariosForm extends sfForm {
public function configure() {
$this->setWidgets(array(
'password1' => new sfWidgetFormInputPassword(),
'password2' => new sfWidgetFormInputPassword(),
'avatar' => new sfWidgetFormInputFile(),
));
$this->widgetSchema->setLabels(array(
'password1' => 'Password',
'password2' => 'Repetir Contraseña',
'avatar' => 'Imagen a mostrar'
));
$this->widgetSchema->setNameFormat('RegUsuario[%s]');
$this->validatorSchema->setPostValidator(new sfValidatorSchemaCompare('password1', '==', 'password2',
array(),
array('invalid' => 'Las contraseñas no son iguales')));
$this->setValidators(array(
'password1' => new sfValidatorString(array('min_length' => 4),
array('required' => 'Campo obligatorio',
'min_length' => 'Minimo %min_length% caracteres.',)),
'password2' => new sfValidatorString(array('min_length' => 4),
array('required' => 'Campo obligatorio',
'min_length' => 'Minimo %min_length% caracteres.',)),
'avatar' => new sfValidatorFile(
array(
'required' => false,
'max_size' => (1048576 * 2),
'mime_types' => 'web_images',
),
array(
'required' => 'Campo obligatorio',
'max_size' => 'El archivo es muy grande (máximo de 2Mb).',
'mime_types' => 'El tipo de archivo es invalido (%mime_type%).',
'partial' => 'El archivo subido fue sólo parcialmente cargado.',
'no_tmp_dir' => 'Falta la carpeta temporal.',
'cant_write' => 'No se pudo guardar el archivo en el servidor.',
'extension' => 'De carga del archivo se detuvo, por extensión.'
)),
));
}
}
public function executeActivarinvitacion(sfWebRequest $request) {
$key = $request->getParameter('key');
$this->formulario = new RegistroUsuariosForm();
if (($dato = Invitaciones::TraerDatosDeInvitacion($key))) {
$this->key = $key;
if ($request->isMethod('post')) {
$RegUsuario = $request->getParameter('RegUsuario');
$Avatar = $request->getFiles('RegUsuario');
$this->formulario = new RegistroUsuariosForm();
$this->formulario->bind($RegUsuario, $Avatar);
if ($this->formulario->isValid()) {
echo $RegUsuario['password1'];
echo ' - '.$RegUsuario['password2'];
exit();
}
}
} else {
$this->forward404();
}
$this->usuario = $dato['usuario'];
$this->correo = $dato['correo'];
}
The validation of the password just does not work, does anyone know what?
sfForm->setValidators() internally re-creates a new validatorSchema, so your previously set form validator is just cleared. Just put the call to $this->validatorSchema->setPostValidator() below the rest and it should work.