CakePHP-合并添加和编辑问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CakePHP-合并添加和编辑问题相关的知识,希望对你有一定的参考价值。

可以这么说,我正在尝试将添加和编辑功能“合并”到一个“保存”功能中,无论是否提供了模型的$ id,该功能都会更新或添加模型的新实例。通过开始编写此代码,我意识到这个想法比Cakephp的添加和编辑方法内置的方法带来更多的麻烦,实际上,我的导师坚持认为我将其合并,因此即使我个人认为这不是最佳方法,也应尝试一下。

ItemTypesController.php

class ItemTypesController extends AppController {
public function save($id = null) {
    if($this->request->is(array('post', 'put'))){
        $this->ItemType->set($this->request->data);
        //if i put an exit() funct here, it exits on this spot
        if($this->ItemType->validates()){
            if(!$id){
                $this->ItemType->create();
                if ($this->ItemType->save($this->request->data)) {
                    $this->Flash->success(__('The item type has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } else {
                    $this->Flash->error(__('The item type could not be saved. Please, try again.'));
                }
            }
            else{
                if ($this->ItemType->save($this->request->data)) {
                    $this->Flash->success(__('The item type has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } else {
                    $this->Flash->error(__('The item type could not be saved. Please, try again.'));
                }
            }
        } else {
            $this->Flash->warning($this->ItemType->validationErrors, array(
                'key' => 'negative'
            ));
        }

    } else {
        $options = array('conditions' => array('ItemType.' . $this->ItemType->primaryKey => $id));
        $this->request->data = $this->ItemType->find('first', $options);
    }
    $this->set('classes', $this->ItemType->classes);
}
}

因此,如果没有提供$ id,则该函数将进入if block,如果我输入一个新ItemType的链接,就是这种情况。而且它对于create很有效,但是,当我尝试对其进行更新时,由于“ isUnique”规则,它始终要求必须更改任何字段,因此我将该规则设置为仅用于create,但是CakePHP会自动考虑其create函数。 ,虽然这里使用了我的save()函数,但它可能认为它需要为我的函数输入该规则。

ItemType.php

class ItemType extends AppModel {

public $classes = array(
    'product' => 'Proizvod',
    'kit' => 'Kit (bundle)'
);

public $validate = array(
    'code' => array(
        'required' => array(
            'rule' => 'notBlank',
            'message' => 'A code is required'
        ),
        'alphanum' => array(
            'rule' => 'alphanumeric',
            'message' => 'A code must be an alphanumeric value'
        ),
        'unique' => array(
            'rule' => 'isUnique',
            'message' => 'This code already exists!',
            'required' => 'create'
        ),
        'between' => array(
            'rule' => array('lengthBetween', 3, 7),
            'message' => 'Code must be between 3 and 7 characters long'
        )
    ),
    'name' => array(
        'required' => array(
            'rule' => 'notBlank',
            'message' => 'A name is required'
        ),
        'unique' => array(
            'rule' => 'isUnique',
            'message' => 'This name already exists!',
            'required' => 'create'
        ),
        'between' => array(
            'rule' => array('lengthBetween', 3, 30),
            'message' => 'Name must be between 3 and 30 characters long'
        )
    ),
    'class' => array(
        'valid' => array(
            'rule' => array('inList', array('product', 'material', 'kit', 'semi_product', 'service_product', 'service_supplier','consumable','inventory','goods','other')),
            'message' => 'Please enter a valid class',
            'allowEmpty' => false
        )
    ),
    'tangible' => array(
        'bool' => array(
            'rule' => 'boolean',
            'message' => 'Incorrect value for the checkbox'
        )
    ),
    'active' => array(
        'bool' => array(
            'rule' => 'boolean',
            'message' => 'Incorrect value for the checkbox'
        )
    )
    );

public $hasMany = array(
    'Item' => array(
        'className' => 'Item',
        'foreignKey' => 'item_type_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);
}

这是我要输入新视图或更新视图的视图:

index.ctp

    <div class="itemTypes index">
    <h2><?php echo __('Item Types'); ?></h2>
    <table cellpadding="0" cellspacing="0">
    <thead>
    <tr>
            <th><?php echo $this->Paginator->sort('id'); ?></th>
            <th><?php echo $this->Paginator->sort('code'); ?></th>
            <th><?php echo $this->Paginator->sort('name'); ?></th>
            <th><?php echo $this->Paginator->sort('class'); ?></th>
            <th><?php echo $this->Paginator->sort('tangible'); ?></th>
            <th><?php echo $this->Paginator->sort('active'); ?></th>
            <th><?php echo $this->Paginator->sort('created'); ?></th>
            <th><?php echo $this->Paginator->sort('modified'); ?></th>
            <th class="actions"><?php echo __('Actions'); ?></th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($itemTypes as $itemType): ?>
    <tr>
        <td><?php echo h($itemType['ItemType']['id']); ?>&nbsp;</td>
        <td><?php echo h($itemType['ItemType']['code']); ?>&nbsp;</td>
        <td><?php echo h($itemType['ItemType']['name']); ?>&nbsp;</td>
        <td><?php echo h($itemType['ItemType']['class']); ?>&nbsp;</td>
        <td><?php if($itemType['ItemType']['tangible']) echo "Yes"; else echo "No" ?></td>
        <td><?php if($itemType['ItemType']['active']) echo "Yes"; else echo "No" ?></td>
        <td><?php echo h($itemType['ItemType']['created']); ?>&nbsp;</td>
        <td><?php echo h($itemType['ItemType']['modified']); ?>&nbsp;</td>
        <td class="actions">
            <?php echo $this->html->link(__('View'), array('action' => 'view', $itemType['ItemType']['id'])); ?>
            <?php echo $this->Html->link(__('Edit'), array('action' => 'save', $itemType['ItemType']['id'])); ?>
            <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $itemType['ItemType']['id']), array('confirm' => __('Are you sure you want to delete # %s?', $itemType['ItemType']['id']))); ?>
        </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
    </table>
    <p>
        <?php
        echo $this->Paginator->counter(array(
        'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
    ));
    ?>  </p>
    <div class="paging">
    <?php
        echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
        echo $this->Paginator->numbers(array('separator' => ''));
        echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
    ?>
    </div>
</div>

    <div class="actions">
            <h3><?php echo __('Actions'); ?></h3>
            <ul><li><?php echo $this->Html->link(__('New Item Type'), array('action' => 'save'));         ?>
</li>
</ul>
</div>

save.ctp

<div class="itemTypes form">
    <?php echo $this->Form->create('ItemType'); ?>
    <fieldset>
        <legend><?php echo __('Add Item Type'); ?></legend>
        <?php
        echo $this->Form->input('code');
        echo $this->Form->input('name');
        echo $this->Form->input('class', array('options' => $classes));
        echo $this->Form->input('tangible');
        echo $this->Form->input('active');
        ?>
    </fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>
</div>

    <div class="actions"><h3><?php echo __('Actions'); ?></h3><ul><li><?php echo     $this->Html->link(__('List Item Types'), array('action' => 'index')); ?></li></ul></div>
答案

功能保存的编码不好,因为从未设置过模型的ID,所以它不知道它是否正在更新。

public function save($id = null) {
        if($this->request->is(array('post', 'put'))){
            if($id){
                $this->request->data['ItemType']['id'] = $id;
            }
            $this->ItemType->set($this->request->data);
            if($this->ItemType->validates()){
                if(!$id){
                    $this->ItemType->create();
                }
                if ($this->ItemType->save($this->request->data)) {
                    $this->Flash->success(__('The item type has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } else {
                    $this->Flash->error(__('The item type could not be saved. Please, try again.'));
                }
            } else {
                $this->Flash->warning($this->ItemType->validationErrors, array(
                    'key' => 'negative'
                ));
            }

        } else {
            $options = array('conditions' => array('ItemType.' . $this->ItemType->primaryKey => $id));
            $this->request->data = $this->ItemType->find('first', $options);
        }
        $this->set('classes', $this->ItemType->classes);}

现在,这是函数的外观。

以上是关于CakePHP-合并添加和编辑问题的主要内容,如果未能解决你的问题,请参考以下文章

CakePHP 3 编辑上传

CakePHP 2.4 中同一模型的多个编辑表单

CakePHP:向表单添加字段(动态)

CakePHP 2.1 测量页面执行时间

跨 CakePHP 检索和传输用户 ID 的安全方法

如何将 URL 编码为 CakePHP 参数