锂形式帮助数据和错误丢失?

时间:2012-05-02 11:18:00

标签: php php-5.3 lithium

我正在构建一个测试Lithium应用程序以了解它是如何工作的,我发现表单助手似乎无法识别我的数据被传回或任何验证错误。

目前我不得不手动传回我的错误,然后在视图中处理它们。

QuestionsController ::问

public function ask() {
    if (!empty($this->request->data)) {
        $question = Questions::create($this->request->data);
        if ($question->save()) {
            return $this->redirect(array('Questions::view', 'args'=>$question->id));
        } else {
            $errors = $question->errors();
        }

        if (empty($question)) {
            $question = Questions::create();
        }

        return compact('question', 'errors');
    }
}

视图/问题/ ask.html.php

<?php
// Assign the protected object to a variable so we can get at it
if(isset($question)){
    $data = $question->data();
}else{
    $data['title'] = '';
    $data['text'] = '';
}
?>

<?=$this->form->create();?>

    <?=$this->form->field('title', array('placeholder'=>'Title your question', 'value'=>$data['title']));?>
    <?php if(isset($errors['title'])){
        echo "<div class='alert alert-error'><a class='close' data-dismiss='alert' href='#'>×</a>";
        foreach($errors['title'] as $e){
            echo $e."<br/>";
        }
        echo "</div>";
    }?>

    <?=$this->form->field('text', array('placeholder'=>'Enter your question (supports Markdown)', 'type'=>'textarea', 'value'=>$data['text']));?>
    <?php if(isset($errors['text'])){
        echo "<div class='alert alert-error'><a class='close' data-dismiss='alert' href='#'>×</a>";
        foreach($errors['text'] as $e){
            echo $e."<br/>";
        }
        echo "</div>";
    }?>
    <p>Text input supports <?php echo $this->html->link('markdown', 'http://en.wikipedia.org/wiki/Markdown');?></p>

    <?=$this->form->submit('Ask', array('class'=>'btn'));?>
<?=$this->form->end();?>

我可以从lithium\template\helper\Form看到field()方法可以采用template参数,在示例中为<li{:wrap}>{:label}{:input}{:error}</li>,因此帮助程序中有足够的容量用于显示验证信息。

那么如何在我的控制器中组织我的数据,以便将其传递回视图,以便帮助者填充我的字段并显示错误?

修改
我应该补充一点,示例'Sphere'应用程序,也使用此方法,它是标准的吗? (ref

1 个答案:

答案 0 :(得分:2)

TL; DR

简短的回答是,您可以将表单绑定到Entity的子类,即RecordDocument,如Form::create()所示(链接缩写为{ {1}}打破了链接解析器。)

您的代码如下:

::

答案很长:

<?= $this->form->create($question); ?> <?= $this->form->field('title'); ?> <?= $this->form->field('text'); ?>

QuestionsController::ask()

public function ask() { $question = Questions::create(); if (!empty($this->request->data)) { if ($question->save($this->request->data)) { return $this->redirect(array('Questions::view', 'args'=>$question->id)); } } return compact('question'); }

views/questions/ask.html.php

请注意,如果有以下情况,表单助手将自动显示错误:)

#li3哲学的一些有用链接:

1 - http://www.slideshare.net/nateabele/lithium-the-framework-for-people-who-hate-frameworks

2 - Video of roughly the same presentation (w/ a good example on changing form templates)