gpt4 book ai didi

php - 如何在 Laravel 中从 XML 构建表单

转载 作者:可可西里 更新时间:2023-11-01 14:03:01 24 4
gpt4 key购买 nike

更新:
我知道如何解析 XML,但不知道在体系结构中的确切位置,请参阅下面定义的问题。
欢迎所有建议!


在学习 Laravel 的过程中,我尝试从 XML 文件构建一个表单。

问题:

  1. 如何从 XML 中获取数据到 View 中?
  2. 在哪里构建该表单 - 就重复而言,我更愿意创建一次表单,然后使用它来创建、编辑和查看
  3. 验证 - 我想尽可能多地重用它

XML: foods_form.xml(简化):

<form>
<field id="1" name="cheese" label="favorite cheese?" type="radio" req="1" filter="int">
<option id="1" value="1">Camembert</option>
<option id="2" value="3">Gouda</option>
</field>
<field id="2" name="beer" label="favorite beer?" type="text" req="1" filter="str" />
</form>

View : app/views/create.blade.php:

@extends('layout')
@section('content')

<form action="{{ action('FormsController@handleCreate') }}" method="post" role="form">

@foreach ($fields as $field)
<label for="{{ $field->name }}">{{ $field->label }}</label>

@if ($field->type == 'text')
<input type="text" name="{{ $field->name }}" />
@else
@foreach ($field->option as $option)
<input type="radio" name="{{ $field->name }}" value="{{ $option }}" />
@endforeach
@endif
@endforeach

<input type="submit" value="Create" />
<a href="{{ action('FormsController@index') }}">Cancel</a>
</form>
@stop

Controller : app/controllers/FormsController.php:

class TestsController extends BaseController {

public function index() {
// return some view
}

public function create() {
return View::make('create');
}

public function handleCreate() {
// validation according to XML
// save to database if valid || return to form if not valid
}
}

最佳答案

Laravel 不会帮助您从一些 XML 创建表单。

您需要使用像 SimpleXML 这样的库来解析您的 XML:您会找到一些文档 here, on php.net

从创建一个 SimpleXMLElement 开始:

$xml = new SimpleXMLElement('../path/to/your/file/foods_form.xml', 0, true);

您现在可以使用您的 $xml 对象来生成您的表单,遵循您的 XML 格式(转储您的 $xml 对象以了解结构)

只需将您的对象放在您的 View 中即可直接使用它。

要验证您的表单,您可以使用 Laravel 中的 Validation:link to the doc

关于php - 如何在 Laravel 中从 XML 构建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21271120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com