为了创建表单装饰器(用于视图渲染),我创建了一个抽象类 BaseForm ,如下所示:
abstract class BaseForm extends Form {
/**
* Render form field
* @param $name
* @param array $attr
* @return string
*/
public function renderDecorated($name, $attr = [])
{
$e = $this->get($name);
return '<li '.($this->hasErrors($e)?'class="error"':'').'>'.$this->renderItem($e, $attr).'</li>';
}
/**
* Render form field with errors displayed
* @param $name
* @param array $attr
* @return string
*/
public function renderDecoratedErrors($name, $attr = [])
{
$e = $this->get($name);
return '<li '.($this->hasErrors($e)?'class="error"':'').'>'.$this->renderErrors($e).$this->renderItem($e, $attr).'</li>';
}
/**
* Render classic form field
* @param $e
* @param array $attr
* @return string
*/
public function renderItem($e, $attr = []){
return '<label for="'.$e->getName().'">'.$e->getLabel().'</label>'.$e->render($attr);
}
/**
* Render errors
* @param $e
* @return string
*/
public function renderFieldErrors($e){
$m = $this->getMessagesFor($e->getName());
if (count($m)) {
$r = '<ul class="err_msg">';
foreach ($m as $i) {
$r .= '<li>'.$this->flash->error($i).'</li>';
}
return $r.'</ul>';
}
}
/**
* Check if specific field by $e has assigned errors
* @param $e
* @return bool
*/
public function hasErrors($e){
$m = $this->getMessagesFor($e->getName());
if (count($m))
return true;
return false;
}
/**
* Decorator for form errors
* @return null|string
*/
public function renderErrorsDecorated(){
if(count($this->getMessages())){
$r = '<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>';
foreach ($this->getMessages() as $key => $message) {
$r .= $message. '<br />';
}
return $r.'</div>';
}
return null;
}
}
我的所有表单都应该扩展 BaseForm 类。所有 BaseForm 方法通常仅在视图中调用。
可在此处找到使用示例:https://github.com/mpetcu/report-manager/tree/master/app/forms
还有其他办法吗?我不认为在表单类中使用视图逻辑(HTML)是正确的方法吗?