Why is my validator is not validating in Laravel? - php

Why is my validator is not validating the input-email field, it accepts anything!
This is my controller to update the database. The name in form is correct
Edit: This is my entire code, I post here my code with just email but one guy said that is working, so why this is not working with my entire code of update database?
public function atualizar(Request $req)
{
$erros = [
'input-nome.max' => 'Introduziu carateres acima do máximo no campo do nome!',
'input-facebook.max' => 'Introduziu carateres acima do máximo no campo do facebook!',
'input-instagram.max' => 'Introduziu carateres acima do máximo no campo do instagram!',
'input-descricao.max' => 'Introduziu carateres acima do máximo no campo da descrição!',
'input-profissao.max' => 'Introduziu carateres acima do máximo no campo da profissão!',
'input-imagem.max' => 'O tamanho máximo do ficheiro é de 10mb!',
'image' => 'O ficheiro que inseriu não é imagem!',
'mimes' => 'A extensão da imagem não é permitida, apenas JPEG, JPG e PNG!',
'email' => 'Introduza um e-mail válido!'
];
$validator = Validator::make($req->all(), [
'input-nome' => 'max:25',
'input-email' => 'nullable|required_with:input-email|email:rfc,dns,filter',
'input-facebook' => 'max:40',
'input-instagram' => 'max:40',
'input-profissao' => 'max:25',
'input-descricao' => 'max:120',
'input-imagem' => 'image|mimes:jpeg,png,jpg|max:10240'
], $erros);
$id = $req->input('input-id');
$membrosEquipa = DB::table('equipa')
->where('id', $id)
->get();
$inputEmail = $req->input('input-email');
if (!isset($inputEmail)) {
$inputEmail = null;
}
if ($req->filled('input-email')) {
$inputEmail = $req->input('input-email');
}
$inputNome = $req->input('input-nome');
$inputFacebook = $req->input('input-facebook');
$inputInstagram = $req->input('input-instagram');
$inputProfissao = $req->input('input-profissao');
$inputDescricao = $req->input('input-descricao');
$inputImagem = $req->file('input-imagem');
foreach ($membrosEquipa as $membro) {
if (!isset($inputNome)) {
$inputNome = $membro->nome;
}
if (!isset($inputFacebook)) {
$inputFacebook = $membro->facebook;
}
if (!isset($inputInstagram)) {
$inputInstagram = $membro->instagram;
}
if (!isset($inputProfissao)) {
$inputProfissao = $membro->profissao;
}
if (!isset($inputDescricao)) {
$inputDescricao = $membro->descricao;
}
if (isset($inputImagem)) {
Storage::delete($membro->imagem);
$inputImagem = $req->file('input-imagem')->store('storage/equipa');
} else {
$inputImagem = $membro->imagem;
}
}
$timestamp = date('Y-m-d H:i:s');
DB::table('equipa')
->where('id', $id)
->update([
'nome' => $inputNome,
'email' => $inputEmail,
'facebook' => $inputFacebook,
'instagram' => $inputInstagram,
'profissao' => $inputProfissao,
'descricao' => $inputDescricao,
'imagem' => $inputImagem,
'updated_at' => $timestamp
]);
return redirect('/editar/equipa/')->with('status', 'Membro da equipa atualizado com sucesso');
}

you must use below code after define $validator
$validator = Validator::make($req->all(), [
'input-email' => 'email:rfc,dns|required'
], $erros);
if ($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}

Related

Form does not return validation messages using CodeIgniter 4

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

Remove imgur from uploading images

A few months ago a friend of mine added in my cms created in laravel the upload of images via imgur, only that I would like to remove it, on the cms however the images are saved (locally) I would like to remove the upload on imgur and I would like to stay the images locally
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$image = Imgur::setHeaders([
'headers' => [
'authorization' => 'Client-ID MY CLIENT ID',
'content-type' => 'application/x-www-form-urlencoded',
]
])->setFormParams([
'form_params' => [
'image' => URL::to("/").'/uploads/profile/'. $name,
]
])->upload(URL::to("/").'/uploads/profile/'. $name);
\File::delete('uploads/profile/' .$name);
$user->image_profile = $image->link();
$user->save();
$html = $image->link();
return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
}
}
My server is running Ubuntu 16.04 + Laravel 5.5
Best Regards
This code will only upload photo to your local directory.
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
// remove this commented portion
// $image = Imgur::setHeaders([
// 'headers' => [
// 'authorization' => 'Client-ID MY CLIENT ID',
// 'content-type' => 'application/x-www-form-urlencoded',
// ]
// ])->setFormParams([
// 'form_params' => [
// 'image' => URL::to("/").'/uploads/profile/'. $name,
// ]
// ])->upload(URL::to("/").'/uploads/profile/'. $name);
// \File::delete('uploads/profile/' .$name);
// $user->image_profile = $image->link();
// $user->save();
// $html = $image->link();
// update this portion to
$user->image_profile = $imagePath;
$user->save();
$html = $imagePath;
// return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
// also update this portion to
return response()->json(['success' => true, 'html' => $html, 'image' => $imagePath]);
}
}

