如何在Laravel中的同一表单上填充多个选择

时间:2015-02-13 14:19:53

标签: php laravel

我目前正在Laravel中开发一个表单,并且在整个MVC模型中遇到了一些问题。你看,我的应用程序处理"问题分配" (鉴于我的第一个陈述lol,有点讽刺)。所以我在我的数据库中有一个名为tblProblems的表,填写如下:

1 Problem1, cat1
2 Problem2, cat2
3 Problem3, cat1
4 Problem4, cat2
...

字段是ProblemID,ProblemName和Category。我还有一个名为tblCities的表,它基本上是一个包含两个字段的表,CityID和CityName,设置如下:

1 City1
2 City2
3 City3
...

现在我要做的就是在我的会员表上,我想设置三个"选择"控件将列出第一类和第二类的问题,并列出可用的城市。

我做的第一件事就是创建两个模型:

class Problem extends Eloquent 
{

    protected $table = 'tblProblems';
    protected $primaryKey = 'ProblemID';
    public $timestamps = false;

    public function getProblemsByCategory($cat)
    {
        return $this->where('Category', '=', $cat)->lists('ProblemName', 'ProblemID');
    }
}

class City extends Eloquent
{
    protected $table = 'tblCities';
    protected $primaryKey = 'CityID';
    public $timestamps = false;

    public function getAllCities()
    {
        return $this->orderBy('CityName', 'asc')->lists('CityName', 'CityID');
    }
}

然后,当然,我继续向战斗添加适当的控制器,如下所示:

class ProblemController extends BaseController
{
    protected $problems;

    public function __construct(Problem $problem)
    {
        $this->problems = $problem;
    }

    public function getProblemList($cat)
    {
        $problemList = $this->problems->getProblemsByCategory($cat);
        return View::make('testProblem', $problemList);
    }
}

class CityController extends BaseController
{
    protected $city;

    public function __construct(City $city)
    {
        $this->city = $city;
    }

    public function getCityList()
    {
        $cityList = $this->city->getAllCities();
        return View::make('testCity', $cityList);
    }
}

现在是我基本上陷入困境的地方。我在我的routes.php中有这个:

Route::get('member', function()
{
  return View::make('memberForm');
});

Route::get('testProblem/{cat}', ProblemController@getProblemList);
Route::get('testCity', CityController@getCityList);

如果我通过在浏览器中输入正确的URL来手动触发我的路由,我可以告诉我的代码正常工作,因为我的测试视图可以使用正确的内容访问正确的变量。问题是我无法弄清楚如何同时为我的memberForm提供所有三个列表。天哪,我甚至无法弄清楚如何将这些列表中的一个提供给我的memberForm。

任何人都可以帮助我吗?我知道解决方案可能正好盯着我,但对于我的生活,我似乎无法弄明白。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您只需要运行查询并将结果传递给表单视图,而不是为每个列表设置路由和控制器操作。像这样:

Route::get('member', 'MemberController@showForm');

class MemberController extends BaseController {

    public function showForm(){
        $problemsCat1 = $this->problems->getProblemsByCategory(1);
        $problemsCat2 = $this->problems->getProblemsByCategory(2);
        $cities = $this->city->getAllCitites();
        return View::make('memberForm', compact('problemsCat1', 'problemsCat2', 'cities'));
    }
}

然后在memberForm视图中使用它,就像任何PHP变量一样:

$problemsCat1
$problemsCat2
$cities