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
Related
I am beginner in CI. I am getting an error in insert_batch function in CodeIgniter. When I insert array into insert_batch I get this error
Unknown column 'Array' in 'field list'
and
Array to string conversion
I've done many solutions but still get this error,
Can anyone give me an idea?
thanks in advance
in my views
<input type="text" name="companionship[]"> and so forth.
controller
public function addstatistics()
{
$i =0;
foreach($_POST['companionship_id'] as $companionship_id):
$value1[$i++] = array(
'companionship_id'=> $companionship_id
);
endforeach;
foreach($_POST['zone_id'] as $zone_id):
$value2[$i++] = array(
'zone_id'=> $zone_id
);
endforeach;
foreach($_POST['district_id'] as $district_id):
$value3[$i++] = array(
'district_id'=> $district_id
);
endforeach;
foreach($_POST['area_id'] as $area_id):
$value4[$i++] = array(
'area_id'=> $area_id
);
endforeach;
foreach($_POST['baptism'] as $baptism):
$value5[$i++] = array(
'baptism'=> $baptism
);
endforeach;
foreach($_POST['confirm'] as $confirm):
$value6[$i++] = array(
'confirm'=> $confirm
);
endforeach;
foreach($_POST['ibd'] as $ibd):
$value7[$i++] = array(
'ibd'=> $ibd
);
endforeach;
foreach($_POST['iasm'] as $iasm):
$value8[$i++] = array(
'iasm'=>$iasm
);
endforeach;
foreach($_POST['ni'] as $ni):
$value9[$i++] = array(
'ni'=>$ni
);
endforeach;
foreach($_POST['ph'] as $ph):
$value10[$i++] = array(
'ph'=>$ph
);
endforeach;
foreach($_POST['wh'] as $wh):
$value11[$i++] = array(
'wh'=>$wh
);
endforeach;
$this->my_model->addstatistics($value1,$value2,$value3,$value4, $value5,$value6,$value7,$value8,$value9,$value10,$value11);
}
MODEL function
addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $value1,
'zone_id'=> $value2,
'district_id'=> $value3,
'area_id'=> $value4,
'baptism'=> $value5,
'confirm'=> $value6,
'ibd'=> $value7,
'iasm'=> $value8,
'ni'=> $value9,
'ph'=> $value10,
'wh'=> $value11,
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
Can anybody give me idea on how can i solve this problem?
Try this.
public function addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $data['companionship_id'][$x]['companionship_id'],
'zone_id'=> $data['zone_id'][$x]['zone_id'],
'district_id'=> $data['district_id'][$x]['district_id'],
'area_id'=> $data['area_id'][$x]['area_id'],
'baptism'=> $data['baptism'][$x]['baptism'],
'confirm'=> $data['confirm'][$x]['confirm'],
'ibd'=> $data['ibd'][$x]['ibd'],
'iasm'=> $data['iasm'][$x]['iasm'],
'ni'=> $data['ni'][$x]['ni'],
'ph'=> $data['ph'][$x]['ph'],
'wh'=> $data['wh'][$x]['wh'],
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
after a few hours of pondering, I already fix the errors
and now it working fine
here is the code
public function mymethod()
{
$companionship_id = $this->input->post('companionship_id[]');
$zone_id = $this->input->post('zone_id[]');
$district_id = $this->input->post('district_id[]');
$area_id = $this->input->post('area_id[]');
$baptism = $this->input->post('baptism[]');
$confirm = $this->input->post('confirm[]');
$ibd = $this->input->post('ibd[]');
$iasm = $this->input->post('iasm[]');
$ni = $this->input->post('ni[]');
$ph = $this->input->post('ph[]');
$wh = $this->input->post('wh[]');
$value = array();
for($i=0; $i<count($companionship_id); $i++)
{
$value[$i] = array(
'companionship_id' => $companionship_id[$i],
'zone_id' => $zone_id[$i],
'district_id' => $district_id[$i],
'area_id' => $area_id[$i],
'baptism' => $baptism[$i],
'confirm' => $confirm[$i],
'ibd' => $ibd[$i],
'iasm' => $iasm[$i],
'ni' => $ni[$i],
'ph' => $ph[$i],
'wh' => $wh[$i]
);
}
$this->db->insert_batch('monthly_statistics',$value);
$this->session->set_flashdata("success",alert("alert-success","Successfully Inserted"));
redirect(base_url('to_url'));
exit();
}
Am creating a file uploader using the kartik uploader bu the problem is that it doesn't pass extra data
The form(view) code
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'case_description')->textArea();?>
<?php echo $form->field($evidence, 'path')->widget(FileInput::classname(), [
'options' => ['accept' => '*','multiple' => true,'name'=>'images'],
'pluginOptions' => [
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'showPreview' => true,
'showCaption' => true,
'showRemove' => true,
'showUpload' => true,
'browseLabel' => 'Insert Evidence',
'uploadUrl' => Url::to(['cases/upload']),
'maxFileCount' => 10,
'uploadExtraData' => [
'album_id' => "javascript: return $('#cases-case_description').val());",
],
],
]
);?>
The $evidence ,path is a table related to the models table
The controller that I have tested with (code)
public function actionUpload(){
$ann = empty($_POST['album_id']) ? '' : $_POST['album_id'];
var_dump($ann)
}
This returns null showing that the album_id is not passed to the controller and yet the $model->case_description is the field above the upload widget
The new controller
public function actionUpload(){
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
Due the problem with dinamic/variable assign to extraData i suggest a simple solution based on POST / submit method (eventually set the proper action in your form)
use kartik\widgets\FileInput
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'case_description')->textArea();?>
<?php echo $form->field($evidence, 'path')->widget(FileInput::classname(), [
'options' => ['accept' => '*','multiple' => true,'name'=>'images'],
'pluginOptions' => [
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'showPreview' => true,
'showCaption' => true,
'showRemove' => true,
'showUpload' => true,
'browseLabel' => 'Insert Evidence',
'uploadUrl' => Url::to(['cases/upload']),
'maxFileCount' => 10,
],
]
);
echo Html::submitButton($model->isNewRecord ? 'Upload' : 'Update', [
'class'=>$model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']
);
ActiveForm::end();
?>
I have a ajax link in yii when user click it do something and update a element html (content of td) without refresh page how can change 2 element html?
I explain more:
in view i have a table by some td for show information a td for send information (there are a image ajaxlink) and a td by message of content (example: "not send")
When user click image link call a function and valid information (...) and change message of td ('validation is success').("not send" change to "validation is success")
I did what I was told but i want to remove ajaxlink and replace it by a simple image how
can I do it?
i add:
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'))
view.php:
<td id="send_<?php echo CHtml::encode($profileInformationServices->id); ?>"><?php echo "not send"; ?></td>
<td id="sended_<?php echo CHtml::encode($profileInformationServices->id); ?>">
<?php
echo $profileInformationServices->send ? CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array( 'title' => 'sended success')):
CHtml::ajaxLink(CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array(
'title' => 'Send for valid')), Yii::app()->createUrl('/profileInformationService/send'),
array( // ajaxOptions
'type' => 'POST',
'data' => array( 'id' => $profileInformationServices->id ),
'update' => '#send_'.$profileInformationServices->id,
)
);
?>
</td>
controller:
public function actionSend() {
if (Yii::app()->request->isPostRequest) {
$model = $this->loadModel($_POST["id"]);
$model->send = 1;
$model->save();
echo "sended success";
}
}
Use ajaxLink callback to change the text in td.
<?php
//I am keeping your ternary code in if-else condition for readability
if($profileInformationServices->send)
{
echo CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'));
}
else
{
echo CHtml::ajaxLink
(
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array('title' => 'Send for valid')),
Yii::app()->createUrl('/profileInformationService/send'),
array
(
'type' => 'POST',
'data' => array('id' => $profileInformationServices->id),
'success'=>'function(data)
{
if(data=="sended success")
{
$("#send_'.$profileInformationServices->id.'").html("validation is success");
}
}',
)
);
}
?>
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');
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.