douhaoqiao9304 2013-06-13 15:39
浏览 46
已采纳

Laravel:在允许Form :: old()的同时填充表单

What's the best way to populate forms with database data made using the Form class in Laravel while still giving way to Input::old() if there are any errors? I can't seem to get it right.

My current setup looks something like this

public function getSampleform() {
    // Load database data here

    return View::make('sampleform');
}

public function postSampleform() {
    // Save to database again then redirect to success page

    return Redirect::to('success');
}

I usually echo my fields in the View this way:

<?php echo Form::text('entry', Input::old('entry'), array('class' => 'form-select'); ?>

What am I doing wrong?

  • 写回答

4条回答 默认 最新

  • duanmei1922 2013-06-15 14:24
    关注

    The best way to do this is using Form Model Binding (http://four.laravel.com/docs/html#form-model-binding):

    Use an existing model or create an 'empty' model class:

    class NoTable extends Eloquent { 
        protected  $guarded = array();
    }
    

    Find your model or instantiate your empty class and fill it with data:

    public function getSampleform() {
        // Load database data here
    
        $model = new NoTable;
        $model->fill(['name' => 'antonio', 'amount' => 10]);
    
        return View::make('sampleform')->with(compact('model'));
    }
    

    If you'll use your form with a table that you already have data on it, this is how you uset it:

    public function getSampleform() {
    
        // Locate the model and store it in a variable:
        $model = User::find(1);
    
        // Then you just pass it to your view:   
        return View::make('sampleform')->with(compact('model'));
    }
    

    To have your form populated, use Form Model Binding, this is an example in Blade:

    {{ Form::model($model, array('route' => array('sample.form')) ) }}
        {{ Form::text('name') }}
        {{ Form::text('amount') }}
    {{ Form::close() }}
    

    You don't even have to pass your Input data, because Laravel will populate your inputs using what comes first:

    1 - Session Flash Data (Old Input)
    2 - Explicitly Passed Value (wich may be null or not)
    3 - Model Attribute Data
    

    And Laravel will also take care of csrf token for you, using Form::open() or Form::model().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)