如何匹配输入字段,然后将其保存在cakephp中

时间:2012-03-23 16:41:51

标签: cakephp cakephp-1.3

当用户输入完整的url ..我只想保存youtube id ... pregmatch检查并提取视频ID然后它将被保存到数据库中..问题是如何进行这个pregmatch检查并提取youtube id在保存完整的URL之前 谢谢你的帮助

//这是videos_controller中的add()函数

 function add() {
        if (!empty($this->data)) {

            $this->Video->create();

            if ($this->Video->save($this->data)) {
                $this->Session->setFlash(__('The Video has been saved', true));
                $this->redirect(array('action' => 'admin_index'));
            } else {
                $this->Session->setFlash(__('The Video could not be saved. Please, try again.', true));
            }
        }
        $vcats = $this->Video->Vcat->find('list');
        $this->set(compact('vcats'));
    }

//这是add.ctp文件

<div class="videos form">
    <?php // echo $this->Form->create('Image');?>
    <?php echo $form->create('Video'); ?>
    <fieldset>
        <legend><?php __('Add Video'); ?></legend>
        <?php
        echo $this->Form->input('vcat_id');
        echo $this->Form->input('title');
       $url= $this->Form->input('link');
      echo $url
        ?>
    </fieldset>
    <?php echo $this->Form->end(__('Submit', true)); ?>
</div>
<div class="actions">
    <h3><?php __('Actions'); ?></h3>
    <ul>

        <li><?php echo $this->Html->link(__('List Videos', true), array('action' => 'index')); ?></li>
        <li><?php echo $this->Html->link(__('List Vcats', true), array('controller' => 'vcats', 'action' => 'index')); ?> </li>
        <li><?php echo $this->Html->link(__('New Vcat', true), array('controller' => 'vcats', 'action' => 'add')); ?> </li>
    </ul>
</div>

//我们通过匹配模式从网址获取唯一的视频ID,但我在保存之前将此代码与之匹配

preg_match("/v=([^&]+)/i", $url, $matches);
$id = $matches[1];

2 个答案:

答案 0 :(得分:1)

下面

 function add() {
    if (!empty($this->data)) {

        $this->Video->create();
        $url = $this->data['Video']['link'];

        /*assuming you have a column `id` in your `videos` table
        where you want to store the id,
        replace this if you have different column for this*/

        preg_match("/v=([^&]+)/i", $url, $matches);
        $this->data['Video']['id'] = $matches[1];

        //rest of the code
    }
 }

答案 1 :(得分:0)

我想这是一个更好的地方,在模型的beforeSavebeforeValidate方法中:

class Video extends AppModel {

    ...

    public function beforeSave() {
      if (!empty($this->data[$this->alias]['link'])) {
        if (preg_match("/v=([^&]+)/i", $this->data[$this->alias]['link'], $matches)) {
          $this->data[$this->alias]['some_id_field'] = $matches[1];
        }
      }
      return true;
    }

    ...

}