how can I validate property before send my data to database im new on codeigniter

I'm trying to do is make a validation when is not empty my array then it will be display successfully added, but before that I want to implement if stock is greater than min_stock and if max_stock is less greater than stock then do some msg. then if not duplicate .... to check if it's duplicate it works , but it isnt working when I try to implement this
if ($stock > $min_stock) {
$this->json(array('min_stock' => 'el stock no puede ser mayor al min'));
}elseif ($max_stock < $stock) {
$this->json(array('min_stock' => 'el stock no puede ser mayor al max'));
}else{
}
controller
public function addProduct(){
$descripcion = $this->input->post('description');
$cost_price = $this->input->post('cost_price');
$selling_price = $this->input->post('selling_price');
$wprice = $this->input->post('wprice');
$min_stock = $this->input->post('min_stock');
$stock = $this->input->post('stock');
$max_stock = $this->input->post('max_stock');
$data = array(
'descripcion' => $descripcion,
'precio_compra' => $cost_price,
'precio_venta' => $selling_price,
'precio_mayoreo' => $wprice,
'existencia_minima' => $min_stock,
'existencia' => $stock,
'existencia_maxima' => $max_stock
);
//$this->json(array('msg' => 'successfully added'));
//$this->json(array('duplicate' => 'product already exists'));
if (!empty($this->products->addProduct($data))) {
-->> before this $this->json(array('msg' => 'successfully added'));
}else{
$this->json(array('duplicate' => 'product already exists'));
}
// the below code how can I implement into
if ($stock > $min_stock) {
$this->json(array('min_stock' => 'el stock no puede ser mayor al min'));
}elseif ($max_stock < $stock) {
$this->json(array('min_stock' => 'el stock no puede ser mayor al max'));
}else{
}
}
model
public function addProduct($data){
$this->db->select('descripcion');
$this->db->from('storelte_articulos');
$this->db->where('descripcion',$data['descripcion']);
$query = $this->db->get();
return $query->num_rows() == 0 ? $this->db->insert('storelte_articulos',$data) : false;
}
Rewrite your code after $data array in your controller as following:
if ($stock > $min_stock) {
$this->json(array('min_stock' => 'el stock no puede ser mayor al min'));
}elseif ($max_stock < $stock) {
$this->json(array('min_stock' => 'el stock no puede ser mayor al max'));
} else {
if (!$this->products->isExistsProduct($data)) {
$this->products->addProduct($data)
$this->json(array('msg' => 'successfully added'));
}else{
$this->json(array('duplicate' => 'product already exists'));
}
}
Rewrite your Model as following:
public function isExistsProduct($data){
$this->db->select('descripcion');
$this->db->from('storelte_articulos');
$this->db->where('descripcion',$data['descripcion']);
$query = $this->db->get();
return $query->num_rows() == 0 ? false : true;
}
public function addProduct($data){
$this->db->insert('storelte_articulos',$data)
}

Prestashop - custom module and display images

