You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10中如何将--select zone--设为区域选择下拉框的默认加载值

Laravel 10中如何将--select zone--设为区域选择下拉框的默认加载值

我来帮你搞定这个需求,要实现页面加载时下拉框默认显示「--select zone--」,需要同时调整前端Blade模板和后端控制器的逻辑,咱们一步步来:

1. 修改前端Blade模板(zone.blade.php)

在现有的区域选项循环前,添加一个默认空值选项,同时处理它的选中状态:

<form action="{{request()->fullUrl()}}" id="zoneSubmitForm" class="pb-1">
    <div class="">
        <select class="js-select-custom min-w-200 h-35" name="zone_id" id="selectZone">
            <!-- 新增默认选项:页面加载时默认显示 -->
            <option value="" {{ !request('zone_id') ? 'selected' : '' }}>--select zone--</option>
            
            @if(count($zones)>0)
                @foreach($zones as $key =>$zone)
                    <option value="{{$zone->id}}" {{request('zone_id') == $zone->id ? "selected" :""}} data-show-shield="{{ in_array($zone->id, $safetyAlertZones) ? 'true' : '' }}">
                        {{$zone->name}}
                    </option>
                @endforeach
            @else
                <option selected disabled>{{translate("zone_not_found")}}</option>
            @endif
        </select>
    </div>
</form>

<script>
 $('#selectZone').on('change', function () {
     $('#zoneSubmitForm').submit();
 });
</script>

关键说明:

  • 默认选项的value设为空字符串,确保提交时zone_id参数为空
  • 用!request('zone_id')判断选中状态:当页面首次加载(无zone_id参数)或用户选择默认选项时,该选项会被自动选中
  • 原有区域选项的选中逻辑保持不变,确保筛选后能正确高亮选中的区域

2. 调整后端控制器逻辑(ZonemanageController)

原控制器会在无zone_id时自动选中第一个区域,这会覆盖我们的默认选项,所以要修改这部分逻辑:

public function fleetMap(?Request $request, $type = null) {
    $zones = $this->zoneService->getBy(relations: ['tripRequest.safetyAlerts']);
    $safetyAlertZones = $zones->filter(function ($zone) {
        return $zone->tripRequest->contains(function ($tripRequest) {
            return $tripRequest->safetyAlerts->where('status', PENDING)->isNotEmpty();
        });
    })->pluck('id')->toArray();
    $safetyAlertCount = $this->safetyAlertService->getBy(criteria: ['status' => PENDING])->count();

    // 替换原有的zone判断逻辑
    $zoneId = $request->get('zone_id');
    if ($zoneId) {
        $zone = $this->zoneService->findOne(id: $zoneId);
    } else {
        // 无zone_id时不再默认选择第一个区域,保持为null
        $zone = null;
    }

    $safetyAlertLatestUserRoute = $safetyAlertCount > 0 ? $this->safetyAlertService->safetyAlertLatestUserRoute() : 'javascript:void(0)';
    $safetyAlert = $this->safetyAlertService->findOneBy(criteria: ['status' => PENDING], relations: ['sentBy'], orderBy: ['created_at' => 'desc']);
    $safetyAlertUserId = $safetyAlert?->sentBy?->id ?? null;

    // Calculate center lat/lng
    $latSum = 0;
    $lngSum = 0;
    $totalPoints = 0;
    $polygons = $zone ? json_encode([formatCoordinates(json_decode($zone?->coordinates[0]->toJson(), true)['coordinates'])]) : json_encode([[]]);
    if ($zone) {
        foreach (formatCoordinates(json_decode($zone?->coordinates[0]->toJson(), true)['coordinates']) as $point) {
            $latSum += $point->lat;
            $lngSum += $point->lng;
            $totalPoints++;
        }
    }
    $centerLat = $latSum / ($totalPoints == 0 ? 1 : $totalPoints);
    $centerLng = $lngSum / ($totalPoints == 0 ? 1 : $totalPoints);

    if ($zone) {
        $data = $this->fleetCommon($type, $zone, $request->all());
        $drivers = $data['drivers'] ?? [];
        $customers = $data['customers'] ?? [];
        $markers = $data['markers'];
        return view('adminmodule::fleet-map', compact('drivers', 'customers', 'zones', 'safetyAlertZones', 'safetyAlertCount', 'safetyAlertLatestUserRoute', 'safetyAlertUserId', 'type', 'markers', 'polygons', 'centerLat', 'centerLng'));
    }
    $drivers = [];
    $customers = [];
    $markers = json_encode([[]]);
    return view('adminmodule::fleet-map', compact('drivers', 'customers', 'zones', 'safetyAlertZones', 'safetyAlertCount', 'safetyAlertLatestUserRoute', 'safetyAlertUserId', 'type', 'markers', 'polygons', 'centerLat', 'centerLng'));
}

关键说明:

  • 仅当zoneId存在且不为空时,才加载对应区域的数据
  • 无zoneId时将$zone设为null,对应页面展示无区域筛选的状态(比如全量地图数据或空状态,取决于你的业务逻辑)

3. 功能验证

修改完成后可以测试以下场景:

  • 页面首次加载:下拉框默认显示「--select zone--」
  • 选择任意区域:表单正常提交,对应区域数据加载,下拉框高亮选中项
  • 无区域数据时:下拉框显示「zone_not_found」禁用选项,符合原有逻辑
  • 选择默认选项提交:表单发送空zone_id,控制器处理无区域筛选的情况

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 09:03:00