Link to home
Create AccountLog in
Avatar of error77
error77

asked on

Cakephp Validation not working

Hi all,

I have added some validation to my model but it just won't work. I wonder what might be going wrong. No messages are shown either.

Code is below attached:

Hope someone can help

THanks

//Model Code

<?php
class Upload extends AppModel {
var $name = 'Upload';
var $useTable = 'entries';

var $validate = array(
        'name' => array(
            'rule' => 'alphaNumericDashUnderscore',
            'allowEmpty' => false,
            'message' => 'Only letters, numbers, dash and underscore'
        ),
        'upload' => array(
            'rule' => array('extension',array('jpg','gif','jpeg','tif','png','mov','mp4','flv','swf')),
            'required' => true,
            'allowEmpty' => false,
            'message' => 'Invalid file'
        ),
		'file' => array(
		'rule' => array('validateFile', true),
		'allowEmpty' => false,
		'message' => 'There is a problem with uploading the file.' //message
)
		
       );



function validateFile($data, $required = false) {
$file = array_shift($data); // for easier handling

if ($required && $file['size'] == 0) {
	
	echo 'This file is invalid or empty!';
	
}
 // If no file is uploaded
if ($file['error'] !== 0) return false; // PHP Errors 
if ($upload_info[‘error’] !== 0) {	return false; }
return is_uploaded_file($file['tmp_name']); // If everything is fine

}
}
?>

//controller code

<?php
class UploadsController extends AppController {
	
	var $name = 'Uploads';
	var $useTable = 'competitions_entry';
	var $components = array('RequestHandler','FileUpload','Session');  
	var $helpers = array('Html', 'Form', 'Javascript','Session', 'Ajax');
	var $uses = array('User','Competition','Upload', 'Vote');
	
		
	
	
	
	function index($id = null) {
		

		
		//$this->set('uploads', $this->Upload->find('all')); 
		
		$theuploads = $this->Upload->query("SELECT * FROM entries");
										   
		$this->set('uploads', $theuploads);
		
			
		if($this->RequestHandler->isPost()) {
		
		
		
		$this->Upload->create();
		
			$component = new FileUploadComponent();
			$component->upload(array('name'=>'blablabla', 'tmp_name'=>'tmp_blabla'));
			$FullUrl = $component->getFullpath();
			$currentUserId = $this->sodium_user['User']['id'];
			$test = $component->getFolder();
			
		
				
		
		   
			//Get the path to save;
			$data = array('Upload' => array(
					'competition_id' => $this->data['Upload']['comp_id'],
					'user_id' => $currentUserId,// <- Need to get this via url
			 		'directory_name'=> 'img/uploads/',
					'name' => $test.'-'.$this->data['Upload'][0]['file']['name'],
					'size' => $this->data['Upload'][0]['file']['size'], 
					'type' => $this->data['Upload'][0]['file']['type']
				)
			);
		
		
		//Check if empty file
		if ($this->data['Upload'][0]['file']['size'] == 0)  {
			//$this->redirect('http://www.error.com/');
			echo '<div style="margin:10px 0">';
			echo 'The file is empty. Please try again';
			echo '</div>';
			
    

			
			
			

		}
		
		

		
		if($this->Upload->save($data, array('validate'=>true))) { // validate now
		
		

		if(!$this->FileUpload->upload($this->data['Upload'][0]['file'])) {
		
		
		
		$this->Upload->delete($this->Upload->id); // remove the DB entry because there were upload errors
		$this->redirect('/'); //Redirect after saving
		}
		}
		
		}
		}
		
} 
?>

//view code
<?php

