CakePHP-One视图到另一个视图按钮单击功能

时间:2016-06-22 05:15:45

标签: cakephp file-upload

我正在使用CakePHP MVC。我在View / Elements中创建了两个ctp模板。在一个ctp文件中我添加了一个按钮点击功能。在另一个ctp文件中,我已经在按钮单击时将文件的上传功能添加到数据库。所以现在我需要帮助如何从其他ctp文件传递文件上传的按钮单击功能。

希望你们能帮忙。

1 个答案:

答案 0 :(得分:0)

您应该避免在模板中保留任何逻辑。 看看下面的例子:

class Photo extends AppModel {

    public $validate = array(
        'post_id' => array(
            'numeric' => array(
                'rule' => array('numeric')
            ),
        ),
        'img_alt' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty')
            ),
        ),
        'rating' => array(
            'numeric' => array(
                'rule' => array('numeric')
            ),
        ),
        'other' => array(
            'boolean' => array(
                'rule' => array('boolean')
            ),
        ),
        'img_url' => array(
            'uploadError' => array(
                'rule' => 'uploadError',
                'message' => 'Something went wrong with the file upload',
                'required' => FALSE,
                'on' => 'create'
            ),
            // custom callback to deal with the file upload
            'processUpload' => array(
                'rule' => 'processUpload',
                'message' => 'Something went wrong processing your file',
                'required' => FALSE,
                'last' => TRUE,
                'on' => 'create'
            ),
        ),
    );

    public function processUpload($check=array()) {
        if (!empty($check['img_url']['tmp_name'])) {
            if (!is_uploaded_file($check['img_url']['tmp_name'])) {
                return FALSE;
            }

            // build full filename 
            $filename = WWW_ROOT . $this->uploadDir . DS . $this->data['Photo']['post_id'] . DS . Inflector::slug(pathinfo($check['img_url']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['img_url']['name'], PATHINFO_EXTENSION);

            // try moving file
            if (!move_uploaded_file($check['img_url']['tmp_name'], $filename)) {
                return FALSE;

            // file successfully uploaded
            } else {
                $filename = WWW_ROOT . Inflector::slug(pathinfo($check['img_url']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['img_url']['name'], PATHINFO_EXTENSION);
                // save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
                $this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename) );
            }
        }
        return TRUE;
    }

}