Can´t show validation messages - validation

I am a newbie. I have tried many solutions on other posts but I just can't get it right. The mesages on my validation simply don't show up, but the value of the file input field gets null if the size validation does not pass, but it seems that the extension valdiation is not working as well. Why are no messages showing up and the extension validation not working?
I am using CakePHP 2.4.4.
Controller
public function admin_upload_image(){
$this->set('title_for_layout', 'Inserir Fotografias');
if(!$this->Session->check('User')) {
$this->Session->setFlash('Está a aceder a uma zona restrita. Por favor faça Login.');
$this->redirect(array(
'controller' => 'users',
'action' => 'login'));
}
$this->layout = 'admin_index';
if($this->request->is('post') || $this->request->is('put')) {
/* $file = $this->request->data['gallery_images']['path']['name'];*/
$file = array(
'GalleryImage' => array(
'path' => $this->request->data['gallery_images']['path']['name']
)
);
move_uploaded_file($this->data['gallery_images']['path']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/html/PushUp/app/webroot/img/gallery/' . $this->data['gallery_images']['path']['name']);
$this->loadModel('GalleryImage');
$this->GalleryImage->create();
//debug($file);
//die;
if($this->GalleryImage->save($file)){
$validationErrors = $this->GalleryImage->invalidFields();
$this->Session->setFlash($validationErrors['path']); // named key of the rule
$this->Session->setFlash(__('Evento guardado com sucesso.'));
}
//else{
//$error = $this->Notification->validationErrors;
//$this->set('error', $error);
//$this->Session->setFlash(__($error), 'Flash/warning');
//}
}
}
View
<h2>Adicionar Fotografia</h2>
<?php
echo "<br>";
echo $this->Form->create('GalleryImage',array('type'=>'file'));
echo $this->Form->file('gallery_images.path');
echo "<br>";
echo $this->Form->submit(__('Guardar'), array('class' => 'btn btn-success','formnovalidate' => false)) ;
echo $this->Form->end();
/*if ($this->Form->isFieldError('path')) {
echo $this->Form->error('path');
}*/
?>
Model
<?php
App::uses('AppModel', 'Model');
class GalleryImage extends AppModel{
public $displayField ='path';
public $useTable = 'gallery_images';
//public $actsAs = array('MultipleDisplayFields' => array('fields' => array('path', 'id')));
var $name = 'GalleryImage';
var $validate= array(
'path' => array(
'is_valid' => array(
'rule' => 'notEmpty',
'message' => 'Seleccione uma fotografia por favor.',
'last' => true),
'size' => array(
'rule' => array('fileSize','<=','1.5MB'),
'message' => 'O ficheiro deve ter um tamanho igual ou inferior a 1.5MB.',
'last' => true),
'extension' => array(
'rule' => array('extension', array('gif','jpeg','png','jpg')),
'message'=> 'A imagem deve estar num formato gif, jpeg, png ou jpg.',
'last' => true)
)
);
}
?>
debug($file)
\app\Controller\GalleriesController.php (line 58)
array(
'GalleryImage' => array(
'path' => '1604710_722861904399871_963210258_n.jpg'
)
)
pr($this->GalleryImage->invalidFields());
Notice (8): Undefined index: gallery_images [APP\Controller\GalleriesController.php, line 50]
Notice (8): Undefined index: gallery_images [APP\Controller\GalleriesController.php, line 53]
Notice (8): Undefined index: gallery_images [APP\Controller\GalleriesController.php, line 53]
Array
(
[path] => Array
(
[0] => Seleccione uma fotografia por favor.
[1] => Seleccione uma fotografia por favor.
)
)

Use Form->input
"building block" functions such as checkbox, radio, select and file are just the input. The normal way to generate forms is to use the input (or inputs) method:
echo $this->Form->input('path', array('type' => 'file'));
Or explicitly render errors
Alternatively, you can render the validation errors explicitly:
echo $this->Form->file('path');
echo $this->Form->error('path');

Related

Preview image in ACF gutenberg block

Is it possible to add an image to the gutenber block preview when using ACF to register the block ?
Here's the code to register the block:
acf_register_block(array(
'name' => 'bk-raisons',
'title' => __('Les raisons', 'diezel'),
'description' => __('Les raisons', 'diezel'),
'render_callback' => 'my_acf_block_render_callback',
'category' => 'spira-custom',
'icon' => 'align-wide',
'keywords' => array('bk-raisons'),
));
The preview appears when hovering the block.
Thank you !
I finally found a solution.
I don't know if you use Twig (Timber) or not.
If not check this : https://stackoverflow.com/a/67846162/6696150
For my part with Timber
When you declared your block add example attributes :
$img_quadruple = array(
'name' => 'img-quadruple',
'title' => __('Quatre images'),
'title_for_render' => 'img-quadruple',
'description' => __(''),
'render_callback' => 'ccn_acf_block_render_callback',
'category' => 'imgs',
'icon' => '',
'mode' => 'edit',
'keywords' => array( 'quatre images' ),
'example' => array(
'attributes' => array(
'mode' => 'preview',
'data' => array(
'preview_image_help' => get_template_directory_uri().'/assets/img/preview/preview_img_quadruple.jpg',
),
)
)
);
And when your declared your callback :
function ccn_acf_block_render_callback( $block, $content = '', $is_preview = false ) {
$context = Timber::context();
// Store block values.
$context['block'] = $block;
// Store field values.
$context['fields'] = get_fields();
// back-end previews
if ( $is_preview && ! empty( $block['data'] ) ) {
echo '<img src="'. $block['data']['preview_image_help'] .'" style="width:100%; height:auto;">';
return;
} elseif ( $is_preview ) {
echo 'Other condition';
return;
}
// Store $is_preview value.
$context['is_preview'] = $is_preview;
// Render the block.
Timber::render('gutenberg/gut_' . strtolower($block['title_for_render']) . '.twig', $context );
}

Validation is always firing rule message

My validation for my image upload is always firing the message related with the allowed size for the file to be uploaded, after I copied the code to the top of the validation array where previouslly was the is_valid rule, which was being always triggered as well, even when the file size is lower than the limit and even when the file is uploaded successfully. My is_unique rule is working as expected but the rest seem to be always triggered even when the files obey the rules .What is triggering this behaviour?
I am using CakePHP 2.4.4.
Controller
public function admin_upload_image(){
$this->set('title_for_layout', 'Inserir Fotografias');
if(!$this->Session->check('User')) {
$this->Session->setFlash('Está a aceder a uma zona restrita. Por favor faça Login.');
$this->redirect(array(
'controller' => 'users',
'action' => 'login'));
}
$this->layout = 'admin_index';
if($this->request->is('post') || $this->request->is('put')) {
/* $file = $this->request->data['gallery_images']['path']['name'];*/
//debug($this->request->data['gallery_images']['path']['name']);
//die;
$file = array(
'GalleryImage' => array(
'path' => $this->request->data['gallery_images']['path']['name']
)
);
move_uploaded_file($this->data['gallery_images']['path']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/html/PushUp/app/webroot/img/gallery/' . $this->data['gallery_images']['path']['name']);
$this->loadModel('GalleryImage');
$this->GalleryImage->create();
//debug($file);
//die;
if($this->GalleryImage->save($file)){
$validationErrors = $this->GalleryImage->invalidFields();
$this->Session->setFlash($validationErrors['path']); // named key of the rule
$this->Session->setFlash('Fotografia guardada com sucesso.', 'default', array('class'=>'alert alert-success'));
}
//else{
//debug($this->GalleryImage->invalidFields());
//die;
//$error = $this->Notification->validationErrors;
//$this->set('error', $error);
//$this->Session->setFlash(__($error), 'Flash/warning');
//}
}
}
Model
<?php
App::uses('AppModel', 'Model');
class GalleryImage extends AppModel{
public $displayField ='path';
public $useTable = 'gallery_images';
//public $actsAs = array('MultipleDisplayFields' => array('fields' => array('path', 'id')));
var $name = 'GalleryImage';
var $validate= array(
'path' => array(
'size' => array(
'rule' => array('fileSize','<=','1.5MB'),
'message' => 'O ficheiro deve ter um tamanho igual ou inferior a 1.5MB.',
//'last' => true,
'required'=> true),
'is_valid' => array(
'rule' => 'fileSelected',
'message' => 'Seleccione uma fotografia por favor.',
//'last' => true,
'required'=> true),
'extension' => array(
'rule' => array('extension', array('gif','jpeg','png','jpg')),
'message'=> 'A imagem deve estar num formato gif, jpeg, png ou jpg.',
//'last' => true,
'required'=> true),
'is_unique' => array(
'rule' => 'isUnique',
'message' => 'Uma fotografia com este nome já existe.',
'required'=> true
)
)
);
/*public function isUploadedFile($params) {
$val = array_shift($params);
if ((isset($val['error']) && $val['error'] == 0) || (!empty( $val['tmp_name']) && $val['tmp_name'] != 'none')) {
return is_uploaded_file($val['tmp_name']);
}
return false;
}*/
public function fileSelected($file) {
if(is_array($file) && array_key_exists('path', $file) && !empty($file['path'])) {
// Seems like a file was set
return true;
}
// No file set, doesn't validate!
return false;
}
}
?>
View
<style>
.alert-warning{
width:100%;
}
.error-message{
}
.col-lg-4{
width:100%;
}
</style>
<h2>Apagar Fotografia</h2>
<?php echo $this->Session->flash();?>
<br>
<table border="1" bordercolor="#e2e2e2" width="720" style="word-wrap: break-word" cellpadding="5px" class="">
<tr>
<?php
$i=0;
foreach( $gallery_images as $gallery_image ):?>
<?php
echo "<td style=text-align: justify>";
//echo $gallery_image['GalleryImage']['path'];
echo $this->Form->postLink('Apagar', array('controller'=>'Galleries', 'action'=>'admin_del_image', $gallery_image['GalleryImage']['id']/*,'prefix'=>'admin'*/), array('class'=>'foto_del btn btn-danger', 'title'=>'Apagar Fotografia'), __('Tem a certeza que quer apagar esta Fotografia?'));
echo "</td>";
echo "<td>";
//$src3 =$this->webroot. 'img/gallery/' .$gallery_image['GalleryImage']['path'];
echo $this->Html->image('gallery/' . $gallery_image['GalleryImage']['path'] , array('width' => '200px', 'height' => '133px', 'alt' => $gallery_image['GalleryImage']['path'] ));
echo "</td>";
$i++;
if($i==4){
echo "</tr><tr>";
$i=0;
}
?>
<?php endforeach ?>
</tr>
</table>
You are passing the $file variable to be save
$this->GalleryImage->save($file)
and you are setting this variable value manually
$file = array(
'GalleryImage' => array(
'path' => $this->request->data['gallery_images']['path']['name']
)
);
so you are not passing file information to your model. you have to pass $this->request->data['gallery_images']['path'] to your save method

How addValidator works with Zend Form?

I supposed the $form->addVlidator functions works as some front-end form checking thing, however when I add it, even the input is invalid, it seems the form is still being submited.
Or I was wrong, it's more a controller-side checking, which means the form will submit the data whatever then the server sides returns the error message?
My code works like this.
Form class:
<?php
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setName('stdForm');
//$this->setMethod('post');
//$this->addDecorator('HtmlTag', array('tag' => 'div', 'class' => 'my-lovely-form'));
$this->setAttrib('enctype', 'multipart/form-data');
$this->setAction('somewhere')
->setMethod('post');
$username = $this->createElement('text', 'name', array('label' => 'Username:'));
$username->addValidator('alnum')
->addValidator('regex', false, array('/^[a-z]+/'))
->addValidator('stringLength', false, array(9, 20, 'messages'=>'Cannot be more than 9 chars'))
->setRequired(true)
->addFilter('StringToLower');
$email = $this->createElement('text', 'email', array('label' => 'E-mail'));
$email->addValidator('StringLength', false, array(8))
->setRequired(true);
$password = $this->createElement('password', 'pass1', array('label' => 'Password'));
$password->addValidator('StringLength', false, array(6))
->setRequired(true);
$password2 = $this->createElement('password', 'pass2', array('label' => 'Repeat password'));
$password2->addValidator('StringLength', false, array(6))
->setRequired(true);
$message = $this->createElement('textarea', 'message', array('label' => 'Message'));
$message->addValidator('StringLength', false, array(6))
->setRequired(true)
->setAttrib('COLS', '40')
->setAttrib('ROWS', '4');
$captcha = new Zend_Form_Element_Captcha('foo', array(
'label' => "human?",
'captcha' => 'Figlet',
'captchaOptions' => array(
'captcha' => 'Figlet',
'wordLen' => 6,
'timeout' => 300,
),
));
// Add elements to form:
$this->addElement($username)
->addElement($email)
->addElement($password)
->addElement($password2)
->addElement($message)
->addElement($captcha)
// use addElement() as a factory to create 'Login' button:
->addElement('submit', 'send', array('label' => 'Form sender'));
}
}
Controller code:
public function aboutAction()
{
$this ->_helper->layout->disableLayout();
$form = new Application_Form_Test();
$this->view->testForm = $form;
}
View file:
<?php echo $this->testForm;?>
The second: "the form will submit the data whatever then the server sides returns the error message". In order to do this you must call $form->isValid($this->_request->getPost()) in your action.
If it is not valid then you need to send data back to the user:
$form->populate($this->_request->getPost());
$this->view->form = $form;
For client side validation you can use http://docs.jquery.com/Plugins/Validation

