【问题标题】:Yii2 Getting user input from a formYii2 从表单获取用户输入
【发布时间】:2015-07-04 00:58:37
【问题描述】:

我正在为用户进行搜索查询以查找价格范围内的房产。我不知道 Yii2 如何获取用户输入。这是我的表单代码:

  <?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'address') ?>

<?= $form->field($model, 'minprice')->dropDownList(['£100' => '£100','£200' => '£200','£300' => '£300']) ?>

 <?= $form->field($model, 'maxprice')->dropDownList(['£100' => '£100','£200' => '£200','£300' => '£300']) ?>

<div class="form-group">
    <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>

<?php ActiveForm::end(); ?>    

这是我的模型:

class PropertiesSearch extends Properties
{

 public $minprice;
 public $maxprice;

public function search($params)
{
    $query = Properties::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
        'NoofBedrooms' => $this->NoofBedrooms,
        'type_id' => $this->type_id,
    ]);

    $query->andFilterWhere(['like', 'address', $this->address])
        ->andFilterWhere(['like', 'city', $this->city])
        ->andFilterWhere(['like', 'Postcode', $this->Postcode])
        ->andFilterWhere(['>=', 'price', $this->minprice])
        ->andFilterWhere(['<=', 'price', $this->maxprice])
        ->andFilterWhere(['=', 'option', $this->option])
        ->andFilterWhere(['like', 'description', $this->description]);
   return $dataProvider;
}
}

我在收到此错误时添加了公开的 $minprice 和 $maxprice:

获取未知属性:app\models\PropertiesSearch::minprice

但是,查询不起作用,在我的 URL 中它显示了用户输入,但查询没有通过。我会认为 ($model, 'minprice') 为该字段提供了一个名称,并且 $this-minprice 获得了该值。当我公开 $minprice = '$100' 和 $maxprice = '$300' 时,它会起作用,因此它们必须覆盖用户输入,但如果我删除它们,我会再次收到上一个错误,我做错了什么?

【问题讨论】:

  • 你能展示你在模型中的规则吗?这很可能是 load() 无法将内容分配给没有规则的属性的情况。

标签: php forms input yii2


【解决方案1】:

尝试将属性 $minprice 和 $maxprice 放在模型 app\models\Properties 并添加条件验证。

class Properties extends ActiveRecord
{

 public $minprice;
 public $maxprice;

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 2017-12-21
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2019-08-17
    • 2014-11-21
    相关资源
    最近更新 更多