This is my first time with prestashop and following the docs I was able to create a simple module that store some text.
I want to modify it and add the possibility to upload an image...on this scenario the docs is very poor so I tried myself and I was ablo to upload it but if I try to pass the image to the fronend all I get is NULL.
This is my configuration file:
<?php if ( ! defined('_PS_VERSION_') ) exit;
class Stilogopopup extends Module
{
public function __construct()
{
$this->name = 'stilogopopup';
$this->tab = 'front_office_features'; //Indica dove posizionare il modulo (http://doc.prestashop.com/display/PS15/Creating+a+PrestaShop+module)
$this->version = '1.0.0';
$this->author = 'Christian Giupponi STILOGO';
$this->need_instance = 0; //Indica se il modulo deve essere caricato quando si entra nel backoffice 0=no 1=si
$this->ps_versions_compliancy = array('min' => '1.5');
parent::__construct();
$this->displayName = $this->l('STILOGO PopUp');
$this->description = $this->l('Permette di mostrare un PopUp contenente un testo o una immagine');
$this->confirmUninstall = $this->l('Sicuro di voler disinstallare questo modulo?');
if( ! Configuration::get('STILOGOPOPUP_NAME') )
{
$this->warning = $this->l('Non è stato fornito nessun nome');
}
}
/*
* Installazione
* In questa funzione definisco anche gli hook per il frontend.
* Un elenco degli hook disponibili:
* http://doc.prestashop.com/display/PS15/Hooks+in+PrestaShop+1.5
*/
public function install()
{
if( parent::install() == false )
{
return false;
}
//Registro un hook per la homepage
if( ! $this->registerHook('displayHome') )
return false;
//Registro un hook per aggiungere dati all'header
if( ! $this->registerHook('displayHeader') )
return false;
Configuration::updateValue('STILOGOPOPUP_NAME', 'popup');
//Fatto
return true;
}
public function uninstall()
{
if( ! parent::uninstall() )
{
return false;
}
if( ! Configuration::deleteByName('STILOGOPOPUP_NAME') )
{
return false;
}
return true;
}
/*
* Questa funzione viene richiamata dal frontend quando viene eseguito l'hook:
* displayHome
* In questo modo posso inviare al frontend delle variabili per essere utilizzate
* dal template engine smarty.
* E' un semplice array che assegna alle variabili il valore delle configurazioni
* e recupera il file template che contiene il codice da mostrare in home
*/
public function hookDisplayHome( $params )
{
$this->context->smarty->assign(
array(
'stilogopopup_testo' => Configuration::get('STILOGOPOPUP_TEXT'),
'stilogopopup_titolo' => Configuration::get('STILOGOPOPUP_TITLE'),
'stilogopopup_image' => Configuration::get('STILOGOPOPUP_IMAGE'),
'stilogopopup_link' => $this->context->link->getModuleLink('stilogopopup', 'display')
)
);
return $this->display(__FILE__ , 'stilogopopup.tpl');
}
/*
* Questa funzione viene richiamata dal frontend quando viene eseguito l'hook:
* displayHeader
* e permette di inserire all'interno dei tag <head> del codice aggiuntivo,
* Utile quando si ha la necessità di inserire file css o js
*/
public function HookDisplayHeader()
{
$this->context->controller->addCSS($this->_path.'css/stilogopopup.css', 'all');
$this->context->controller->addJS($this->_path.'js/stilogopopup.js', 'all');
}
/*
* Questa funzione è utilizzata nel backend di prestashop per mostrare il form di configurazione
* del modulo.
* Gestisce sia il salvataggio dei parametri di configurazione che la stampa del form (tramite funzione esterna)
*/
public function getContent()
{
$output = null;
//Controllo se devo salvare dei dati
if( Tools::isSubmit('submit'.$this->name) )
{
//Recupero i valori degli input
$stilogopopup_text = strval(Tools::getValue('STILOGOPOPUP_TEXT'));
$stilogopopup_title = strval(Tools::getValue('STILOGOPOPUP_TITLE'));
$stilogo_image = $_FILES['STILOGOPOPUP_IMAGE'];
//Controllo se c'è una immagine da salvare
if( $stilogo_image['name'] != "" )
{
//Formati accettati
$allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
//Controllo che l'immagine sia in un formato accettato
if( in_array($stilogo_image['type'], $allowed) )
{
$path = '../upload/';
//Controllo se esiste già un file con questo nome
//Carico il file
if( ! move_uploaded_file($stilogo_image['tmp_name'], $path.$stilogo_image['name']) )
{
$output .= $this->displayError( $path.$stilogo_image['name'] );
return $output.$this->displayForm();
}
}
else
{
$output .= $this->displayError( $this->l('Formato immagine non valido.') );
return $output.$this->displayForm();
}
}
//Controllo se i campi obbligatori sono effettivamente stati riempiti
if( ! $stilogopopup_title || empty($stilogopopup_title) || ! Validate::isGenericName($stilogopopup_title) )
{
$output .= $this->displayError( $this->l('Devi inserire un titolo.') );
return $output.$this->displayForm();
}
//Se arrivo qui è perchè tutti i campi obbligatori sono stati riempiti quindi aggiorno i valori
Configuration::updateValue('STILOGOPOPUP_TEXT', $stilogopopup_text);
Configuration::updateValue('STILOGOPOPUP_TITLE', $stilogopopup_title);
Configuration::updateValue('STILOGOPOPUP_IMAGE', $stilogopopup_image['name']);
$output .= $this->displayConfirmation( $this->l('Impostazioni salvate') );
}
//Richiamo la funzione di stampa del form e concateno il ritultato (se c'è) del salvataggio
return $output.$this->displayForm();
}
/*
* Questa è la funzione che si occupa di generare il form di configurazione del modulo.
* Viene richiamata dalla funzione getContent e permette di definire dei campi da mostrare all'utente.
* Per generare i campi si utilizza un semplice array.
* Qui un elenco di tutti i tipi supportati:
* http://doc.prestashop.com/display/PS15/HelperForm
*/
public function displayForm()
{
//Recupero la lingua di default
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
//Creo i campi del form
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Impostazioni')
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Titolo del PopUp'),
'name' => 'STILOGOPOPUP_TITLE',
'required' => true
),
array(
'type' => 'textarea',
'label' => $this->l('Testo del PopUp'),
'name' => 'STILOGOPOPUP_TEXT',
'required' => false
),
array(
'type' => 'file',
'label' => $this->l('Inserisci una immagine'),
'name' => 'STILOGOPOPUP_IMAGE',
'display_image' => true,
'required' => false
),
),
'submit' => array(
'title' => $this->l('Salva'),
'class' => 'button'
),
);
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true; // false -> rimuove la toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' => array(
'desc' => $this->l('Salva'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Carico i valori correnti
$helper->fields_value['STILOGOPOPUP_TEXT'] = Configuration::get('STILOGOPOPUP_TEXT');
$helper->fields_value['STILOGOPOPUP_TITLE'] = Configuration::get('STILOGOPOPUP_TITLE');
//Genero il form
return $helper->generateForm($fields_form);
}
}
?>
As you can see I have added in the displayForm function this code that should add a file input:
array(
'type' => 'file',
'label' => $this->l('Inserisci una immagine'),
'name' => 'STILOGOPOPUP_IMAGE',
'display_image' => true,
'required' => false
),
and it does...in the getContent, where according to the docs all the save/display should live I get the image with PHP (does prestashop have a better built in solution for this?) in this way:
$stilogo_image = $_FILES['STILOGOPOPUP_IMAGE'];
//Controllo se c'è una immagine da salvare
if( $stilogo_image['name'] != "" )
{
//Formati accettati
$allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
//Controllo che l'immagine sia in un formato accettato
if( in_array($stilogo_image['type'], $allowed) )
{
$path = '../upload/';
//Controllo se esiste già un file con questo nome
//Carico il file
if( ! move_uploaded_file($stilogo_image['tmp_name'], $path.$stilogo_image['name']) )
{
$output .= $this->displayError( $path.$stilogo_image['name'] );
return $output.$this->displayForm();
}
}
else
{
$output .= $this->displayError( $this->l('Formato immagine non valido.') );
return $output.$this->displayForm();
}
}
Then I saved just the image name here:
Configuration::updateValue('STILOGOPOPUP_IMAGE', $stilogopopup_image['name']);
and I send it to the front end in the hookDisplayHome function in this way:
$this->context->smarty->assign(
array(
'stilogopopup_testo' => Configuration::get('STILOGOPOPUP_TEXT'),
'stilogopopup_titolo' => Configuration::get('STILOGOPOPUP_TITLE'),
'stilogopopup_image' => Configuration::get('STILOGOPOPUP_IMAGE'),
'stilogopopup_link' => $this->context->link->getModuleLink('stilogopopup', 'display')
)
);
return $this->display(__FILE__ , 'stilogopopup.tpl');
The problem is that the smarty variable $stilogopopup_image is NULL and I can see it just if I add in my view the {debug} tag.
What is the problem? The other fields works
in getContent() function you use the "$stilogo_image" variable, but for save to DB (Configuration::updateValue()) you are use another variable the "$stilogopopup_image".
I think this is the main reason of empty value in Configuration::get('STILOGOPOPUP_IMAGE')
Regards

