【问题标题】:Laravel populate form with cloned model dataLaravel 使用克隆的模型数据填充表单
【发布时间】:2021-11-14 07:32:18
【问题描述】:

我在我的应用程序中实现了一个“克隆”按钮,它应该允许执行以下操作:

  1. 创建所选模型的副本;
  2. 重定向到create 视图,其表单字段应填充克隆模型的数据;
  3. 允许用户编辑某些字段;
  4. 保存新模型。

到目前为止,我的ModelController@clone方法是:

$newModel = $existingModel->replicate();
$newModel->title = "Copy of ".$existingModel->title;
$newModel->created_at = now() // not sure if necessary, or if it'll be changed once the model is stored in the database

return redirect(route('models.create')); // I know this doesn't do what I need

显然,没有任何东西传递给create 视图,但我找不到任何关于如何做到这一点的线索。

我尝试将->withInput(compact($newModel)) 添加到redirect() 调用中,但我没有看到该字段被填充。

models.create 视图中,我已将表单字段设置为使用old(...) 数据(如果有)。

This 答案几乎是我所需要的,但这意味着更改每个字段以检查除了old 会话数据之外是否还有某种输入,如下所示:

<input [other attributes omitted] value="{{ $newModel['title'] ?? old('title') }}">

这样做是正确的方式,还是有更快/更标准化的处理方式?

【问题讨论】:

    标签: laravel laravel-5 view clone


    【解决方案1】:

    您可以通过以下方式覆盖会话旧输入数据:

    Session::put('_old_input', $newModel);
    

    然后在表单输入中渲染old()

    【讨论】:

    • 不知道old 值可以像这样“人工”创建。必须调整一些涉及关系的事情才能使其发挥作用,但现在没关系。谢谢!
    • 不客气...
    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 2019-01-29
    • 2014-06-11
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多