使用Laravel 4表单设置默认值并使用错误输入?

gre*_*ert 2 laravel laravel-4

我正在使用Laravel 4及其内置的表单组件.我正在尝试设置它,以便我可以给出默认值的表单集,但如果用户提交并且验证程序失败,它将使用前一个输入的值.但是,下面的代码总是失败.由于某种原因,会话值'threw_error'始终为true,即使表单引发错误也是如此.

似乎一切都是通过会话完成的,这就是为什么我要设置__old_input,这是表单使用的内部键.我究竟做错了什么?我应该像这样使用__old_input,还是有更好的方法来实现这个目标?

我正在使用资源丰富的控制器,因此下面的index()是GET /,而store()是POST /.

class Admin_DetailsController extends Admin_BaseController
{
    public function index()
    {           
        $details = Detail::all();

        // this is always true for some reason?
        if(!Session::get('threw_error', false))
        {
            Session::put('__old_input', $details);          
        }

        $data['message'] = Session::get('message');

        $this->layout->nest('content', 'admin.details.index', $data);
    }

    public function store()
    {
        $validator = $this->makeValidator();
        if($validator->fails())
        {
            return Redirect::to('/admin/details')->withErrors($validator)->withInput()->with('threw_error', 1);
        }

        // process normally
    }
}

// in view
{{ Form::text('some_field') }}
Run Code Online (Sandbox Code Playgroud)

编辑:此代码或多或少按预期工作,但Session :: flashInput($ details)优于手动调用__old_input.我尝试删除表单中的一些字段以查看它是否存在,这实际上有效.换句话说,我认为这是我本地版本的PHP或某些配置或其他问题 - 而不是Laravel问题.

Mir*_*kov 7

从Laravel 4开始,您可以使用Form :: model($ model,array)而不是Form::open(array)

然后,您不必将值传递给Form帮助器方法.它将从模型中获取值,但首先,它将检查是否存在oldInput,因此该值将是旧值.

看看这个方法.这是一个很小的变化,但真的很聪明:)

但为了实现这一点,您必须使用输入重定向

Redirect::back()->withInput();
Run Code Online (Sandbox Code Playgroud)

像这样:

public function createNew()
{
    $data = array(
        'model' => new Model();
    );

    $this->layout->nest('content', 'admin.details.form', $data);
}

public function store()
{
    $validator = $this->makeValidator();
    if($validator->fails())
    {
        return Redirect::back()
            ->withErrors($validator)
            ->withInput();
    }
}

// In the view
{{ Form::model($model, array(...)) }}

    // The first time it will be null
    // But if the validation fails, it will be the old value 
    {{ Form::text('some_field', 'Some fields title') }} 

{{ Form::close()}}
Run Code Online (Sandbox Code Playgroud)

PS而不是使用Session::flashInput(),你可以使用Input::old()