【问题标题】:Laravel dynamic dropdown country and stateLaravel 动态下拉国家和州
【发布时间】:2017-12-17 00:35:59
【问题描述】:

我正在尝试制作两个下拉菜单。这些是从我的数据库中选择的国家和州。我的问题是不知道如何制定国家必须依赖国家的条件。当我选择 [countryname] 时,它会在我的下拉列表中提供不同的州名选择。到目前为止,我到目前为止所做的一切。

AdminController.php

public function user_register()
    {
        $countryname = DB::table('countries')
            ->get();
        $statename = DB::table('states')
            ->get();

        $title = ucwords(Lang::get('constants.user') . ' ' . Lang::get('constants.register')); 
        return View::make('register.user_register')
            ->with('title', $title)
            ->with('page', 'user_register')
            ->with('countryname', $countryname)
            ->with('statename', $statename)
    }

user_register.blade.php

<select class="form-control" id="countries" name="countries">
    <option value="">Please select</option>
        <?php foreach ($countryname as $key=>$countryname): ?>
        <option value="<?php echo $countryname->sortname; ?>"<?php
         if (isset($countries) && Input::old('countries') == $countryname->sortname) 
         {
             echo 'selected="selected"';
         }
         ?>>
         <?php  echo $countryname->sortname ." - ". $countryname->name  ; ?>
    </option>
    <?php endforeach; ?>
</select>


<select class="form-control" id="states" name="states">
    <option value="">Please select</option>
        <?php foreach ($statename as $key=>$statename): ?>
        <option value="<?php echo $countryname->name; ?>" <?php
        if (isset($states) && Input::old('states') == $statename->name)
        {
            echo 'selected="selected"';
        }
        ?>>
        <?php  echo $statename->name; ?></option>
        <?php endforeach; ?>
</select>

在我的数据库中

表格: 国家

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| country_id| int(11)      | NO   | PRI | NULL    | auto_increment |
| sortname  | varchar(3)   | NO   |     | NULL    |                |
| name      | varchar(150) | NO   |     | NULL    |                |
| phonecode | int(11)      | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

表格: 状态

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   |     | NULL    |                |
| country_id | int(11)          | NO   |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

【问题讨论】:

  • 您想在选择国家时更新州(仅显示与该国家相关的州)吗?如果是,您将需要 javascript。
  • 这应该用javascript来完成。将国家/州数据作为变量传递,并在国家/地区选择上使用 onChange() 更改州。
  • 另外,如果您使用刀片,请不要使用&lt;?php if (...,只需使用@if (...。请参阅文档laravel.com/docs/5.4/blade
  • @tompec(仅显示与该国家相关的州)是的先生,我确实想让它成为动态下拉列表(更改时)。先生,您能帮我看看我将如何进行编码吗? :( 也是编码而不是html标签的正确方法,例如:
  • 是的 @aynber 先生,感谢您的回复我遇到了问题我将如何进行编码... :( 在 laravel 中

标签: php mysql database laravel dropdown


【解决方案1】:

我想更新这篇文章,我已经解决了我的问题。我只是想为社区分享这个解决方案:)

我刚刚在 user_register.blade.php 中为此添加了一些 ajax 代码:

<div class="form-group">
    <label for="title">Select Country:</label>
    <select name="country" class="form-control">
        <option value="">--- Select country ---</option>
        @foreach ($countries as $key => $value)
            <option value="{{ $value }}">{{ $value }}</option>
        @endforeach
    </select>
</div>
<div class="form-group">
    <label for="title">Select state:</label>
    <select name="state" class="form-control">
    </select>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country"]').on('change', function() {
    var countryID = $(this).val();
        if(countryID) {
        $.ajax({
            url: '/admin/user_register/ajax/'+encodeURI(countryID),
            type: "GET",
            dataType: "json",
            success:function(data) {
            $('select[name="state"]').empty();
            $.each(data, function(key, value) {
                $('select[name="state"]').append('<option value="'+ value +'">'+ value +'</option>');
                });
            }
        });
        }else{
        $('select[name="state"]').empty();
          }
       });
    });
</script>

我根据国家 ID 指定了从哪里获取数据并将传递给我的 routes.php:

url: '/admin/user_register/ajax/'+encodeURI(countryID),

在我的routes.php中:

    //dynamic dropdown country and states
Route::get('/admin/user_register/ajax/{country_id}',array('as'=>'user_register.ajax','uses'=>'AdminController@stateForCountryAjax'));

最后我在 AdminController.php 中添加了一些代码来做什么:

public function stateForCountryAjax($country_name)
{
    $country_name = urldecode($country_name);
    $country_id = $this->_stateCountryIDForCountryName($country_name);
    $states = DB::table("states")
                ->where("country_id",$country_id)
                ->lists('name','id');
    return json_encode($states);
}

private function _stateCountryIDForCountryName($country_name)
{
    return DB::table('countries')->where("name","$country_name")->first()->country_id;
}

这种方法对我有用。我现在能够根据国家 ID 动态更新下拉选项(状态)。

【讨论】:

    【解决方案2】:

    下面是如何在 Laravel 中进行动态下拉:

    您可以在此处查看其工作原理的演示 https://www.dronejobs.co/

    免责声明:我没有对此进行测试,但它应该可以工作。欢迎评论,我会更新?

    app/Http/Controllers/HomeController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use App\{Country, State};
    
    class HomeController extends Controller
    {
        public function index()
        {
            return view('home', [
                'countries' => Country::all(),
                'states' => State::all(),
            ]);
        }
    }
    

    resources/views/home.blade.php

    <select name="country">
        @foreach ($countries as $country)
            <option value="{{ $country->id }}">{{ $country->name }}</option>
        @endforeach
    </select>
    
    <select name=“state”>
        @foreach ($states as $state)
            <option value="{{ $state->id }}">{{ $state->name }}</option>
        @endforeach
    </select>
    
    <script>
        $(function() {
            $('select[name=country]').change(function() {
    
                var url = '{{ url('country') }}' + $(this).val() + '/states/';
    
                $.get(url, function(data) {
                    var select = $('form select[name= state]');
    
                    select.empty();
    
                    $.each(data,function(key, value) {
                        select.append('<option value=' + value.id + '>' + value.name + '</option>');
                    });
                });
            });
        });
    </script>
    

    app/Country.php

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Country extends Model
    {   
        public function states()
        {
            return $this->hasMany('App\State');
        }
    

    app/State.php

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    Class State extends Model
    {   
        public function country()
        {
            return $this->belongsTo('App\Country');
        }
    

    路由/web.php

    Route::get('country/{country}/states', 'CountryController@getStates');
    

    app/Http/Controllers/CountryController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Country;
    
    class CountryController extends Controller
    {
        public function getStates(Country $country)
        {
            return $country->states()->select('id', 'name')->get();
        }
    }
    

    【讨论】:

    • 请让我知道它有效,如果是这种情况,请将问题标记为已解决;)
    • 是否有任何更短的方法可以从数据库中检索数据并传入我的下拉列表?比如:$countryname = DB::table('countries')->get(); .然后为参数(onchange条件)添加一些js代码?
    猜你喜欢
    • 2010-11-17
    • 2017-08-27
    • 2019-05-25
    • 1970-01-01
    • 2011-01-07
    • 2011-01-21
    • 2013-06-28
    • 1970-01-01
    • 2012-05-06
    相关资源
    最近更新 更多