akkun_choi pedia
mindiaakkun_choi pedia見出し語

Zend_Form+Smarty

akkun_choi · 2008-10-22 更新

Zend_FormのレンダリングにはZend_View_Interfaceが必要です。でもこのZend_View_Interfaceの実装がなかなか大変。Zend_Formは要素の出力にZend_View_Helperを使ってるし…、もしかしてこれ全部実装しないといけないのか…?

考え出すとなんか大変な気がするので、ここはもう諦めて、Zend_View_AbstractでZend_Form_Elementをrenderしちゃいます。その後でSmartyテンプレートを使って各要素を出力していくという手法を取りましょう。

>|php|
<?php
// Zend_Formの各要素を事前に出力して、Smartyにassignする。

$smarty = $this->getSmarty(); // Smarty
$fh = $this->getFormHelper(); // FormHelper

if ($errors = $fh->errors()){
$smarty->assign('message', $errors);
}
$smarty->assign('attributes', $fh->formAttribs());
$smarty->assign('hidden', $fh->hiddens());

$elements = array();
foreach ($form->inputElements() as $key => $value){
$elements[$key] = array(
'type' => $value->getType(),
'label' => $value->getLabel(),
'html' => $value->render()
);
}
$smarty->assign('elements', $elements);

//各自実装してね
interface FormHelper{
// 各elementsのgetMessagesを集約したものを返す
function errors();

// formの属性値を返す
function formAttribs();

// 全てのHiddenとHash要素を返す
function hiddens();

// HiddenとHashとSubmit要素以外のすべてを返す
function inputElements();
}
?>
||<

テンプレートはこんな風に。

{if $message}
  <div class="message">{$message}</message>
{/if}

<form {$attributes}>
{$hidden}

<table>
{foreach from=$elements item=e}
  <tr><th>{$e.label}</th><td>{$e.html}</td></tr>
{/foreach}
</table>

{$elements.submit.html}
</form>

もっと自由にデザインしたい場合は、foreachをやめてキーを指定すればいい。速度的にもそんなに変わらないし、わかりやすいし、ちゃんとしたアダプタークラスができるまではとりあえずこれでいいと思う。

関連する見出し語