在添加数据库之前在php中编辑表单输入

时间:2016-03-15 07:39:56

标签: php cakephp cakephp-2.0

我有一个向db添加产品的方法,我想自动将产品名称编辑为产品的url。 它怎么样?

这是我的表格:

<?php echo $this->Form->create('Product', array('type'=>'file')); ?>
        <fieldset>
            <legend><?php echo __('Add Product'); ?></legend>
        <?php
            echo $this->Form->input('category_id');
            echo $this->Form->input('name');
            echo $this->Form->input('Picture.0.name', array('type'=>'file'));
            echo $this->Form->input('description');
        ?>
        </fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>

在db的product表中有一个名为url的coloumn。我想获取产品的名称并进行编辑,然后将其保存为产品的网址。

public function add() {
    if ($this->request->is('post')) {
        $this->Product->create();
        $this->request->data['Product']['user_id'] = $this->member['id'];
        if ($this->Product->saveAll($this->request->data)) {
            $this->Flash->success(__('The product has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }
    }
    $categories = $this->Product->Category->find('list');
    $users = $this->Product->User->find('list');
    $this->set(compact('categories', 'users'));
}

这是我的编辑功能:

function edit_url($input_str){
  $input_str = strtolower($input_str);
                                                // replaces other characters to en characters
  $input_str=str_replace('â', 'a', $input_str);
  $input_str=str_replace('ç', 'c', $input_str);
  $input_str=str_replace('ğ', 'g', $input_str);
  $input_str=str_replace('ı', 'i', $input_str);
  $input_str=str_replace('ö', 'o', $input_str);
  $input_str=str_replace('ş', 's', $input_str);
  $input_str=str_replace('ü', 'u', $input_str);
                                                // replaces spaces with -
  $input_str=str_replace(' ', '-', $input_str);
                                                // replaces symbols
  $input_str=str_replace('.', '', $input_str);
  $input_str=str_replace('/', '', $input_str);
  $input_str=str_replace('*', '', $input_str);
  $input_str=str_replace('+', '', $input_str);
  $input_str=str_replace('?', '', $input_str);

  return $input_str;
}

2 个答案:

答案 0 :(得分:0)

$ this-&gt; request-&gt; data ['Product'] ['url'] = $ this-&gt; slugify($ this-&gt; request-&gt; data ['Product'] ['name' ]);

解决了我的问题。但还有一个问题。如果有多个产品具有相同的名称......

答案 1 :(得分:0)

嘿,您可以在此网址http://milesj.me/code/cakephp/utility下下载cakephp实用工具插件 那么你应该在你的模型中添加这个代码     

imageNamed:

您还应该在数据库表中创建一个列作为slug。 现在,如果你想在更新数据时更改slug,那么你应该通过&#39; onUpdate&#39; =&GT;真的 这是为了创建独特的slug
Cakephp还提供了一些您可以在此网址http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html

下查看的功能

Inflector :: slug($ word,$ replacement =&#39; _&#39;)