@pankarの答えはほとんど良いです。ただし、$this->form->save()
はをオーバーライドしますsetLink
。
まず、新しいツールクラスで定義されているように、YouTubeIDを取得する関数を定義します。lib/myTools.class.php
<?php
class myTools
{
/**
* Get youtube video ID from URL
*
* @see https://stackoverflow.com/a/6556662/569101
* @param string $url
* @return string Youtube video id or FALSE if none found.
*/
public static function youtube_id_from_url($url)
{
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if (false !== $result)
{
return $matches[1];
}
return false;
}
}
次に、これでアクションを更新します。
if ($this->form->isValid())
{
// save the form
$song = $this->form->save();
// update saved value
$youtube_id = myTools::youtube_id_from_url($song->getLink());
$song->setLink($youtube_id);
$song->save();
$this->getUser()->setFlash('notice', 'Thank you, the song has been added');
$this->redirect('@homepage');
}
ちなみに、この方法は、フォームを1か所でのみ使用する場合は問題ありません。更新はフォームクラスではなくアクションで実行されるためです。それ以外の場合は、@ glerendeguiが言ったように、フォームクラスでこのアクションを実行する必要があります。しかし、私はむしろのdoUpdateObject
代わりにそれを行いdoSave
ます。コードが言うので:
/**
* Updates the values of the object with the cleaned up values.
*
* If you want to add some logic before updating or update other associated
* objects, this is the method to override.
*
* @param array $values An array of values
*/
abstract protected function doUpdateObject($values);
だから私はあなたのフォームの中でこのようにそれをします(lib/form/doctrine/yourForm.class.php
):
class yourForm extends BaseYourForm
{
public function configure()
{
}
protected function doUpdateObject($values)
{
$youtube_id = myTools::youtube_id_from_url($values['link']);
$this->getObject()->setLink($youtube_id);
return parent::doUpdateObject($values);
}
}