CakePHP 2 & Translate Behavior: save multiple translations in a single form

Its possibile save multiple translations of the same field in a single form?
I have a model with Behavior Translate to translate the name field. The three translations (deu, eng, ita) are properly recorded in the i18n table but the field is not properly validated! Any suggestions?
app/Model/Category.php
class Category extends AppModel {
public $actsAs = array('Translate' => array('name' => 'TranslateName'));
public $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Error notempty',
),
),
);
...
app/View/Categories/admin_edit.ctp
<?php
echo $this->Form->create('Category');
echo $this->Form->input('Category.id');
echo $this->Form->input('Category.name.deu', array('label' => __d('Category', 'Name Deu')));
echo $this->Form->input('Category.name.eng', array('label' => __d('Category', 'Name Eng')));
echo $this->Form->input('Category.name.ita', array('label' => __d('Category', 'Name Ita')));
echo $this->Form->end(__d('app', 'Submit'));
?>
app/View/Controller/CategoriesController.php
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__d('Category', 'The category has been saved'));
} else {
$this->Session->setFlash(__d('Category', 'The category could not be saved. Please, try again.'));
}
I have a similar Problem
But you can try out this - it should solve it for you: https://github.com/zoghal/cakephp-MultiTranslateBehavior

Why aren't validation errors being displayed in CakePHP?

I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.

Resources