"Notice: Array to string conversion" in CakePHP when uploading a file - php

I'm having some issues with a form and it's driving me insane.
Whenever I try to upload an image to my database, I get
Notice: Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]
I'm not sure what I'm doing wrong or missing. Any help is appreciated.
This is my Model
'banner_image' => array(
'not_required' => array(
'allowEmpty' => true,
'required' => false,
),
'is_image' => array(
'rule' => 'is_image_check',
'message' => 'We found that the file you uploaded is not an image.',
//'allowEmpty' => false,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
This is my controller
/**
* admin_add method
*
* #return void
*/
public function admin_add() {
if ($this->request->is('post')) {
$this->Survey->create();
if ($this->Survey->save($this->request->data)) {
$this->Session->setFlash(__('The survey has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The survey could not be saved. Please, try again.'));
}
}
}
and this is my form
<?php echo $this->Form->create('Survey', array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Admin Add Survey'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('subtitle');
if ( empty($this->request->data['Survey']['banner_image']) or isset($this->validationErrors['Survey']['banner_image']) ):
echo $this->Form->input('banner_image', array('type'=>'file'));
else :
echo $this->Html->image('/img/surveys/' . $this->request->data['Survey']['banner_image'] ) ;
echo $this->Html->link('Remove this image?', '/admin/Surveys/remove_image/' . $this->request->data['Survey']['id'] ) ;
endif;
// echo $this->Form->input('listing_image', array('type'=>'file'));
echo $this->Form->input('url_iframe');
echo $this->Form->input('enable');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>

This is what your controller receives for field banner_image:
$this->request->data['Survey']['banner_image'] = array(
'name' => 'example_image.jpg',
'type' => 'image/jpg',
'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp', //path will vary on Unix-like OSes
'error' => 0,
'size' => 41737,
);
If you attempt to save this into your table, you will get
Notice: Array to string conversion in filename on line X
Therefore, you have to do some pre-processing before you can call save().
Your surveys.banner_image is probably set to accept a file name.
A typical approach is to implement the Survey::beforeSave() callback and add the necessary code to move the uploaded file from its temporary location to the destination folder of your choice.
You then overwrite the $data['Survey']['banner_image'] array with $data['Survey']['banner_image']['name'].
Or, instead of reinventing the wheel, you can use one of the multiple CakePHP plugins which handles uploads, for example josegonzalez/cakephp-upload.
For further reference, see:
FormHelper::file(string $fieldName, array $options)

Related

codeigniter form validation on array not form submit

i want validate my form input field or you want to say i have an array and i want to validate that array using codeigniter
Example :
i have array like :
$array['obj_type']='sample';
$array['obj_id']='44';
$array['user_id']='34566';
and my form validation config as like :
'validatedata' => array(
array(
'field' => 'obj_type',
'label' => 'No Type Define here',
'rules' => 'required'
),
array(
'field' => 'obj_id',
'label' => 'No any item selected here',
'rules' => 'required|is_natural_no_zero'
),
array(
'field' => 'user_id',
'label' => 'No user logged in',
'rules' => 'required|is_natural_no_zero'
),
),
and when i use form validate its not validate array
if ($this->form_validation->run('validatedata')) {
} else {
echo validation_errors();
}
its print all error which define on on validatedata config array;
i just use
$this->form_validation->set_data($array);
then i validate form
if ($this->form_validation->run('validatedata')) {
echo "sucess";
} else {
echo validation_errors();
}
now its works fine and good.
You have to load form validation library in your controller..
$this->load->library(array('form_validation'));
You have to provide the data to the form_validation library:
$this->form_validation->set_data($array);
and then you can use
$this->form_validation->run('validatedata')
as intended.
If you want to validate multiple arrays, you'll have to call reset_validation() after validating each array.
Check system/libraries/Form_validation.php (around line 255, depending on your version of CI) for more information.

CakePHP 2.4: Unwanted pre-filled form data

I have a form to add a new user. Only an admin who is logged in may access this form. Unfortunately, the username and the password of the admin are filled into the form fields which are expected to be completely clear. And one really strange thing is: The username is printed into the birthday field!
I really cannot explain myself how it works. And I could not found in the WWW any post from a person who has got the same problem - I only found questions and answers about pre-filled form data that is wanted.
This is the View /Users/add.ctp
<h1>Add a new Member</h1>
<?php echo $this->Form->create('User', array('url' => BASE_URL.'/users/add', 'action'=>'post')); ?>
<table class="form">
<tr><td>Username:</td><td><?php echo $this->Form->input('User.username', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Name:</td><td><?php echo $this->Form->input('User.name', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Lastname:</td><td><?php echo $this->Form->input('User.lastname', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>E-Mail:</td><td><?php echo $this->Form->input('User.email', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Birthday:</td><td><?php echo $this->Form->input('User.birth', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Password:</td><td><?php echo $this->Form->input('User.password', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
</table>
<?php
echo $this->Form->submit('Submit', array('formnovalidate' => true));
echo $this->Form->end();
?>
And here is the Controller /UsersController.php
public function add() {
$this->layout = 'admin';
if ($this->request->is('post')) {
// Saving the data
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Data saved.'));
return $this->redirect(array('action' => 'view'));
}
$this->Session->setFlash(__('Data could not be saved.'));
}
}
By the way: Saving works fine.
Of course, the admin is of Object User, as is the new member to be added. I think, here lies the problem, but I really do not know... I am thinking about this problem the whole day :( Does anybody know what to do?
Thanks in advance.
Is not your browser? (saved username/password when you type for the first time)
So, you can turn of the autocomplete.
<?php echo $this->Form->create('User', array('url' => BASE_URL.'/users/add', 'action'=>'post', 'autocomplete' => 'off')); ?>
This option => 'autocomplete' => 'off'
Check your $this->data.
CakePHP autocompletes forms with data found there because it guesses that is data already submitted by the user.
In you example, if you have some value in $this->data['User']['birth'] it should show that value in the Birthday input.

CakePHP validation not detecting form field

I have a form where users can upload images, and I'm printing it to the page like so:
<?php echo $this->Form->label('file', 'Image file', array('class' => 'col-lg-1 control-label')); ?>
Then, in the model I'm setting up validation like so:
public $validate = array(
'file' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must select an image to upload'
),
'extension' => array(
'rule' => array('extension', array('png')),
'message' => 'Images must be in PNG format'
),
'size' => array(
'rule' => array('fileSize', '<', '1MB'),
'message' => 'Images must be no larger than 1MB'
),
'goodUpload' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the upload, please try again'
)
)
);
However, Cake doesn't seem to be associating the form field with the validation rule, as if I select an image to upload I always get "You must select an image to upload" as a form error. I've made sure the form has enctype="multipart/form-data".
Is this happening because file isn't a database field? How can I make cake run some validation on file?
Edit: Here's my entire form, as requested: http://pastebin.com/SbSbtDP9
You can validate fields that are not in the database, long as you have the correct field name in the correct model.
From what I can see in your code it seems your outputting a label instead of an actual input, for the image upload I would try
echo $this->Form->create('Model', array('type'=>'file'));
echo $this->Form->input('file', array('type'=>'file'));
echo $this->Form->submit('Upload Image'):
echo $this->Form->end();
For the validation I would try something like with the rest of your validate options (size, etc...) CakePHP usually throws an error on notEmpty on File Uploads. So just checking for the extension type is usually good enough.
public $validate = array(
'file' => array(
'rule' => array(
'extension', array('jpeg', 'jpg')
'message' => 'You must supply a file.'
)
)
);
Majority of time in CakePHP for Image Uploading I resort to a plugin such as https://github.com/josegonzalez/cakephp-upload it does validation and upload handling all in one.
Managed to figure it out. Turns out having the notEmpty validation on a file fieldnever works, it always thinks there's nothing there and so always throws that validation message.
Worked around it by writing my own validation method.

CakePHP validation for file upload

I'm trying to perform validation with cake 2.3.8 on a file upload to make sure that only PDF's can be uploaded. I'm loosly basing this off of this tutorial.
My form is displaying the asterisk next to the input, and when I remove the validation from my model the asterisk goes away. I'm assuming this means it "sees" the input for validation, but I just can't figure out why even the custom validation isn't being triggered.
Here's the form
echo $this->Form->create('Upload', array('type' => 'file'));
echo $this->Form->input('file_upload', array('type' => 'file'));
echo $this->Form->input('file_title');
echo $this->Form->end(__('Upload File!', true));
Here's the code in my Upload model
public function checkUpload(){
echo "test"; //check to see if it reaches this...not displaying
return false; //the error message should be set just for testing, it's not displaying though
}
public $validate = array(
'file_upload' => array(
'extension' => array(
'rule' => array('extension', array('pdf')),
'message' => 'Only pdf files',
),
'upload-file' => array(
'rule' => array('checkUpload'),
'message' => 'Error uploading file'
)
)
);
Here is my answer (albeit for cakephp 1.3):
In your model add the following validation to your $validate variable.
$this->validate = array(...
// PDF File
'pdf_file' => array(
'extension' => array(
'rule' => array('extension', array('pdf')),
'message' => 'Only pdf files',
),
'upload-file' => array(
'rule' => array('uploadFile'), // Is a function below
'message' => 'Error uploading file'
)
)
); // End $validate
/**
* Used when validating a file upload in CakePHP
*
* #param Array $check Passed from $validate to this function containing our filename
* #return boolean True or False is passed or failed validation
*/
public function uploadFile($check)
{
// Shift the array to easily acces $_POST
$uploadData = array_shift($check);
// Basic checks
if ($uploadData['size'] == 0 || $uploadData['error'] !== 0)
{
return false;
}
// Upload folder and path
$uploadFolder = 'files'. DS .'charitylogos';
$fileName = time() . '.pdf';
$uploadPath = $uploadFolder . DS . $fileName;
// Make the dir if does not exist
if(!file_exists($uploadFolder)){ mkdir($uploadFolder); }
// Finally move from tmp to final location
if (move_uploaded_file($uploadData['tmp_name'], $uploadPath))
{
$this->set('logo', $fileName);
return true;
}
// Return false by default, should return true on success
return false;
}
You may have to display the error validation messages yourself, you can do this using:
<!-- The classes are for twitter bootstrap 3 - replace with your own -->
<?= $form->error('pdf_file', null, array('class' => 'text-danger help-block'));?>
if you try to debug sth in Cake, always use debug(sth) // sth could be variable could be string could be anything, cuz in Cake debug means
echo "<pre>";
print_r(sth);
echo "</pre>";`
it's already formatted very well.
then after that you have to put die() otherwise after echo sth it will load the view that's why you can't see it even there was an output.

How to insert multiple records

I am a new cake php developer.I am trying to insert multiple record but i cant.My table Structure is given below:
Table Name :
agents
==============================================
id | Contact | Name | email_add | Address
==============================================
Controller Code :
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if(empty($this->data) == false)
{
if($this->Agent->save($this->data))
{
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
}
else
{
$this->set('errors', $this->Agent->invalidFields());
}
}
Model Code Is :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Agent extends AppModel
{
public $name='Agent';
public $usetables='agents';
public $validate = array(
'contact' => array(
'contact_not_empty' => array(
'rule' => 'notEmpty',
'message' => 'Please Give Contact No',
'last' => true
),
),
'name' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
Its not possible to insert records with this code.What should I do?
Let me explain everything.
First of all your html form must be looks like following.
<?php echo $this->Form->create('User'); ?>
<tr>
<td>
<?php
echo $this->Form->input('User.0.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.1.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.2.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
</td>
<td>
<input type="submit" value="Add" >
</td>
</tr>
<?php echo $this->Form->end(); ?>
As you can see to save many record at same time using cakephp you must define it as above it will parse input fields as array this is cakephp convention.
I mean User.0.address for first array element
User.1.address for second array element
User.2.address for third array element and so on.
Now.
In Controller file.
<?php
function add()
{
$this->User->saveAll($this->data['User']);
}
And yes here you are done saving multiple record at same time.
I just gave you how cakephp works all you need to do is set above hint as per your need.
Best of luck...
Cheers...
Feel Free to ask... :)
Try this saveall() in your query except save, hope this helps
if($this->Agent->saveall($this->data))
Let me know if it work.
I think this
php echo $this->Form->create('Agents', array('action' => 'send_money'));?>
should be replaced with
php echo $this->Form->create('Agent', array('action' => 'send_money'));?>
and use saveall() in place of save.

Categories