The Errors messages in edit actions, doesn't appear - php

I have my validation rules in model, and everything is fine. It validates like I want to, but in the Edit actions, although it not validates, don't show me de red error marks under textbox.
Any tip?
Thanks.
The Model Code(Model name is Safpercent):
var $validate = array(
'sequencia' => array(
'must_be_numeric' => array(
'rule' => 'Numeric',
'message' => 'Number Field: insert only numbers.'
)
),
);
View Text Box:
echo $form->input('Safpercent.sequence', array('id' => 'sequence', 'options' => $criteria, 'label' => false, 'div' => false, 'style' => 'width: 300px'));
Controller Code:
function edit($id = null) {
$criteria = $this->Safpercent->Safrequirement->find('list', array('fields' => array('Safrequirement.sequencia', 'Safrequirement.descricao'), 'conditions' => array('Safrequirement.tipo' => 'ILC')));
$this->set('criteria', $criteria);
if (!$id && empty($this->data)) {
$this->Session->setFlash(RecordNotValid, 'flash_failure');
$this->redirect(array('controller' => 'safpercents', 'action'=>'index'));
}
if (!empty($this->data)) {
$sequencia = $this->data['Safpercent']['sequencia'];
if($this->data['Safpercent']['tipo'] == ''){$tipo = 'ILC';}else{$tipo = $this->data['Safpercent']['tipo'];}
$encontro = $this->Safpercent->Safrequirement->find('all', array('conditions' => array('sequencia' => $sequencia, 'tipo' => $tipo)));
if($encontro <> array()){
if ($this->Safpercent->save($this->data)) {
$this->Session->setFlash(RecordSaved, 'flash_success');
$this->redirect(array('controller' => 'safpercents', 'action'=>'index'));
}else{
$this->Session->setFlash(RecordNotSaved, 'flash_failure');
}
}else{
$this->Session->setFlash('A Sequência que tentou Inserir não existe. Verifique a tabela de novo, por favor.');
}
}
if (empty($this->data)) {
$this->data = $this->Safpercent->read(null, $id);
$this->set('id', $id);
}
$this->set('cod_percent',$this->Safpercent->read(null, $id));
}
(Portuguese Variables and Text in some cases)

Try
debug($this->Safpercent->validationErrors)
and see if it shows any errors.

