cakephp 2.x设置验证前未在表单中传递的某些模型参数

时间:2014-10-27 07:22:45

标签: cakephp cakephp-2.0

我在验证之前设置了一些模型属性,并且我有这个代码块

public function beforeValidate() {
    $this->inventory->read(null, 1);
    $this->inventory->set('item_amount', '0.00');
    if ($this->inventory.'item_type' == 'powder'){
        $this->inventory->set('unit_measurement','g')
    }
    else if ($this->inventory.'item_type' == 'liquid'){
        $this->inventory->set('unit_measurement','ml')
    }
}

基本上我是根据从表单*传递的参数来设置库存模型的属性,而项目类型参数的形式是......单位测量不是... ..但它仍然是我的模型及其数据库表的一部分...任何重要的方式来解决这个问题?

如果你们需要它,那么这就是观点

<div class="inventories form">
    <?php echo $this->Form->create('Inventory'); ?>
    <fieldset>
    <legend><?php echo __('Admin Add Inventory item'); ?></legend>
    <?php
        echo $this->Form->input('Item_Name');
        echo $this->Form->input('Item_type', array(
        'options' => array('powder', 'liquid'),
        'empty' => '(choose one)'
        ));

    ?>
    </fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
    <h3><?php echo __('Actions'); ?></h3>
    <ul>

    <li><?php echo $this->Html->link(__('List Inventories'), array('action' => 'index')); ?></li>
    </ul>
</div>

1 个答案:

答案 0 :(得分:3)

您需要更改之前的验证功能,如

public function beforeValidate() {

if ($this->data['Inventory']['Item_type'] == 'powder'){
    $this->data['Inventory']['unit_measurement'] = 'g';
}
else {
    $this->data['Inventory']['unit_measurement'] = 'ml';
}

}