tags:

views:

23

answers:

1

In cakephp I am trying to check if an file input field has a file attached, and if not output an error. I have done this with other fields but just can't seem to get this to work on that field.

Here is the model

array('notempty'), 'uploadeduploaded_file' => array('notempty') ); ?>

and here is my ctp file

<?php echo $form->input('Uploaded.uploaded_file', array('type' => 'file', 'label' => 'Upload file', "label" => false)); ?>

I am guessing that it must be something to do with what I should call the field in the model, but I have tried all sorts of combinations and can't get it work.

Any help would be grateful

A: 

http://stackoverflow.com/questions/3146933/cakephp-optional-validation-for-file-upload

this may help u

or

var $validate = array(
            'imageupload' => array(
                'checksizeedit' => array(
                    'rule' => array('checkSize',false),
                    'message' => 'Invalid File size',

                ),
                'checktypeedit' =>array(
                    'rule' => array('checkType',false),
                    'message' => 'Invalid File type',

                ),
                'checkuploadedit' =>array(
                    'rule' => array('checkUpload', false),
                    'message' => 'Invalid file',

                ),
);



function checkUpload($data, $required = false){
        $data = array_shift($data);
        if(!$required && $data['error'] == 4){
            return true;
        }
        //debug($data);
        if($required && $data['error'] !== 0){
            return false;
        }
        if($data['size'] == 0){
            return false;
        }
        return true;

        //if($required and $data)
    }

    function checkType($data, $required = false){
        $data = array_shift($data);
        if(!$required && $data['error'] == 4){
            return true;
        }
        $allowedMime = array('image/gif','image/jpeg','image/pjpeg','image/png');
        if(!in_array($data['type'], $allowedMime)){
            return false;
        }
        return true;
    }

    function checkSize($data, $required = false){
        $data = array_shift($data);
        if(!$required && $data['error'] == 4){
            return true;
        }
        if($data['size'] == 0||$data['size']/1024 > 2050){
            return false;
        }
        return true;
    }
RSK