【发布时间】:2015-11-19 18:15:50
【问题描述】:
仍在通过教程学习 Phalcon,但在表单字段旁边显示表单错误消息时遇到问题。
表单代码如下
<?php
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\TextArea;
use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Email;
class ContactForm extends Form
{
public function initialize()
{
// Name
$fullname = new Text('fullname');
$fullname->setFilters(array('striptags', 'string'));
$fullname->addValidators(array(
new PresenceOf(array(
'message' => 'Full Name is required'
))
));
$this->add($fullname);
// Email and text area fields with validators
/**
* Prints messages for a specific element
*/
public function messages($name)
{
if ($this->hasMessagesFor($name)) {
foreach ($this->getMessagesFor($name) as $message) {
$this->flash->error($message);
}
}
}
}
使用volt引擎的表格如下
{{ form('pages/contact') }}
<div class="controls controls-row">
{{ form.render('fullname') }}
{{ form.render('email') }}
<span class="help-inline error">{{ form.messages('fullname') }}</span>
<span class="help-inline error">{{ form.messages('email') }}</span>
</div>
<div class="controls">
<span class="help-inline error">{{ form.messages('comments') }}</span>
{{ form.render('comments') }}
</div>
<div class="controls">
{{ submit_button('Send It', 'class': 'btn btn-primary pull-right') }}
</div>
</form><!--end form-->
在contactAction()中处理表单的代码如下
$form = new ContactForm();
if ($this->request->isPost() == true)
{
if ($form->isValid($_POST)==false)
{
$form->messages("fullname");
$form->messages("email");
$form->messages("comments");
}else
{
//send email
}
}
$this->view->form =$form
通过调用 $form->messages("fullname") 和其他字段,将使用 {{ flash.output() }} 打印验证消息,这通常位于我放置代码的页面顶部.如何让 Flash 消息显示在表单字段旁边?
请帮忙。谢谢
【问题讨论】:
-
我认为您需要使用 $this->view->setVar('fullname_error', $form->messages("fullname")); 在控制器中设置一个变量对于每个错误并在您想要的位置显示该变量。
-
谢谢沙德,不工作
标签: php html mysql model-view-controller phalcon