[symfony]Javascriptを用いたリンク処理
2009 年 5 月 29 日
コメントはありません
普通にウェブプログラミングをしていると、ハイパーリンク内で特定のスクリプトのトリガーを引きたくなるときがある。
「戻る」や「ポップアップ」機能がその代表例とも言えるだろう。
symfonyにはjavascriptヘルパーが用意されており、これらを用いると比較簡単にリンク処理をすることができる。
- echo link_to_function('戻る', 'history.back()');
- // <a href="#" onclick="history.bakc()">戻る</a>
- echo button_to_function('削除', 'if confirm("本当に削除してもよろしいですか?"){ do_delete(); }');
- // <input type="button" onclick='if confirm("本当に削除してもよろしいですか?"){ do_delete(); }' value="削除" />
ちなみにpear内のJavascriptHelper.phpには次のように書かれていた。
- /**
- * Returns a link that'll trigger a javascript function using the
- * onclick handler and return false after the fact.
- *
- * Examples:
- * <?php echo link_to_function('Greeting', "alert('Hello world!')") ?>
- * <?php echo link_to_function(image_tag('delete'), "if confirm('Really?'){ do_delete(); }") ?>
- */
- function link_to_function($name, $function, $html_options = array())
- {
- $html_options = _parse_attributes($html_options);
- $html_options['href'] = isset($html_options['href']) ? $html_options['href'] : '#';
- $html_options['onclick'] = $function.'; return false;';
- return content_tag('a', $name, $html_options);
- }
- /**
- * Returns a button that'll trigger a javascript function using the
- * onclick handler and return false after the fact.
- *
- * Examples:
- * <?php echo button_to_function('Greeting', "alert('Hello world!')") ?>
- */
- function button_to_function($name, $function, $html_options = array())
- {
- $html_options = _parse_attributes($html_options);
- $html_options['onclick'] = $function.'; return false;';
- $html_options['type'] = 'button';
- $html_options['value'] = $name;
- return tag('input', $html_options);
- }
ヘルパーのファイルを探索すれば、意外に便利なものが見つかるかもしれない。

