douyan2002 2012-09-17 23:35
浏览 40

CakePHP没有从saveMany获取验证消息(从Behavior调用)

So, I have a behavior that supports uploading data to the model from an Excel file. From within this Behavior, I call saveMany, which works fine. However, if the data are invalid, I do not get any errors, only a silent failure (I return a generic error in this case, but I want the details from the validation failure).

I'm sure there's a way to deal with this that I as a CakePHP newbie, do not know. Here's the main function of the behavior (there's a bunch of extra logic here that probably is not germane to the problem, but I'm reluctant to cull in case it turns out to be subtly relevant) :

public function parseExcelFile(Model &$model, $fileInfo, $lookupKeys, $otherData = null, $referencedFields = null) {
    $allowedTypes = array('application/vnd.ms-excel');
    if ((isset($fileInfo['error']) && $fileInfo['error'] == 0) ||
        (!empty( $fileInfo['tmp_name']) && $fileInfo['tmp_name'] != 'none')) {
        // basic pre-checks are done.  Now ask PHP if it's a good file
        if (is_uploaded_file($fileInfo['tmp_name'])) {
            // it's a good uploaded file.  Now check the type
            if (in_array($fileInfo['type'], $allowedTypes)) {

                $data = new Spreadsheet_Excel_Reader($fileInfo['tmp_name']);

                // Check text of header row to be sure that it hasn't been changed (equal to db field name)
                $numAltered = 0;
                $numAdded = 0;
                $schema = $model->schema();
                $newModelData = array($model->name => array()); // this is a holder for the data to be added to the model
                $fieldlist = array();   // this will be an array of field names found in the Excel file, and which we have data for
                $newData = $this->modifyDataForReferencedFields($model, $data, $referencedFields);  // $newData is now 0-based.
                for ($curCol = 0; $curCol < count($newData[0]); $curCol++) {
                    $curFieldName = $newData[0][$curCol];
                    if (!array_key_exists($curFieldName, $schema)) {
                        return 'Row header "'.$curFieldName.'" is not one of the database fields.'
                                .'  You probably altered the template in an incorrect manner.';
                    } else {
                        // set up the fieldlist and newModelData arrays
                        array_push($fieldlist, $curFieldName);
                        $newModelData[$model->name][$curFieldName] = null;
                    }
                }
                // append $otherData fields to fieldlist
                foreach ($otherData as $key => $value) {
                    array_push($fieldlist, $key);
                }

                // So, the headers seem okay, let's try to enter the data into the Model
                $saveData = array();
                for ($curRow = 1; $curRow < count($newData); $curRow++) {   // row 0 is the headers
                    // put the data into the newModelData
                    for ($curCol = 0; $curCol < count($newData[0]); $curCol++) {
                        $curFieldName = $newData[0][$curCol];
                        $curVal = $newData[$curRow][$curCol];
                        $newModelData[$model->name][$curFieldName] = $curVal;
                    }
                    $existingID = $this->existingID($model, $lookupKeys, $newModelData[$model->name]);
                    if ($existingID) {
                        // we must be updating a model entry, so set the ID
                        $newModelData[$model->name]['id'] = $existingID;
                        $numAltered++;
                    } else {
                        // otherwise, unset
                        unset($newModelData[$model->name]['id']);
                        $numAdded++;
                    }

                    // Add in the fixed fields
                    foreach ($otherData as $key => $value) {
                        $newModelData[$model->name][$key] = $value;
                    }
                    array_push($saveData, $newModelData);
                }
                $options = array('fieldlist' => $fieldlist);
                if ($model->saveMany($saveData, $options)) {
                    return 'From the uploaded file, '.$numAdded.' records were added and '.$numAltered.' records were updated.';
                } else {
                    return 'There was a problem with the uploaded data.';
                }
            } else {
                return "The chosen file was not one of the allowed types.";
            }
        } else {
            return "There was something wrong with the upload process.";
        }
    } else {
        return "No file was chosen for uploading.";
    }
}

And here is the controller action that is called upon upload form submission:

public function processUpload() {
    // now parse the file in the model
    $result = $this->Instructor->parseExcelFile(
        $this->data['Instructor']['bulkData'],
        array(  // field(s) for looking up data in the model to see if we are adding or updating
            'username',
        ),
        array(  // a set of fixed fields to add to all entries, new or updates
            'department_id' => $this->request->data['Instructor']['department_id'],
            'role' => 'instructor',
            'password' => '')
    );
    $this->Session->setFlash($result);                  
    $this->redirect($this->referer(), null, true);
}

Thanks in advance. -Dave

  • 写回答

1条回答 默认 最新

  • dongxiangchan0743 2012-09-19 06:58
    关注

    The Model has some methods that could be invoked in order to check records. You should be able to use Model->validateMany() The Model class also has some other manual validation methods:

    Model->validateAssociated() which is used to validate a single record, as well as all its directly associated records and Model->validates() which returns true if all fields pass validation.

    Check the DataValidation section of the Cake Book. Cake 2.2.x also introduces the concept of Dynamically Changing validation rules, which could come in very handy.

    Cheers! :)

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器