0

I have scenario where I have 3 different models data being saved from one form, by means of the saveAll pass through method in CakePHP 2.x

The models on the form are:

  1. Project
  2. ProjectImage
  3. ProjectAttachment

1 and 2 are saving perfectly, but I am having problems with the ProjectAttachment fields. If you look at the following image, the fields in question are at the bottom right, highlighted by a red frame: http://img.skitch.com/20120417-bnarwihc9mqm1b49cjy2bp13cf.jpg

Here is the situation:

I have named the fields as follows: *ProjectAttachment.0.project_id*, ProjectAttachment.0.name .... *ProjectAttachment.6.project_id* etc where the numbers are relative to the already present amount of attachments the user has added, as there is no limit. So if the user has ALREADY added 6 documents, the field would be called ProjectAttachment.7.id and so on. This is because of the naming convention when using the saveAll method.

I have made use of two hidden fields, one to store the user ID, the other to store the project ID.

The problem is that if the user does not fill in the Document Title and select a file to upload, the form fails! If I remove all validation rules, the form no longer fails BUT a blank ProjectAttachment record is inserted.

I suspect the problem may also be that the project_id and user_id fields (that are hidden) already have values in them?

I gave it some thought, and came up with a simple concept: In my controller, before the saveAll call, I would check to see if a blank Document Title field was submitted, and if so, I would completely eliminate the relevant array entry from the $this->request->data['ProjectAttachment'] array, but this did not seem to work.

To clarify, I am not looking for validation rules. If the user decides they only want to upload images and not touch the ProjectAttachment form, them the saveAll operation must not fail, it must simple not attempt to save the blank fields in the form, if this is at all possible.

Any suggestions?

Kind regards, Simon

4

1 回答 1

0

好吧,似乎解决方案比我最初想象的要简单得多!我部分在正确的轨道上,如果遇到任何空白字段,我必须取消设置$this->request->data数组中的变量ProjectArray键。

我这样做如下:

    if(!empty($this->request->data['ProjectAttachment'])){
        foreach($this->request->data['ProjectAttachment'] as $key => $value){
            if(is_array($value) && array_key_exists('upload_file', $value)){
                if($value['upload_file']['name'] == ''){ // Blank document file
                    unset($this->request->data['ProjectAttachment']);
                }
            }
        }
    }

我希望有人发现这以某种形式有用。

亲切的问候,西蒙

于 2012-04-17T09:11:32.407 回答