du4373 2013-08-26 07:05
浏览 26
已采纳

CakePHP HABTM数据未保存到数据库

I have a model GenForm which has a HABTM relationship with another model PdfFile. I use this to generate a list of checkboxes in my GenForm index view. In the GenForm model, I added:

public $hasAndBelongsToMany = array(
    'PdfFile' => array(
        'className' => 'PdfFile',
        'joinTable' => 'gen_forms_x_pdf_files'
    )

Here's a fragment from my GenForm index.ctp view:

<?php 
echo $this->Form->input( 'PdfFile', array('label' => 'Select some PDF files', 'multiple' => 'checkbox') );
echo $this->Form->input( 'first_name' );
echo $this->Form->input( 'last_name' );
?>

In the controller, I have a basic save:

    if ($this->request->is('post')) { // form was submitted
        $this->GenForm->create();
        if ($this->GenForm->save($this->request->data)) {
            return $this->redirect(array('action' => 'generate', $this->GenForm->id)); // assemble the PDF for this record
        } else {
            $this->Session->setFlash(__('Log entry not saved.'));
        }
    }

Now $this->data looks something like this when I debug() it:

array(
    'PdfFile' => array(
        'PdfFile' => array(
            (int) 0 => '1',
            (int) 1 => '5'
        )
    ),
    'GenForm' => array(
        'first_name' => 'xxx',
        'last_name' => 'xxx',
        'association_id' => '1',
        'email' => ''
    )
)

Everything works perfectly, but I couldn't validate the checkboxes (at least one must be checked). So, as per this answer, I made some changes.

The index.ctp view became:

<?php 
echo $this->Form->input( 'GenForm.PdfFile', array('label' => 'Select some PDF files', 'multiple' => 'checkbox') );
echo $this->Form->input( 'first_name' );
echo $this->Form->input( 'last_name' );
?>

Here's my validation rule:

public $validate = array(
    'PdfFile' => array(
        'rule' => array(
            'multiple', array('min' => 1)
        ), 
        'message' => 'Please select one or more PDFs'
    )
)

This is what $this->data looks like now:

array(
    'GenForm' => array(
        'PdfFile' => array(
            (int) 0 => '1',
            (int) 1 => '5'
        ),
        'first_name' => 'xxx',
        'last_name' => 'xxx',
        'association_id' => '1',
        'email' => ''
    )
)

Now the checkboxes for PdfFile validate, but the PdfFile data isn't saved -- although the other fields for GenForm are saved correctly to their own table.

Can anyone tell me what I'm missing so that PdfFile saves automatically and gets validated?

展开全部

  • 写回答

2条回答 默认 最新

  • douluo3256 2013-08-26 07:59
    关注

    The first form is right

    Stating the obvious, but the form that worked is the form to use i.e.:

    echo $this->Form->input('PdfFile', array(
        'label' => 'Select some PDF files', 
        'multiple' => 'checkbox'
    ));
    

    Changing the form to have a "field" named 'PdfFile' will simply not work - as the model layer will remove any data for fields that don't exist - and in this form it will check for gen_forms.PdfFile, find there is no field and ignore the data.

    Validation

    To take care of validation errors - use a validation rule running on the model which checks the number of habtm records to be saved. It doesn't matter what the name of the field used for validation is e.g.:

    <?php
    class GenForm extends AppModel {
    
        public $validate = array(
            'dummy' => array( // <- name this whatever you like
                'atLeastOne' => array(
                    'required' => true, // run always
                    'rule' => array('validateAtLeastOne')
                )
            )
        );
    
        function validateAtLeastOne() {
            if (!isset($this->data['PdfFile'])) {
                // there is no pdf data at all, ignore this rule
                // allow other save operations to work
                return true;
            }
    
            $return = count(array_filter($this->data['PdfFile']['PdfFile']));
            if (!$return) {
                $this->PdfFile->invalidate('PdfFile', 'Please upload a file');
            }
            return $return;
        }
    
    }
    

    Because the validation rule returns false if there are no records it will halt the save. By calling invalidate on the HABTM association with the same "field" name that the form helper will look for - an error message will be displayed.

    Alternatively

    You can use the second approach in the question:

    echo $this->Form->input('GenForm.PdfFile', array(
        'label' => 'Select some PDF files', 
        'multiple' => 'checkbox'
    ));
    

    In the full knowledge that this is not how cake expects to receive data and then manipulate it to be the right format in beforeValidate:

    <?php
    class GenForm extends AppModel {
    
        public $validate = array(
            'PdfFile' => array( // existing rule
                ...
            )
        );
    
        function beforeValidate() {
            if (isset($this->data[$this->alias]['PdfFile'])) {
                // keep the existing data as that's what validation will check against
                // copy to the right location so Cake will process it
                $this->data['PdfFile']['PdfFile'] = $this->data[$this->alias]['PdfFile'];
            }
            return true;
        }
    
        ...
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部