echo $form->create('Upload',array('name'=>'form1','type'=>'file', 'url' => 'uploads','class'=>'form')); 
echo $form->input('0.file',array('type'=>'file','label'=>'File Upload:'));
echo $form->input('comp_id', array('type'=>'hidden', 'value'=>$competitionid));
echo '<div style="padding:10px;">&nbsp;</div>';
echo '<label><input type="checkbox" id="enableSubmit" onclick="enableSubmitBtn(this.checked);">';
echo '<a href="'.$this->webroot.'tac" rel="shadowbox;width=890px" style="font-size:100%; text-decoration:none; margin-left:10px;">I agree to the terms and conditions.</a>';
echo '</label>';
													
													
echo '<span class="hide" name="mySubmit" id="mySubmit">';
echo $form->end('Submit');
echo '</span>';

?>

//and finally here is the component

//component code
<?php

class FileUploadComponent extends Object {
      var $components = array('RequestHandler');
	  

  
      protected $folder;
      protected $destination;
	  protected $fullpath;
      
      function upload($data) {            
            
            if(!is_dir($this->fullpath)) 
        { 
			
			$this->folder = date('Y-m-d_H-i-s');
            $tempdest  = 'img/uploads/';
          
            $this->fullpath = $tempdest;
			
			$this->destination = $this->fullpath.'/'.$this->folder.'-'.$data['name'];
			
            if(move_uploaded_file($data['tmp_name'], $this->destination)) {
                  
                  return true;
            }  
            return false;
      }
  }

           

  public function getDestination() {
    return $this->destination;
  }

  public function getFolder() {
    return $this->folder;
  }
  
    public function getFullpath() {
    return $this->fullpath;
  }
}



?>

Open in new window

Avatar of Codebot
Codebot

Hello,

where's the Initialization of the $upload_info array? and what's its values?
Avatar of error77

ASKER

Codebot : Seen that link but still couldn't get mine to work :o/


Prograministrator: Is it the DB structue you are after?

If so... please see attached below

thanks



CREATE TABLE IF NOT EXISTS `entries` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `competition_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `directory_name` varchar(255) NOT NULL,
  `type` varchar(50) NOT NULL,
  `size` varchar(50) NOT NULL,
  `created` datetime NOT NULL,
  `finalist` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;

Open in new window

No, I meant this :

function validateFile($data, $required = false) {
$file = array_shift($data); // for easier handling

if ($required && $file['size'] == 0) {
	
	echo 'This file is invalid or empty!';
	
}
 // If no file is uploaded
if ($file['error'] !== 0) return false; // PHP Errors 
if ($upload_info[‘error’] !== 0) {	return false; }
return is_uploaded_file($file['tmp_name']); // If everything is fine

}

Open in new window


this row :
if ($upload_info[‘error’] !== 0) {	return false; }

Open in new window


$upload_info not Initialized, so this condition always return false.
Avatar of error77

ASKER

OK I've changed it to true but still when I submit an empty upload ... in other words...submit no file it doesn't stop me.

Only this code from the controller gives a message:

//Check if empty file
            if ($this->data['Upload'][0]['file']['size'] == 0)  {
                  echo '<div style="margin:10px 0">';
                  echo 'The file is empty. Please try again';
                  echo '</div>';
                  
but the above shouldn't be needed right?
   

                  
                  
                  
Avatar of error77

ASKER

Any ideas please?
OK, have you tried submitting file what does it returned?

And what do you want to return if there isn't a file submitted?
Avatar of error77

ASKER

Basically there are 2 main things I need it Niot to do.

1. Not let me upload nothing
2. Not let me upload invalid extensions..

 'rule' => array('extension',array('jpg','gif','jpeg','tif','png','mov','mp4','flv','swf')),

Know what I mean?
What's the name of the file field that shown in browser?

Maybe that, this validation not applied on it's name correctly.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of error77

ASKER

Sorry that didn'ty work...code errors
As nearly as I can recall, "didn't work code errors" is not in the lexicon of error messages.  If we are to have any hope of helping you with anything other than abstract and theoretical answers, we need to see the code, the data and the error messages.  It needs to be complete.  So please post those things here, thanks.
Avatar of error77

ASKER

fixed. Thanks