2012-03-23 5 views
0

, когда пользователь вводит полный url..i хочу сохранить только идентификатор youtube ... pregmatch исследует и извлекает идентификатор видео, а затем он будет сохранен в базе данных .. проблема как сделать эту проверку pregmatch и извлечь идентификатор YouTube, прежде чем сохранить полный адрес спасибо за помощькак совместить поле ввода, прежде чем сохранить его в cakephp

// это добавить() функцию в videos_controller

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> 

// получаем уникальный идентификатор видео из URL, сопоставляя образец, но когда я ставлю этот код, чтобы соответствовать, прежде чем сохранить

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

ответ

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 
    } 
} 
0

Я думаю, лучшее место для него в модели beforeSave или beforeValidate:

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; 
    } 

    ... 

} 
Смежные вопросы