Multiple File Upload CakePHP not work correctly - cakephp

since yesterday i try to implement multiple file upload in my project, the database get's updated with the new filenames, but the files were not uploaded (to localhost).
So my view looks like this now:
<?php echo $this->Form->create('Upload', array('type' => 'file')); ?>
<fieldset>
<br/>
<?php echo $this->Form->input('files.', array('type' => 'file', 'multiple' => 'multiple', 'label' => '')); ?>
</fieldset>
<?php echo $this->Form->end(__('upload'));?>`
I added in my controller foreach():
$files = $this->request->data['Upload']['files'];
$counter = 0;
foreach ($files as $row) {
$counter += 1;
$uploads = $this->Upload->find('all');
$exists=false;
foreach ($uploads as $upl) {
if (strcmp($upl['Upload']['name'], $row['name'])==0)
$exists=true;
}
print_r($exists);
if ($exists) {
continue;
} else {
$this->Upload->create();
$this->Upload->set('name', $row['name']);
$this->Upload->set('type', $row['type']);
$this->Upload->set('size', $row['size']);
$this->Upload->save();
}
}
if($counter > 1) {
$this->Session->setFlash(__('Files uploaded'));
} else if($exists && $counter == 1) {
$this->Session->setFlash(__('File could not be uploaded. File already exists.'));
} else {
$this->Session->setFlash(__('File uploaded'));
}
In my logs it gives me the following errors:
Warning (512): FileUpload: A file was detected, but was unable to be processed due to a misconfiguration of FileUpload. Current config -- fileModel:'Upload' fileVar:'file' [APP/Plugin/file_upload/Controller/Component/FileUploadComponent.php, line 403]
And the other on:
Warning (2): Invalid argument supplied for foreach() [APP/Plugin/file_upload/Controller/Component/FileUploadComponent.php, line 341]
My FileUploadComponent is the following
* #link http://www.webtechnick.com
* #author Nick Baker
* #version 4.0.4
* #license MIT
And line 341 in FileUploadComponent is the following:
function processAllFiles(){
foreach($this->uploadedFiles as $file){
$this->_setCurrentFile($file);
$this->Uploader->file = $this->options['fileModel'] ? $file[$this->options['fileVar']] : $file;
$this->processFile();
}}
Maybe some of you know this problem already and can give me a hint for this?

So i just disabled the FileUploadComponent and inserted
if ($exists) {
continue;
} else {
--> move_uploaded_file($row['tmp_name'], WWW_ROOT . 'files/' . $row['name']);
$this->Upload->create();
$this->Upload->set('name', $row['name']);
$this->Upload->set('type', $row['type']);
$this->Upload->set('size', $row['size']);
$this->Upload->save();
}
Now it works fine :)

Related

CakePHP 3.x call function

I have a view that is add a called help desk opening form (referring to add function, of course), and have this function is to upload that file to attach request, which is connected with a component, but I do not want to Let them in different view, because if I just send a file upload through the view, the image is "lost " and does not turn the call. I need within the add function I can call the upload function, to join views. If I call her by $ this-> upload (); Or simply make all the checking in of add, does not find the component, returning me an error (which I put down ), I believe the conflict is in the request-> data but do not know if there is a way to join the way I explained.
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is(['post', 'put'])) {
$this->Posts->patchEntity($post, $this->request->data);
$post->user_id = $this->Auth->user('id');
if ($this->Posts->save($post)) {
$this->Flash->success(__('send'));
return $this->redirect(['action' => 'listar']);
}
$this->Flash->error(__('not send'));
}
$this->set(compact('post'));
}
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data(['uploadfile']));
return $this->redirect(['action'=>'add']);
}
}
Component:
public function send( $data )
{
if ( !empty( $data) ) {
if ( count( $data) > $this->max_files ) {
throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
}
foreach ($data as $file) {
$filename = $file['name']; //line 32
$file_tmp_name = $file['tmp_name']; //33
$dir = WWW_ROOT.'img'.DS.'Anexos';
$allowed = array('png', 'jpg', 'jpeg');
if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) ) {
throw new InternalErrorException("Error Processing Request.", 1);
}elseif( is_uploaded_file( $file_tmp_name ) ){
$filename = Text::uuid().'-'.$filename;
$filedb = TableRegistry::get('Arquivos');
$entity = $filedb->newEntity();
$entity->filename = $filename;
$filedb->save($entity);
move_uploaded_file($file_tmp_name, $dir.DS.$filename);
}
}
}
}
Error when calling upload();
Warning (2): Illegal string offset 'name' [APP/Controller\Component\UploadComponent.php, line 32]
Warning (2): Illegal string offset 'tmp_name' [APP/Controller\Component\UploadComponent.php, line 33]
view:
<?php
//this is my view add ;
echo $this->Form->input('id' );
echo $this->Form->input('titulo');
echo $this->Form->input('ip');
echo $this->Form->input('mensagem');
?>
//and this is my view upload, I would like to join with add ;
<?php echo $this->Form->create(null, ['type' => 'file']); ?>
<label>Arquivos</label>
<?php
echo $this->Form->file('uploadfile.', ['multiple']);
echo $this->Form->button('Anexar', ['action' => 'submit']);
echo $this->Form->end();
?>
You aren't accessing uploadfile array. This line $this->Upload->send($this->request->data(['uploadfile'])); should be like $this->Upload->send($this->request->data('uploadfile'));.
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data('uploadfile'));
return $this->redirect(['action'=>'add']);
}
}

Array to string Error while uploading an Image

i was trying to upload image using cakephp , i got the following error :
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]
<?php echo $this->Form->create('User',array('type'=>'file'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
anything wrong with what i've did ?
You study cakephp manual properly HOW form type can be File ?????? :)
Use this
<?php echo $this->Form->create('User',array('enctype'=>'multipart/form-data'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
You need to treat the file upload in the controller. If you debug the request you'll see that profile_pic field is an array:
# in controller:
if ($this->request->is('post')) {
debug($this->request->data); die();
}
# result:
array(
'User' => array(
'profile_pic' => array(
'name' => 'wappy500x500.jpg',
'type' => 'image/jpeg',
'tmp_name' => '/tmp/phptk28hE',
'error' => (int) 0,
'size' => (int) 238264
)
)
)
Short answer:
public function upload() {
if ($this->request->is('post')) {
if(isset($this->request->data['User']['profile_pic']['error']) && $this->request->data['User']['profile_pic']['error'] === 0) {
$source = $this->request->data['User']['profile_pic']['tmp_name']; // Source
$dest = ROOT . DS . 'app' . DS . 'webroot' . DS . 'uploads' . DS; // Destination
move_uploaded_file($source, $dest.'your-file-name.jpg'); // Move from source to destination (you need write permissions in that dir)
$this->request->data['User']['profile_pic'] = 'your-file-name.jpg'; // Replace the array with a string in order to save it in the DB
$this->User->create(); // We have a new entry
$this->User->save($this->request->data); // Save the request
$this->Session->setFlash(__('The user has been saved.')); // Send a success flash message
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
Of course you need to make extra validations on the uploaded file.
Further reading: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+cakephp+upload+file

Selecting a default value for a dropdown (key-value array) in cakePHP

Here is the dropdown in a form:
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
The $customers is a key-value array like this:
array(
(int) 2 => 'Best customer',
(int) 5 => 'Good customer',
(int) 9 => 'Customer')
I need one value to be pre selected once the dropdown is created. I have tried to select a default value as the int id and as the customer name but none of them worked.
Here is the controller edit function:
function edit($id = null) {
$this->Project->id=$id;
$this->Project->recursive = 0;
$customers = $this->Customer->find('list', array('conditions'=>array('company_id'=>$this->Auth->user('company_id'))));
$this -> set('customers', $customers);
if(!$this->Project->exists()){
throw new NotFoundException('Invalid project');
}
if($this->request->is('post')|| $this->request->is('put')){
if($this->Project->save($this->request->data)){
$this->Session->setFlash('The project has been edited');
$this->redirect(array('controller'=>'projects', 'action'=>'view', $id));
} else{
$this->Session->setFlash('The project could not be edited. Please, try again');
}
}else{
$this->request->data = $this->Project->read();
$this->request->data['Project']['customer_id'] = 'New customer';
}
}
And here is the edit form:
<?php echo $this->Form->create('Project');?>
<fieldset>
<legend><?php __('Edit Project'); ?></legend>
<?php
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
echo $this->Form->input('name');
echo $this->Form->input('project_nr', array('type'=>'text', 'label'=>'Case number'));
echo $this->Form->input('address');
echo $this->Form->input('post_nr');
echo $this->Form->input('city');
echo $this->Form->input('start_date', array('label'=>'Start Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('finish_date', array('label'=>'End Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('company_id', array('value' => $current_user['company_id'], 'type'=>'text', 'type'=>'hidden'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
The best approach is to leverage the controller for this
if ($this->request->is('post')) {
$this->Model->create();
if ($this->Model->save($this->request->data)) {
...
} else {
...
}
} else {
/* Now here you can put your default values */
$this->request->data['Model']['field'] = ...;
}
For details see http://www.dereuromark.de/2010/06/23/working-with-forms/

Cakephp2.3 html->url in custom function

I am using Cakephp2.0 i created a custom function
<?php echo GenerateNavHTML($navarray); ?>
<?php
function GenerateNavHTML($nav)
{
if(!empty($nav)) {
if(isset($nav[0]['parent'])) {
$parentid=$nav[0]['parent'];
}else{
$parentid=1;
}
if($parentid==0) {
$html = '<ul style="display: block;" class="nav">';
}else {
$html='<ul>';
}
foreach($nav as $page) {
$html.='<li>';
$html .= '"'.$this->Html->url('Logout',array('controller'=>'users','action'=>'logout')).'"';
$html .= '</li>';
}
$html.='</ul>';
return $html;
}
}
?>
and it give
Fatal error: Cannot redeclare GenerateNavHTML()
But there is no redeclaration of function.
if i write
<?php
function GenerateNavHTML($nav)
{
if(!empty($nav)) {
if(isset($nav[0]['parent'])) {
$parentid=$nav[0]['parent'];
}else{
$parentid=1;
}
if($parentid==0) {
$html = '<ul style="display: block;" class="nav">';
}else {
$html='<ul>';
}
foreach($nav as $page) {
$html.='<li>';
$html .= '';
$html .= '</li>';
}
$html.='</ul>';
return $html;
}
}
?>
and it is working fine
i want to use cakephp syntax
Thanks
In MVC, this code should be part of a Helper, not just a standalone 'function'.
Creating your own Helper
This may sound hard, but it really isn't. It has many advantages as well; by moving your code to a Helper, it's easier to re-use and maintain.
For example;
Create a 'Navigation' helper (of course, give it a logical name);
app/View/Helper/NavigationHelper.php
class NavigationHelper extends AppHelper
{
/**
* Other helpers used by *this* helper
*
* #var array
*/
public $helpers = array(
'Html',
);
/**
* NOTE: In general, convention is to have
* functions/methods start with a lowercase
* only *Classes* should start with a capital
*
* #param array $nav
*
* #return string
*/
public function generateNavHTML($nav)
{
$html = '';
if (!empty($nav)) {
if (isset($nav[0]['parent'])) {
$parentid = $nav[0]['parent'];
} else {
$parentid = 1;
}
if ($parentid == 0) {
$html = '<ul style="display: block;" class="nav">';
} else {
$html = '<ul>';
}
foreach ($nav as $page) {
$html .= '<li>';
$html .= '"' . $this->Html->url('Logout', array('controller' => 'users', 'action' => 'logout')) . '"';
$html .= '</li>';
}
$html .= '</ul>';
}
// NOTE: moved this 'outside' of the 'if()'
// your function should always return something
return $html;
}
/**
* You can add other methods as well
* For example, a 'Convenience' method to create a link to the Homepage
*
* Simply use it like this:
* <code>
* echo $this->Navigation->logoutLink();
* </code>
*/
public function logoutLink()
{
return $this->Html->link(__('Log out'), array(
'controller' => 'users',
'action' => 'logout',
'confirm' => __('Are you sure you want to log out')
));
} }
Once you created that file, you can use it in any view or element;
echo $this->Navigation->generateNavHTML($navarray);
You don't even have to add it to the 'Helpers' array of your controller, because CakePHP 2.3 uses 'autoloading' to do that for you
If you need other functionality (related to 'Navigation'), you can just add a 'method' to the Helper, I added a 'logoutLink()' method just to illustrate this
For more information, read this chapter Creating Helpers
Try this:
<?php echo $this->GenerateNavHTML($navarray); ?>
And declare the function before all for secure

cakephp post data field missing from SQL update statement

Having trouble geting cakephp to update a record.
Controller Code:
public function viewBenefit($id) {
if ($this->request->is('post')) {
$this->set('post', $this->request->data);
$this->Benefit->id = $id;
if ($this->Benefit->save($this->Benefit->data)) {
$myVars['Sucsess'] = TRUE;
$this->Session->setFlash('Updates Saved');
} else {
$myVars['NewID'] = 0;
$myVars['Sucsess'] = False;
$this->Session->setFlash('There was an error.');
}
}
$this->Benefit->recursive = 2;
$this->Benefit->id = $id;
$this->set('benefit', $this->Benefit->read());
}
Relevant View Code:
<?php echo $this->Form->create('Benefit',array('action'=>'edit','url' => '#')); ?>
<?php echo $this->Form->input('id',array('type'=>'hidden')) . "\n"; ?>
<?php echo $this->Form->input('short_description',array('type'=>'textarea')) . "\n"; ?>
<?php echo $this->Form->end(); ?>
NOTE: The Form is sumbitted via JS
POST Data (via debug($post); )
array(
'Benefit' => array(
'id' => '1952e98e-f589-47d4-b458-11a1bd58ba3b',
'short_description' => '<p>This is great sample insurance 321321</p>'
)
)
SQL UPDATE statment:
UPDATE `c16memberdev`.`benefits` SET `modified` = '2012-12-04 10:45:16' WHERE `c16memberdev`.`benefits`.`id` = '1952e98e-f589-47d4-b458-11a1bd58ba3b'
As you can see the field "short_description" does not get added to the SQL statement, and therefore the data not added to the database. Thanks for your help.
Try changing
$this->Benefit->save($this->Benefit->data)
to
$this->Benefit->save($this->request->data)

Resources