Example of form validation cakephp

anybody please give an example of validation form in cakephp, because i have cakephp 2.3.3 and cant' validate forms, doesnt recognize my model Usuario
model usuario
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
};
public $validate = array(
'nombre' => array(
'sololetras' =>array(
'rule' => '/^[a-z]$/i',
'message' => 'Solo se Permite Letras en este Campo'
),
'required'=> true,
'allowEmpty' => false,
),
'apellido' => array(
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'El nombre de usuario debe ser una dirección de email válida.'
),
'allowEmpty' => false,
'required' => true,
),
'nrotlf' => array(
'rule' => array('phone', null, 'us')
)
);
}
?>
UsuarioController
<?php
class UsuariosController extends AppController{
var $name = 'Usuarios';
var $helpers = array('Html','Form');
//var $scaffold;
function cargapaq(){ //Carga la lista de la tabla Paquete
$this->loadModel('Paquete');
$paquetes = $this->Paquete->find('list', array('fields'=>'Paquete.id, Paquete.nombre'));
//debug($paquetes);
$this->set(compact('paquetes'));
}
function cargamod(){ //Carga la lista de la tabla Modelo
$this->loadModel('Modelo');
$modelos = $this->Modelo->find('list', array('fields'=>'Modelo.id, Modelo.nombre'));
//debug($modelos);
$this->set(compact('modelos'));
}
function index(){
$usuarios = $this->Usuario->find('all',array(
'fields'=>array(
'Usuario.nombre',
'Usuario.apellido',
'Usuario.email',
'Usuario.password',
'Usuario.grupo_id',
'Usuario.paquete_id',
'Usuario.modelo_id',
'Usuario.nrotlf',
'Usuario.valido',
'Usuario.id'),
'conditions'=>'Usuario.valido=true',
'order'=>'Usuario.apellido ASC')
);
$this->set('usuarios',$usuarios);
###Carga del nombre de los modelos de telefonos para cada modelo en el index.ctp####
$idmod = Hash::extract($usuarios,'{n}.Usuario.modelo_id');
$array=array();
$modelos=array();
$this->loadModel('Modelo');
for ($i=0; $i < count($idmod); $i++) {
$busqueda = $this->Modelo->find('all', array('fields'=>'Modelo.nombre', 'conditions'=>"Modelo.id=$idmod[$i]"));
array_push($modelos, $busqueda['0']);
}
$this->set('modelos',$modelos);
#######Fin de La Carga#########
###Carga del nombre de los planes de telefonos para cada modelo en el index.ctp####
$idpaq = Hash::extract($usuarios,'{n}.Usuario.paquete_id');
$array=array();
$paquetes=array();
$this->loadModel('Paquete');
for ($i=0; $i < count($idpaq); $i++) {
$busqueda = $this->Paquete->find('all', array('fields'=>'Paquete.nombre', 'conditions'=>"Paquete.id=$idpaq[$i]"));
array_push($paquetes, $busqueda['0']);
}
$this->set('paquetes',$paquetes);
#######Fin de La Carga#########
}
function add(){
if ($this->request->is('post')){
//$this->Usuario->create();
if ($this->Usuario->save($this->request->data)){
$this->Session->SetFlash('Usuario Nuevo Creado');
$this->redirect(array('action'=>'index'),null,true);
}else{
$this->Session->SetFlash('No se ha Agregado el Usuario, intente de Nuevo');
}
}
$this->cargapaq();
$this->cargamod();
}
add.ctp
<?php echo $this->Form->create('Usuario');?>
<fieldset>
<legend>Añadir Nuevo Usuario</legend>
<?php
echo $this->Form->input('nombre');
echo $this->Form->input('apellido');
echo $this->Form->input('email',array('label'=>'Correo Electrónico'));
echo $this->Form->input('password',array('label'=>'Contraseña'));
echo $this->Form->input('password2',array('label'=>'Repita Contraseña', 'type'=>'password'));
echo $this->Form->input('paquete_id',array('label'=>'Plan','empty'=>'(Seleccione un Plan)'));
echo $this->Form->input('modelo_id',array('label'=>'Modelo de Teléfono','empty'=>'(Seleccione un Modelo)'));
echo $this->Form->input('nrotlf',array('label'=>'Numero de Teléfono'));
echo $this->Form->input('grupo_id',array('empty'=>'(Seleccione un Rol)'));
echo $this->Form->input('valido', array('checked'=>'true'));
?>
</fieldset>
<?php echo $this->Form->end('Enviar') ?>
<?php echo $this->Html->link('Mostrar Todos Los Usuarios',array('action'=>'index')); ?>
i've seen the documentation but i can make the validation work
I solved the problem.. was the name of the model and doesnt recongnize the validation

Categories