I have a problem in my site created with cakePhp 2.x, when I try to register an account my form check all my rules of my fields and beforeSave crypt the password, but crypt the password before check the password(MatchPassword) with the confirm password and then return me the error tha the two password is't equal because the password is crypt with 40characters.
Here is my Model code, How can I solv this problem?
<?php
//questo modello interessa lòa tabella User
class User extends AppModel{
public $name = 'User'; //non utilizzata nel sito è il nome del modello alla fine per migliorare la compatibilità
public $validate = array(
'password' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
),
'min_lunghezza' => array(
'rule' => array('minLength',5),
'message' => 'La password deve contenere almeno 5 caratteri'
),
'max_lunghezza' => array(
'rule' => array('maxLength',15),
'message' => 'La password deve contenere al massimo 15 caratteri'
),
'password_uguale' => array(
'rule' => 'matchPasswords',
'message' => 'Not equal password'
)
),
'password_confirm' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
)
)
);
public function matchPasswords($data){
if ($data['password']==$this->data['User']['password_confirm']){
return true;
}
$this->invalidate('password_confirm','Le due password non coincidono');
return false;
}
public function beforeSave(){
//crypt
if (isset($this->data['User']['password'])){
$this->data['User']['password']=AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
I had a similar problem -- I'm not sure if it's exactly what you were asking -- but I needed to validate my model, before the beforeSave() rules were applied.
I found CakePHP's Validating Data from the Controller page helpful. Basically, you set the data
$this->ModelName->set($this->request->data);
Then you can check the model's validates() method...
if ($this->ModelName->validates()) { // ...
Then, you can decide whether to save the model or show the user an error using, e.g., $this->Session->setFlash().
Related
In my HunterModel.php file all the validations and custom messages are from the validations, but I don't know if my form_create.php doesn't show the error messages, they simply return to the form without shows the failures committed by the user, why is this happening?
form_create.php
<?php if (isset($validation)) : ?>
<div class="text-danger">
<?= $validation->listErrors() ?>
</div>
<?php endif; ?>
<form action="<?= site_url('create')?>" method="POST">
...
</form>
In my HunterController.php method createHunter() must do the record insertion operation, checking if everything is right or returns to the form showing the necessary corrections to the user.
HunterController.php
public function createHunter()
{
try {
helper(['form']);
$hunter = new HunterModel();
$data = [
'name_hunter' => $this->request->getPost('name_hunter'),
'age_hunter' => $this->request->getPost('age_hunter'),
'height_hunter' => $this->request->getPost('height_hunter'),
'weight_hunter' => $this->request->getPost('weight_hunter'),
'type_hunter' => $this->request->getPost('type_hunter'),
'type_nen' => $this->request->getPost('type_nen'),
'type_blood' => $this->request->getPost('type_blood')
];
if ($hunter->insert($data)){
return $this->response->redirect(site_url('listing'));
} else {
$data['validation'] = $this->validator;
echo view('form_create', $data);
}
} catch (\Exception $e) {
exit($e->getMessage());
}
}
HunterModel.php
// Validation
protected $validationRules = [
'nome_hunter' => 'required|max_length[30]',
'idade_hunter' => 'required|integer',
'altura_hunter' => 'required|decimal',
'peso_hunter' => 'required|decimal',
'tipo_hunter' => 'required|max_length[30]',
'tipo_nen' => 'required|max_length[30]',
'tipo_sanguineo' => 'required|max_length[3]'
];
protected $validationMessages = [
'nome_hunter' => [
'required' => 'O nome do Hunter não pode ficar vazio.',
'max_length' => 'O nome do Hunter precisa ter no máximo 30 caracteres.'
],
'idade_hunter' => [
'required' => 'A idade do Hunter não pode ficar vazia.',
'integer' => 'A idade do Hunter precisa ser um número inteiro.'
],
'peso_hunter' => [
'required' => 'O peso do Hunter não pode ficar vazio.',
'decimal' => 'O peso do Hunter precisa ser um número decimal.'
],
'altura_hunter' => [
'required' => 'A altura do Hunter não pode ficar vazia.',
'decimal' => 'A altura do Hunter precisa ser um número decimal.'
],
'tipo_hunter' => [
'required' => 'É necessário definir o tipo de Hunter.',
'max_length' => 'O tipo de Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_nen' => [
'required' => 'É necessário definir o nen do Hunter.',
'max_length' => 'O nen do Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_sanguineo' => [
'required' => 'É necessário definir o tipo sanguíneo do Hunter.',
'max_length' => 'O tipo sanguíneo do Hunter precisa ter no máximo 3 caracteres.'
]
];
you should learning again about validate data,
learn this page
https://codeigniter4.github.io/userguide/libraries/validation.html#form-validation-tutorial
if you want to use helper function, try this
function yourController($request){
helper(['form']);
$validation = \Config\Services::validation();
$rules = [
"nome_hunter" => [
"label" => "nome_hunter",
"rules" => 'required|max_length[30]',
]
];
if ($this->validate($rules)) {
$hunter = new HunterModel();
$hunter->insert($data)
$session = session();
$session->setFlashData("success", "Successful");
return redirect()->to('/');
} else {
$data["validation"] = $validation->getErrors();
}
}
or you can make the validation on your controller, don't make it on model
you can try this too
how to validate form data in codeigniter 4
I'm using Respect to validate some forms in a project but this project is in Spanish and I don't understand how messages work after spending a long time reading the documentation and even its code.
I'm using Slim and I'm using a NestedValidationException following an example I read on a tutorial on Youtube.
This is the validate method:
public function validate($request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
//In English it's enough with
//$this->errors[$field] = $e->getMessages();
$this->$errors[$field] = $e->getMainMessage();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
I've seen some responses before but some are very hard to grasp for me as I don't intend on doing a whole translation of the library. I'm just attempting to write 5 or 6 custom messages.
EDIT: A method using the messages:
$validation = $this->c->validator->validate($request, [
'username' => v::noWhitespace()->notEmpty()->usernameAvailable(),
'email' => v::noWhitespace()->notEmpty()->email()->emailAvailable(),
'password1' => v::noWhitespace()->notEmpty(),
'password2' => v::noWhitespace()->notEmpty()->identical($inputPassword),
]);
Using findMessages with the parameter you're translating the messages. You just have to replace the content in the catch block:
catch (NestedValidationException $e) {
$errors = $e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
$filteredErrors = array_filter($errors); // Ensure the array is not containing empty values
$this->$errors[$field] = $filteredErrors;
}
I make many projects with Laravel 5.6 with the same login setup (Use Auth facade), but with one shared hosting the users can't log in. When you enter the correctly mail and password, only reload de login page WITHOUT ANY ERRORS, when in my controller all the views return errors or a message.
This is the code of my login (Works in all servers except in this):
public function login(Request $request) {
$rules = array(
'email' => 'required|email|min:3|max:88',
'password' => 'required|min:3|max:88',
);
$messages = [
'required' => 'El :attribute es requerido',
'email' => 'Tiene que ingresar un mail válido',
'min' => 'Longitud del campo :attribute no válido',
'max' => 'Longitud del campo :attribute no válido',
];
$validator = Validator::make($request->all(), $rules, $messages);
if($validator->fails()) {
return redirect()->intended('admin')->withErrors($validator);
} else {
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
return redirect()->intended('admin');
} else {
return redirect()->intended('admin')->withErrors(['loginFail' => 'Usuario/Contraseña incorrectos']);
}
}
}
If I enter a wrong email or password in any server, this return me to the login view with the errors, but in these the errors don't appear and I can't login with the correct email and password.
I call to the hosting and say me that is nothing wrong, how can i solve it?
I'm trying to include the class that treats the Request from my form, but it always returns error from not found, however, I've already checked and reverted and the file and patch are correct.
I already tried to update the composer to see if it solved, but without success, follow the code below.
Arguments "Class App\Http\Requests\CadastroRequest does not exist"
File CadastroController.php
<?
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB; // Banco de dados
use Request; // Tratamento URI
use Validator; // Validação
use App\Cadastro; // Modelo
use App\Http\Requests\CadastroRequest; // Regras do formulário
class CadastroController extends Controller {
// Formulário de Cadastro
public function cadastro(){
return view('cadastro.formulario');
}
// Registrar Usuário
public function salvar( CadastroRequest $request ){
Cadastro::create( $request->all() );
return redirect('/cadastro/obrigado')->withInput();
}
}
?>
File CadastroRequest.php (root/app/Http/Requests/CadastroRequest.php)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CadastroRequest extends FormRequest {
public function authorize() {
return true; // Manter true para teste
}
public function rules() {
return [
# Informações de contato
'nome' => 'required|min:10',
'email' => 'required|min:10',
'celular' => 'min:11|max:15',
# Informações de acesso
'senha' => 'required|numeric|min:3|max:8',
'rsenha' => 'required|numeric|min:3|max:8',
# Informações de endereço
'estado' => 'required|min:10',
'cidade' => 'required|min:10',
'cep' => 'required|min:10',
'endereco' => 'required|min:10',
'numero' => 'required|min:10',
'bairro' => 'required|min:10',
];
}
public function messages(){
return [
'nome.required' => 'Você precisa informar seu nome.'
'email.required' => 'Insira um e-mail valido, você precisa confirmar o registro.'
'senha.required' => 'Senha é obrigatória.'
'rsenha.required' => 'Confirmação da senha é obrigatória.'
'estado.required' => 'Saber seu estado ajuda a lhe informar jogos acontecendo no seu estado.'
'cidade.required' => 'Saber a cidade que mora ajuda a lhe informar os jogos próximos a você.'
'cep.required' => 'Campo CEP é obrigatório.'
'endereco.required' => 'Campo Endereço é obrigatório.'
'numero.required' => 'Campo Número é obrigatório.'
'bairro.required' => 'Campo Bairro é obrigatório.'
];
}
}
Run this in your terminal :
composer dump-autoload
it will add your class to your project
If it not work, try to add the new request via artisan :
php artisan make:request CadastroRequest
then just copy and paste your code
I'm using CakePHP 2.6.7.
A user will be able to add to his profile multiple cars and multiple addresses. He will also be able to link multiple addresses to one car, and link one address to multiple cars.
I then have a User model with :
class User extends AppModel {
public $hasMany = array(
'Car',
'Address'
);
}
A Car model with :
class Car extends AppModel {
public $belongsTo = array(
'User'
);
public $hasAndBelongsToMany = array(
'Address' =>
array(
'unique' => 'keepExisting'
)
);
}
An an Address model :
class Address extends AppModel {
public $hasAndBelongsToMany = array(
'Car' =>
array(
'unique' => 'keepExisting',
),
);
public $belongsTo = array(
'User'
);
}
I have a form so that the user can edit his cars (only one for the moment) :
[...]
<legend>Mes voitures</legend>
<?php
for($nbrvoiture = 0; $nbrvoiture <= 0; $nbrvoiture++)
{
?><h3>Voiture <?php echo $nbrvoiture+1?></h3><?php
$myLabelOptions = array('text' => "Marque");
echo $this->Form->input('Car.'.$nbrvoiture.'.CarMake', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
$myLabelOptions = array('text' => "Modèle");
echo $this->Form->input('Car.'.$nbrvoiture.'.CarModel', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
$myLabelOptions = array('text' => "Plaque d'immatriculation");
echo $this->Form->input('Car.'.$nbrvoiture.'.NumberPlate', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
echo $this->Form->submit("Valider", array(
'class' => 'btn btn-default col-sm-offset-2'
));
}
The thing is that I can't save the data to my database.
Here is part of the User controller code :
function edit() {
// On récupère l'ID de l'utilisateur
$user_id = $this->Auth->user('id');
// Si l'utilisateur n'a pas d'ID => il n'est pas connecté => il ne peut pas éditer son profil
if(!$user_id){
$this->redirect('/');
die();
}
debug($this->User->find('all'));
$this->User->id = $user_id;
$passError = false;
if($this->request->is('put') || $this->request->is('post')){
$d = $this->request->data;
$d['User']['id'] = $user_id;
debug($d);
if($this->request['pass'][0]=='cars')
{
if($this->User->saveAssociated($d, array('deep' => true))){
$this->Session->setFlash(__("Les informations sur la voiture ont bien été modifiées"), 'alert', array (
'plugin' => 'BoostCake',
'class' => 'alert-success'
));
}else{
$this->Session->setFlash(__("Impossible de modifier ou d'ajouter les infos"), 'alert', array (
'plugin' => 'BoostCake',
'class' => 'alert-danger'
));
}
}
When I save the data, it shows the error.
In my database I have these 4 tables :
Users(id, username, mail, password, created, lastlogin, active, firstname, lastname, gender, birthdate, phonenumber)
Cars(id, CarMake, CarModel, NumberPlate, user_id)
Addresses(id, address, city, state, postcode, country, user_id)
Addresses_cars(address_id, car_id)
This is an example of what I can get from the form (the $d variable) :
array(
'Car' => array(
(int) 0 => array(
'CarMake' => 'Allard',
'CarModel' => '2005',
'NumberPlate' => '56QDS1'
)
),
'User' => array(
'id' => '1'
)
)
I don't understand why it doesn't work...
Can you help me please ?
Thank you ! :)
EDIT : I also tried with SaveAll but I can't get it to work.. what's wrong?
It's already been solved by OP, but for future CakePHPers, if you have a save() or saveAll() that isn't saving (checked by your if:else block), the most common problem is a validation error.
CakePHP 2.x Data Validation
CakePHP 3.x Data Validation
If that's not it, try looking at any behaviors you're using, and check for anywhere that should be returning true and isn't (like in it's `beforeSave() method).