I see now. In your controller, you are using the sequencia field that you are validating, but not doing any validation at this stage. It passes a non-number to the find query, which then returns an error or something, and the save never gets called?
Before you do this:
$sequencia = $this->data['Safpercent']['sequencia'];
You should check that the data validates, by calling this:
$this->ModelName->set($this->data);
if ($this->ModelName->validates()) {
... //do your business here
So basically, change:
if (!empty($this->data)) {
to:
$this->Safpercent->set($this->data);
if (!empty($this->data) && $this->Safpercent->validates()) {

Related

Cakephp redirection after submission

I'm developing an application with Cakephp and I can't find my answer in existing topics...
I have a main menu with several action (Edit/Delete/Add) which is manage sockets. When I edit a socket and I submit my update, my socket is updated correctly BUT my redirection on the main menu doesn't work. The URL stay the same.
For example, I edit socket with id = 2. The application go to '/my/app/sockets/edit/2'. After update and submit, the application should redirect to '/my/app/sockets/index' but it doesn't work.
Below, you can see my code.
SocketsController.php :
public function index($searchCloset = null) {
$this->Paginator->settings = $this->paginate;
if($searchCloset != null) {
$sockets = $this->paginate('Socket', array(
'Closet.name LIKE' => $searchCloset
));
}
else{
$sockets = $this->paginate('Socket');
$searchCloset = '' ;
}
$this->set('sockets',$sockets);
$this->set('closets',$this->Socket->Closet->find('all'));
$this->set('searchCloset',$searchCloset);
}
public function edit($id = null){
// Bad socket management
if (!$id) {
throw new NotFoundException(__('Invalid socket'));
}
$socket = $this->Socket->findByid_socket($id);
if (!$socket) {
throw new NotFoundException(__('Invalid socket'));
}
// if there's a submit
if ($this->request->is(array('post'))) {
$this->Socket->id = $id;
if ($this->Socket->save($this->request->data)) {
// update 'lastchange' column
if($this->updateSocketStatus($this->Socket->id)){
$this->Session->setFlash(__('Your socket has been updated.'));
}
else {
$this->Session->setFlash(__('Unable to create history.'));
}
}
else {
$this->Session->setFlash(__('Unable to update your socket.'));
}
return $this->redirect(array('controller' => 'sockets','action' => 'index'));
}
// send all informations about the socket to the view
$this->set('socket',$socket);
// send closets list to the view (select menu)
$this->set('closets',$this->Socket->Closet->find('list',array(
'fields' => array('Closet.id_closet','Closet.name')
)));
}
edit.ctp :
<h2>Edit socket</h2>
<div><?php
echo $this->Form->create('Socket');
echo $this->Form->input('Socket.name', array(
'label' => 'Socket name :',
'default' => $socket['Socket']['name']
));
echo $this->Form->input('Socket.location', array(
'label' => 'Location :',
'default' => $socket['Socket']['location']
));
echo $this->Form->input('Socket.comment', array(
'label' => 'Comment :',
'default' => $socket['Socket']['comment']
));
echo $this->Form->input('Socket.closet_id',array(
'type' => 'select',
'label' => 'Closet :',
'options' => $closets,
'default' => $socket['Closet']['id_closet']
));
echo $this->Form->end('Save socket');
echo $this->Form->postButton(
'Back',
array('controller' => 'sockets','action' => 'index'),
array(
'id' => 'back_button',
'class' => 'ui-btn ui-btn-inline ui-icon-back ui-btn-icon-left'
)
);
?></div>
I've already search and it could be a cache problem.
Thanks in advance.
Can you force with
$this->redirect($this->referer());
Please, try and comment
Your request checking if-statement is omitted, because is() method accepts param of string type according to documentation.
So you should change line:
if ($this->request->is(array('post'))) { ... }
into:
if ($this->request->is('post')) { ... }

zend 2 - custom field name in validation message

I would like to customize input name to show in my view when happen an error in validation of the form
$this->add(array(
'name' => 'generica_descricao', // I WOULD LIKE TO CALL HIM DESCRIÇÃO
//'custom_name' => 'Descrição',
'required' => true,
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
'isEmpty' => 'O campo não pode ser vazio'
),
),
),
));
and when i call getMessage() as the code above
if (!$form->isValid()) {
$resultado = new Resultado(Resultado::FLAG_WARNING, $form->getMessages());
$resultado->setaRetornoLayoutErro($this->getServiceLocator());
return $resultado->getJson();
}
they will return
array('Descrição' => 'O campo não pode ser vazio');
then i will can give this array to my view and show dialog with the correctly messages, can anybody help how do that in zend?
I found a best way, create a new method that extends the default form getting the name from the label in the form.
abstract class GenericForm extends Form {
public function getMessagesTranslated($elementName = null) {
$mensagensOriginais = $this->getMessages($elementName);
foreach ($mensagensOriginais as $chave => $mensagens) {
$label = TranslateUtil::translate($this->get($chave)->getLabel());
$mensagensOriginais[$label] = $mensagensOriginais[$chave];
unset($mensagensOriginais[$chave]);
}
return mensagensOriginais;
}
I customize my filter with a method that translates the field name, is not what i want but it works for now:
generic filter
abstract function convertErrorsArrayKeyToFriendlyNames($erros);
specific filter:
public function convertErrorsArrayKeyToFriendlyNames($erros) {
foreach ($erros as $chave => $valor) {
if ($chave == 'generica_descricao') {
$erros['Descrição'] = $erros[$chave];
unset($erros[$chave]);
} else if ($chave == 'generica_ordem') {
$erros['Ordem'] = $erros[$chave];
unset($erros[$chave]);
} else if ($chave == 'generica_ativo') {
$erros['Ativo'] = $erros[$chave];
unset($erros[$chave]);
}
}
return $erros;
}
and in the controller
if (!$form->isValid()) {
$erros = $filtro->convertErrorsArrayKeyToFriendlyNames($form->getMessages());
$resultado = new Resultado(Resultado::FLAG_WARNING, $erros);
$resultado->setaRetornoLayoutErro($this->getServiceLocator());
return $resultado->getJson();
}

ASK CakePHP - work with password field

I have searched many topic in here but I can't solve my problem. Please check this for me.
I made the register page and when I made for password field...
I had users_controller.php like:
class UsersController extends AppController
{
var $name = "Users";
var $helpers = array('Paginator','Html');
var $paginate = array();
//Doi tuong component de thuc thi thao tac login
public $components = array
(
'Auth' => array
(
'authorize' => 'controller',
'loginRedirect' => array
(
'admin' => FALSE,
'controller' => 'users',
'action' => 'dashboard'
),
'loginError' => 'Invalid account',
'authError' => 'You don\'t have permission'
),
'Session'
);
//Ham loc cac user truoc khi truy cap trang
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('add');
$this->Auth->allow('viewuserall');
}
//Ham them moi user
public function add()
{
$this->layout = 'TDCake';
$this->User->set($this->data);
if($this->User->valid_user() == TRUE)
{
if(!empty($this->data))
{
$this->User->create();
if($this->User->save($this->data))
{
$this->Session->setFlash('User has been created!');
$this->redirect(array('action'=>'login'));
}
else
{
$this->Session->setFlash('Please correct the errors');
}
};
}
else
{
$this->Session->setFlash("Your data is NOT available");
}
}
//Ham login cho user
public function login()
{
$this->layout = 'TDCake';
if
(
!empty($this->data) &&
!empty($this->Auth->data['User']['username'])&&
!empty($this->Auth->data['User']['password'])
)
{
$user = $this->User->find
(
'first',array
(
'conditions'=>array
(
'User.email'=>$this->Auth->data['User']['username'],
'User.password'=>$this->Auth->data['User']['password']
),
'recursive' => -1
)
);
if(!empty($user) && $this->Auth->login($user))
{
if($this->Auth->autoRedirect)
{
$this->redirect($this->Auth->redirect());
}
}
else
{
$this->Session->setFlash
(
$this->Auth->loginError,
$this->Auth->flashElement,
array(),'auth'
);
}
}
}
//Ham logout cho user
public function logout()
{
$this->redirect($this->Auth->logout());
}
//Ham gi cha biet, de do tinh sau =))
public function dashboard()
{
$this->layout = 'TDCake';
}
//Ham view cac user khong dieu kien trong table users
function viewuserall()
{
$this->layout = 'TDCake';
$this->paginate=array
(
'limit' => 10,
'order' => array('id' => 'asc'),
);
$data = $this->paginate("User");
$this->set("data",$data);
}
}
User.php in Model is:
class User extends AppModel
{
var $name = "User";
var $validate = array();
function validate_passwords()
{
if($this->data[$this->alias]['pass'] == $this->data[$this->alias]['rpass'])
{
return $this->data[$this->alias]['pass'] = $this->data['User']['password'];
}
else return FALSE;
}
function valid_user()
{
$this->validate = array
(
//Kiem tra username truoc khi add
'username' => array
(
'rule01_notEmpty' => array
(
'rule' => 'notEmpty',
'message' => 'You must enter your Username !'
),
'rule02_max16' => array
(
'rule' => array('maxLength', 20),
'message' => 'Your Username must be less than 20 chars !'
),
'rule03_exists' => array
(
'rule' => 'isUnique',
'message' => 'Your Username have already existed !'
)
),
//Kiem tra email truoc khi add
'email' => array
(
'rule01_notEmpty' => array
(
'rule' => 'notEmpty',
'message' => 'You must enter your Email !'
),
'rule02_exists' => array
(
'rule' => 'isUnique',
'message' => 'Your Email have already existed !'
),
'rule03_emailtype' => array
(
'rule' => 'email',
'message' => 'You didn\'t type a email !'
)
),
//Kiem tra password truoc khi add
'pass' => array
(
'length' => array
(
'rule' => array('between', 6, 20),
'message' => 'Your password must be between 8 and 40 characters.',
),
),
'rpass' => array
(
'length' => array
(
'rule' => array('between', 6, 20),
'message' => 'Your password must be between 8 and 40 characters.',
),
'compare' => array
(
'rule' => 'validate_passwords',
'message' => 'The passwords you entered do not match.',
)
)
);//End this->validate=array
if($this->validates($this->validate==TRUE))
{
return TRUE;
}
else
{
return FALSE;
}
}//End function valid_user
}
add.ctp is
echo $this->Session->flash('auth');
echo $this->Form->create();
echo $this->Form->input('username', array('label' => ('Username')));
echo $this->Form->input('email', array('label' => ('Email')));
echo $this->Form->input('pass', array('label' => ('Password'),'type' => 'password', 'value' => ''));
echo $this->Form->input('rpass', array('label' => ('Repeat Password'), 'type' => 'password', 'value' => ''));
echo $this->Form->input('firstname', array('label' =>('Firstname')));
echo $this->Form->input('lastname', array('label' =>('Lastname')));
echo $this->Form->input('dob', array('label' =>('DOB'),'type' => 'date'));
echo $this->Form->end('Register');
Explanation:
So, in this case, I can validate 2 Password Fields (empty, not equal,...), but it can't insert to the database. That mean it INSERTED current data into the DB but password column in DB is EMPTY. In database, my password column name "password" also.
In another case, I change the name "pass" into "password" for the
echo $this->Form->input('pass', array(
Of course, I have changed any place related to...
and in that case, it can be inserted the password but can not validate anything.
I am too confused about this...I don't know what I am wrong is....can anybody help me.
I am not sure why you are doing an assignment in your validate function:
return $this->data[$this->alias]['pass'] = $this->data['User']['password'];
And even if you were doing an assignment, it should be:
return $this->data['User']['password'] = $this->data[$this->alias]['pass'];
Realize that the field "password" is getting the value from $this->data which has the information, not the other way around.
Also. It would be better (in terms of clarity), to break this code in two lines.
$this->data['User']['password'] = $this->data[$this->alias]['pass'];
return $this->data['User']['password'];
You should name your field the exact name "password" if that's what it is called in the database AND if you are not explicitly assigning it.
Your add function is not doing the above, and further more, as a best practice, you should be hashing the password.
See the CakePHP book on tutorials and examples.
Take some time to go through it with all the snippets and recommendations. And don't forget the standards. :)

cakephp, save multiple row of the same model

I'm tying to figure out how to save, for example 4 days of schedule in one view, and have each field validation message show if validation fails.
My approach was at first to use $this->SomeModel->saveAll() but couldn't save so I tried another way using foreach and all data is saved (pass validation) but no validation message is shown. if you guys know better way to do this I'm open for any suggestions.
Model
public $validate = array(
'hour_from'=>array(
'some mgs' => array(
'rule' => 'good_hours',
),
),
);
public function good_hours($data) {
//throw new Exception(($data['hour_from'] >= $this->data['Hour']['hour_to']));
if ($data['hour_from'] >= $this->data['Hour']['hour_to']) {
return false;
}
return true;
}
Controller:
if ($this->request->is('post')) {
$all_good = true;
foreach ($this->request->data['Hour'] as $day){
if ($this->Hour->save($day)){
}else {
$all_good = false;
$this->Session->setFlash('hours not saved');
}
}
//if all saves are correct rediredt to index
if ($all_good) {
$this->Session->setFlash(__('Hours saved'));
return $this->redirect(array('action' => 'index'));
}
}
View
foreach ($days as $count => $day):
$form_model ='Hour.'.$count. '.';
?>
<fieldset>
<legend><?php
$day_array = (array) $day;
$day = $day_array['date'];
echo $day;
?></legend>
<?php
echo $this->Form->input($form_model.'type_holiday_id', array(
'label'=> 'Typ urlopu',
'type' => 'select',
'options' => $type_holidays,
'empty' => true
));
echo $this->Form->input($form_model.'hour_from', array('label' => 'od'));
echo $this->Form->input($form_model.'hour_to', array('label' => 'do'));
echo $this->Form->input($form_model.'date', array('type' => 'hidden', 'value' => $day));
echo $this->Form->input($form_model.'subordinate_id', array('type' => 'hidden', 'value' => $user['User']['id']));
echo $this->Form->input($form_model.'supervisor_id', array('type' => 'hidden', 'value' => $current_user['id']));
?>
</fieldset>
Request->data array
Hour(array)
0(array)
type_holiday_id
hour_from 8
hour_to 15
date 2014-01-20
subordinate_id 193
supervisor_id 557
1(array)
type_holiday_id
hour_from 7
hour_to 14
date 2014-01-21
subordinate_id 193
supervisor_id 557
Ok i found solution, and everything works perfectly now in controller i needed to change save to saveAll, function add in Controller should look like this:
if ($this->request->is('post')) {
if ($this->Hour->saveAll($this->request->data['Hour'], Array('validate' => 'first', 'deep' => true))){ <--- most important is that data['Hour']
$this->Session->setFlash(__('Godziny robocze zapisane'));
return $this->redirect(array('action' => 'index'));
} else{
$this->Session->setFlash('Godziny robocze nie zostały zapisane.');
}
}

Cakephp AuthComponent: Login successfull despite wrong password

I'm running a 2.2.2 CakePHP Application, everything works as desired. Now I'm developing a Android App for it and therefore need to create the interfaces between those two apps. That's why I need to login users manually. So I created a whole new controller, the AndroidController, in order to bundle everything at one place. First thing to do would be the Login-Action. So I setup the following controller:
<?php
App::uses('AppController', 'Controller');
/**
* Android Controller
*
* #package app.Controller
*/
class AndroidController extends AppController {
public $components = array('RequestHandler','Auth');
public $uses = array('User');
public function beforeFilter() {
$this->Auth->allow();
}
public function login() {
//For testing purposes
$postarray = array('_method' => 'POST','data' => array('User' => array('email' => 'user#gmail.com', 'password' => 'THISisDEFINITELYaWRONGpassword')));
$id = $this->tryToGetUserID($postarray['data']['User']['email']);
if($id == 0){
//return Error json, unknown User
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 1,
'error_msg' => 'Unknown User'
));
}else{
// if ($this->request->is('post')) {
$postarray['data']['User'] = array_merge($postarray['data']['User'], array('id' => $id));
$this->User->id = $id;
if ( $this->Auth->login($postarray['data']['User'])) {
// Login successfull
$this->User->saveField('lastlogin', date(DATE_ATOM));
$user = $this->User->find('all', array(
'recursive' => 0, //int
'conditions' => array('User.id' => $id)
));
$loggedInUser = array(
'tag' => 'login',
'success' => 1,
'error' => 0,
'uid' => '??',
'user' => array(
'name' => $user['0']['User']['forename'].' '.$user['0']['User']['surname'],
'email' => $user['0']['User']['email'],
'created_at' => $user['0']['User']['created'],
'updated_at' => $user['0']['User']['lastlogin']
)
);
$this->set('result', $loggedInUser);
} else {
// Login failed
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 2,
'error_msg' => 'Incorrect password!'
));
}
// }
}
}
public function tryToGetUserID($email = null) {
$user = $this->User->find('list', array(
'conditions' => array('User.email' => $email)
));
if(!empty($user)){
return array_keys($user)['0'];
}else{
return 0;
}
}
}
You need to know that this method will be called as a POST request, but for testing purposes I manually created a post-array. In future I will use the $_POST array.
So, what happens: The Login with a registered user works, but it works every time! Even though the password is wrong or missing! The program never reaches the part in code with the "Login failed" comment.
Am I missing something here..?
Thank you!
If you take a closer look at the documentation you will notice that AuthComponent::login() will ...
In 2.x $this->Auth->login($this->request->data) will log the user in with whatever data is posted

Categories