Laravel编辑页中带输入框的下拉框如何获取旧值?
解决Laravel编辑页面下拉框选中回显与自定义URL输入框显示问题
咱们一步步来搞定你遇到的两个核心问题:下拉框选中值不回显,以及自定义URL输入框的显示逻辑异常。
一、修复下拉框选中值回显
你的视图代码里有两处小问题导致选中状态不对,咱们直接修正:
- 下拉框的
name是page,但你用了old('page1', $items->content_id),参数名匹配错误; - 当
content_id是自定义URL时,没有让Add Custom URL选项自动选中。
修改后的下拉框代码如下:
<div class="form-group"> <label for="page" class="labelclass">Pages</label> <select class="form-control" name="page" id="pageone"> <option value="0">Select page</option> @foreach($pages as $page) <option value="{{$page->id}}" @if(old('page', $items->content_id) == $page->id) selected @endif> {{$page->title}} </option> @endforeach <option disabled>---</option> <option value='NewField' @if(!$pages->pluck('id')->contains(old('page', $items->content_id))) selected @endif> Add Custom URL </option> </select> <input class="form-control" type="text" name="page1" id="page" placeholder="https://" value="{{old('page1', $items->content_id)}}" style="display: none; width: 450px; margin-top: 5px;" /> </div>
这里用$pages->pluck('id')->contains(...)判断当前content_id是否是已存在的页面ID,如果不是,自动选中Add Custom URL选项;同时输入框的value用old('page1', $items->content_id),确保表单提交错误时能保留用户输入的自定义URL。
二、修复输入框的显示逻辑
你原来的JS只监听了下拉框的change事件,但页面刚加载时如果已经是自定义URL的情况,输入框不会自动显示。咱们补充初始化逻辑:
修改后的JS代码:
<script type="text/javascript"> $(function() { // 页面加载时初始化输入框状态 @if(!$pages->pluck('id')->contains($items->content_id)) $("#page").show(); @else const initialValue = $("#pageone").val(); $("#page").toggle(initialValue === "NewField"); @endif // 下拉框切换时更新输入框显示状态 $("#pageone").change(function() { const dropValue = $(this).val(); $("#page").toggle(dropValue === "NewField"); }); }); </script>
通过Blade模板在页面渲染时直接判断并处理自定义URL的显示情况,确保打开编辑页面时输入框状态完全符合预期。
三、优化控制器的验证与更新逻辑
你当前的验证规则没有对自定义URL做校验,用户选了Add Custom URL但不输入内容也能提交,咱们补上这个逻辑:
修改控制器update方法里的验证规则:
$this->validate($request,[ 'name'=>'required', 'status'=>'required|not_in:2', 'page'=>'required|not_in:0', 'page1'=>'required_if:page,NewField|url' // 选中自定义URL时,必须输入有效网址 ]);
然后更新content_id的逻辑可以简化:
$items->content_id = $request->page === 'NewField' ? $request->page1 : $request->page;
四、额外注意事项
- 确保数据库的
content_id字段是字符串类型(比如varchar),因为它既存储数字ID又存储URL字符串,避免类型转换异常; - 测试表单提交错误的场景(比如输入无效URL),确认
old()函数能正确回显之前的输入内容。
内容的提问来源于stack exchange,提问作者Neeraj Tangariya
相关产品推荐
相关产品推荐

