如何在将输入字段保存到cakephp之前匹配它
当用户输入完整url时..我只想保存youtube id。。。预匹配检查并提取视频id,然后将其保存到数据库中。问题是如何在保存完整url之前进行预匹配检查并提取youtube id 谢谢你的帮助 //这是控制器中的add()函数如何在将输入字段保存到cakephp之前匹配它,cakephp,cakephp-1.3,Cakephp,Cakephp 1.3,当用户输入完整url时..我只想保存youtube id。。。预匹配检查并提取视频id,然后将其保存到数据库中。问题是如何在保存完整url之前进行预匹配检查并提取youtube id 谢谢你的帮助 //这是控制器中的add()函数 function add() { if (!empty($this->data)) { $this->Video->create(); if ($this->Video-&g
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>
这里
我想更好的地方是模型的
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;
}
...
}
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
}
}
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;
}
...
}