Solved

Cakephp code driving me crazy (cannot get it to work)

Posted on 2010-08-31
22
423 Views
Last Modified: 2013-11-10
Hi all,
I'm coming back here as my last resort before throwing the towel.
I am following this tutorial:
http://blog.optiss.si/cakephp-simple-upload-tutorial

I tried it first on cakephp version: 1.3 and it works fine.

Now, I need (please don't ask me to upgrade), to do the same thing on version 1.2

I just cannot get it to work :o(

The errors are:

Notice (8): Undefined index:  Upload [APP/controllers/uploads_controller.php, line 13]

Code

        //$this->set('uploads', $this->Upload->find('all'));

        if($this->RequestHandler->isPost()) {

        $this->Upload->saveAll($this->data['Upload'], array('validate'=>'only')); // validation

UploadsController::index() - APP/controllers/uploads_controller.php, line 13
Object::dispatchMethod() - APP/cake/libs/object.php, line 116
Dispatcher::_invoke() - APP/cake/dispatcher.php, line 227
Dispatcher::dispatch() - APP/cake/dispatcher.php, line 194
[main] - APP/webroot/index.php, line 89

Notice (8): Undefined index:  Upload [APP/controllers/uploads_controller.php, line 15]

Code

        $this->Upload->saveAll($this->data['Upload'], array('validate'=>'only')); // validation



        foreach($this->data['Upload'] as $number => $file) {

UploadsController::index() - APP/controllers/uploads_controller.php, line 15
Object::dispatchMethod() - APP/cake/libs/object.php, line 116
Dispatcher::_invoke() - APP/cake/dispatcher.php, line 227
Dispatcher::dispatch() - APP/cake/dispatcher.php, line 194
[main] - APP/webroot/index.php, line 89

Warning (2): Invalid argument supplied for foreach() [APP/controllers/uploads_controller.php, line 15]

It's got problems with:

$this->Upload->saveAll($this->data['Upload'], array('validate'=>'only')); // validation

and

foreach($this->data['Upload'] as $number => $file) {

It does not know "Upload" but there IS a model called Upload.php and upload.php too (just in case)

I just don't know what to do next.

Can someone help me please?

Thanks










0
Comment
Question by:error77
  • 15
  • 7
22 Comments
 

Author Comment

by:error77
Comment Utility
I'll like to add that the table it connects to is not called 'uploads' as expected.
I am using useTable 'nameTable'; in this case.

0
 
LVL 40

Expert Comment

by:RQuadling
Comment Utility
Can you add just before the foreach ...

var_dump($this->data);
die();


Just temporarily. This way you can see exactly what is contained in $this->data.

If you have a dummy site to work on, then good.

If not ...

file_put_contents('./data.txt', var_export($this->data, true));

should do the trick as long as PHP has write access to the current directory. If not, change the directory.

If still no, then mail()...

Basically, if you've followed the steps and it works on a new version, but you are using an old version, it simply may be not backward compatible.

But hopefully we can get you there ...


0
 
LVL 40

Expert Comment

by:RQuadling
Comment Utility
Also, can you completely reset the code to the example. If you've edited it, I don't know what you've changed or what lines things are on.

Get it working (and by the looks of it, it is a simple cut and paste).

Worry about changing the name once you've got things working.
0
 

Author Comment

by:error77
Comment Utility
OK added the var dump and this was returned:

Notice (8): Undefined index:  Upload [APP/controllers/uploads_controller.php, line 13]

Code

        //$this->set('uploads', $this->Upload->find('all'));

        if($this->RequestHandler->isPost()) {

        $this->Upload->saveAll($this->data['Upload'], array('validate'=>'only')); // validation

UploadsController::index() - APP/controllers/uploads_controller.php, line 13
Object::dispatchMethod() - APP/cake/libs/object.php, line 116
Dispatcher::_invoke() - APP/cake/dispatcher.php, line 227
Dispatcher::dispatch() - APP/cake/dispatcher.php, line 194
[main] - APP/webroot/index.php, line 89

array
  'file' =>
    array
      'name' => string 'test.JPG' (length=28)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/tmp/phpAK6H0u' (length=14)
      'error' => int 0
      'size' => int 168517

And about changing the code. It's all as in the link.

Also, where do I put this code?
file_put_contents('./data.txt', var_export($this->data, true));

thanks


0
 

Author Comment

by:error77
Comment Utility
Also, this is the form code it's rendering: (in case it helps)
<form id="UploadAddForm" enctype="multipart/form-data" method="post" action="/website/en/Array">
<fieldset style="display:none;">
<input type="hidden" name="_method" value="POST" />
</fieldset>
<div class="input file">
<label for="Upload0File">Image Upload</label>
<input type="file" name="data[Upload][0][file]" value="" id="Upload0File" />
</div>
<div class="submit">
<input type="submit" value="Submit" />
</div>
</form>

0
 

Author Comment

by:error77
Comment Utility
This line in the view:

echo $form->create('Upload',array('type'=>'file'));

is not creating the action url properly? It's adding action="/website/en/Array" instead of the path to the file.
0
 

Author Comment

by:error77
Comment Utility
I've added: file_put_contents('./data.txt', var_export($this->data, true)); above the foreach line but didn't write any file but no errors either
0
 
LVL 40

Expert Comment

by:RQuadling
Comment Utility
That LOOKS like it should be ...

echo $form->create('Upload', array('name'=>'upload'));

But that doesn't seem right either.



Can you for the sake of testing, please revert ALL changes to the original code. No matter how trivial or inappropriate it may be.

Please.

Just cut and paste the code from the site.

I've posted a question regarding compatibility ... if it is NOT 1.2 compatible, and the author isn't prepared to make it so ... well, I suppose that is why you are here.

0
 

Author Comment

by:error77
Comment Utility
OK Here is all the code:

/*************************************************************/
/ The Component
/************************************************************/
<?php
class FileUploadComponent extends Object {
      var $components = array('RequestHandler');
      function upload($data) {
      $destination = 'img/uploads/'.$data['name']; // Create uploads folder and set proper permissions!
      if(move_uploaded_file($data['tmp_name'], $destination)) {
      return true;
      }
      return false;
      }
}
?>

/*******************************************************************/
/   The Model
/******************************************************************/
<?php
class Upload extends AppModel {
var $name = 'Upload';
var $useTable = 'table2';
var $validate = array(
'file' => array(
'rule' => array('validateFile', false),
'message' => 'File not OK.' // apply your own
)
);
function validateFile($data, $required = false) {
$file = array_shift($data); // for easier handling
if ($required && $file['size'] == 0) return false; // If no file is uploaded
if ($file['error'] !== 0) return false; // PHP Errors (see http://www.php.net/manual/en/features.file-upload.errors.php for more)
return is_uploaded_file($file['tmp_name']); // If everything is fine
}
}
?>

/***********************************************************************/
/ The Controller
/**********************************************************************/
<?php
class UploadsController extends AppController {
      
      var $name = 'Uploads';
      var $useTable = 'table2';
      var $components = array('RequestHandler','FileUpload');
      var $helpers = array('Html', 'Form', 'Javascript');
      
            
      function index() {
            //$this->set('uploads', $this->Upload->find('all'));
            if($this->RequestHandler->isPost()) {
            $this->Upload->saveAll($this->data['Upload'], array('validate'=>'only')); // validation
            
              //file_put_contents('./data.txt', var_export($this->data, true));
           //var_dump($this->data);
          //      die();

            foreach($this->data['Upload'] as $number => $file) {
            if($file['file']['error'] != 0) continue; //do not save when PHP errors occur

            $this->Upload->create();
            if($this->Upload->save($file['file'],array('validate'=>false))) { // no need to validate now
            if(!$this->FileUpload->upload($file['file'])) {
            $this->Upload->delete($this->Upload->id); // remove the DB entry because there were upload errors
            }
            }
            }
            }
            }
            

            
            
            
} //end controller
?>

/*************************************************************/
/   And finally the View
/***********************************************************/

<h1>Image Upload</h1>


<?php
      
      echo $form->create('Upload',array('type'=>'file'));
      echo $form->input('0.file',array('type'=>'file','label'=>'Image Upload'));
      echo $form->end('Submit');

?>

/***********************************************************************************************/

That's all the code.

Hope it helps





0
 

Author Comment

by:error77
Comment Utility
Can you spot anything?
0
 

Author Comment

by:error77
Comment Utility
I don't know if this is important but I inserted the var_dump before the foreach and it doesn't reach it .. it breaks before it reaches it.

The only was to make it reach it is to hardcode the form action in the view

For example: <form id="UploadIndexForm" enctype="multipart/form-data" method="post" action="/website/uploads" accept-charset="utf-8">

The orginal code: echo $form->create('Upload',array('type'=>'file'));  produces a wrong action url .. as it adds /Array to the action url.

Hope this helps.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 40

Expert Comment

by:RQuadling
Comment Utility
If you use the original code from the site what happens?
0
 

Author Comment

by:error77
Comment Utility
It doesn't work on this version. It's almost original. My code is at least getting nearer.

Update: I've updated the view to this:



<h1>Image Upload</h1>
<form id="UploadIndexForm" enctype="multipart/form-data" method="post" action="<?php echo $this->webroot; ?>uploads" accept-charset="utf-8">

<?php
      
      //echo $form->create('Upload',array('type'=>'file')); //OFF
      echo $form->input('0.file',array('type'=>'file','label'=>'Image Upload'));
      echo $form->end('Submit');
?>

And the var_dump is returning:

Notice (8): Undefined index:  Upload [APP/controllers/uploads_controller.php, line 13]

Code

        //$this->set('uploads', $this->Upload->find('all'));

        if($this->RequestHandler->isPost()) {

        $this->Upload->saveAll($this->data['Upload'], array('validate'=>'only')); // validation

UploadsController::index() - APP/controllers/uploads_controller.php, line 13
Object::dispatchMethod() - APP/cake/libs/object.php, line 116
Dispatcher::_invoke() - APP/cake/dispatcher.php, line 227
Dispatcher::dispatch() - APP/cake/dispatcher.php, line 194
[main] - APP/webroot/index.php, line 89

array
  'file' =>
    array
      'name' => string 'm_33077e924ef743748492c4d39a5cb52f.jpg' (length=38)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/tmp/phpfmchiK' (length=14)
      'error' => int 0
      'size' => int 6618

So, it's collecting all the data ... it's just not writting to the DB.

Could it be that Upload this error:
Notice (8): Undefined index:  Upload [APP/controllers/uploads_controller.php

is stopping the process from being final?


   
0
 
LVL 40

Accepted Solution

by:
RQuadling earned 500 total points
Comment Utility
33577603 is very important.

This tells me that there must be a significant change in the form create method.

What type of object is $form? I need to see what it looks like in 1.2 vs 1.3

At a guess ...

http://api12.cakephp.org/class/form-helper#method-FormHelpercreate
vs
http://api13.cakephp.org/class/form-helper#method-FormHelpercreate

shows that there is an option for URL which is missing. That is if I am reading it correctly.

But why you get the value of Array() is odd. Null, or nothing, yes, I'd get that.

Can you create a really really simple form. Forget everything else to do with the uploads, just a simple form with 1 button. Would you supply the URL in the create() options?

Can you add ...

'url' => '/website/uploads',

(or whatever the value is supposed to be)

to the options in $form->create().
0
 

Author Comment

by:error77
Comment Utility
OK the action is now correct in the generated form.

I changed the $form->create line to this:

echo $form->create('Upload',array('type'=>'file', 'url' => 'uploads'));

So that part's now fixed.

Issue now is that the var_dump in now displaying this:

array
  'Upload' =>
    array
      0 =>
        array
          'file' =>
            array
              ...


It's Empty.

0
 

Author Comment

by:error77
Comment Utility
Forget what I said before.

It was empty because the var_dump was stopping it.

You Did it!!!! :o)  

You're a genious!!!! THANK YOU!!!!!!

It's now working :o)

0
 

Author Comment

by:error77
Comment Utility
Where is the Assign Points button gone???
0
 
LVL 40

Expert Comment

by:RQuadling
Comment Utility
"Accept as solution" ?
0
 

Author Comment

by:error77
Comment Utility
Yes...where is the buttons gone?
0
 
LVL 40

Expert Comment

by:RQuadling
Comment Utility
I don't know. What buttons can you see? I see 6 links per question.

Author
Was this comment useful : Yes
Was this comment useful : No
Admin Edit
Accept Multiple Solutions
Accept as Solution
0
 

Author Closing Comment

by:error77
Comment Utility
Thank you VERY MUCH :o)
0
 

Author Comment

by:error77
Comment Utility
OK Done. Had to login using Chrome and Firefox is having display issues here :o/

Thanks very much for all your help! :o)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now