2017-05-11 12 views
0

問題を正しく定式化するのはかなり難しいですが、ここでさらに説明しようとします。私はItem,CategorySaleモデルを持っています。 categoryItemモデルでは、手動でデータを保存しました。今度は入力フィールドとdependent drop-downを持つフォームを作成しました。異なるデータベーステーブルに格納された値を提供する新しい入力フィールドを作成するにはどうすればよいですか? Yii2

選択したカテゴリに応じて、アイテムが読み込まれます。

今、私はpriceになり、新たな入力フィールドを作成する必要があり、ユーザーがItem1選択した場合、それは提供(Feなどのデータベースから注意しなければならない - >Item1価格はで提供としてアップロードする必要があります。?ここにある

/** 
* Creates a new sale 
* 
* @return string 
*/ 
public function actionCreate() 
{ 
    $model = new Sale(); 
    $model->scenario = Sale::SCENARIO_CREATE; 
    $category = new Category(); 
    $category->scenario = Category::SCENARIO_CREATE; 
    $categoryList = ArrayHelper::map(Category::find()->all(), 'id', 'name'); 

    if ($model->load(Yii::$app->request->post())) { 
     if ($model->save()) { 
      return $this->redirect(['index']); 
     } 
    } 
    return $this->render('create', [ 
     'model' => $model, 
     'category' => $category, 
     'categoryList' => $categoryList, 
    ]); 
} 

そして:入力フィールド、私はそれを編集し、別のデータベーステーブルに格納することができ、私はそれを行う必要がありますどのように

ここ

は私SaleController actionです私のview

 <?= $form->field($category, 'id')->dropDownList($categoryList, [ 
     'id' => 'category-id', 
     'prompt' => 'Choose a category', 
    ]); ?> 

    <?= $form->field($model, 'item_id')->widget(DepDrop::classname(), [ 
     'options'=>['id'=>'item-id'], 
     'pluginOptions'=>[ 
      'depends'=>['category-id'], 
      'placeholder'=> 'Choose an item', 
      'url'=>Url::to(['/sale/subcat']) 
     ] 
    ]); ?> 

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

ありがとうございます。私はあなたがモデルからビューに入力フィールドを追加する必要があります質問

答えて

1

ファーストを理解してほしい:

<?= $form->field($model, 'item_price')->textInput([ 
     'maxlength' => true, 
     'id' => 'input-price-id' 
    ]) ?> 

その後、あなたには、いくつかのJavaScriptを追加する必要があります。

<?php 
$item_price=<<<JS 
$('#item-id').on('change', function(event) { 
     var id = $(this).attr('id'); 
     var val = $(this).val();   
     .get(
      // you must code function actionRefreshPrice wtih parameter named item_id in 
      // your controller with fetch from any table you want 
      'refresh-price',   
      {     
       item_id: val // this is id from your item 
      }, 
      function (data) { 
       // here you set a value returned from ajax call 
       // you must have an input element with id input-price-is (change as you like) 
       $('#input-price-id').val(data);    
      } 
     ); 
}); 
JS; 
$this->registerJs($item_price); 
?> 

次にあなたが追加する必要がありますコントローラの動作は次のようになります。

public function actionRefreshPrice($item_id) { 
     // I asume you have table with Price for items prices 
     $price = Price::findOne(['item_id'=>$item_id]); 
     return ($price?0:$price->price_field); 
} 

私はあなたに十分なガイドラインを与えていただきたいと思います。そして、コメントは、モデルと関係についてもっと学びます。私はあなたが少し問題を過度に考えたと思う。ハッピー学習とコーディング。

関連する問題