以yii2的形式获取多个表中的值数据

时间:2016-11-18 10:26:09

标签: php yii yii2 dropdown

我的项目存在问题。在我提出之前,我想向您解释具体的数据库和我的逻辑程序。

我有3个表,表是anak_asuh(主键kode_anak_asuh,外键kode_calon),calon(主键kode_calon)和perkembangan(主键tanggal,外键kode_anak_asuh)。表calon与anak_asuh的关系是一对一的,对于关系表,anak_asuh与perkembangan的关系是一对多。

然后我创建了用于保存在perkembangan表中的表单。但是当我使用下拉列表获得表calon中的名称calon值时,我遇到了问题。

问题是如何通过一个表获取价值数据? 详细我的问题是当我在表calon中获得值名称calon时,但在它通过表anak_asuh之前。我不能那样做,请举个例子。

在视图中:

<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\helpers\Url;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use kartik\widgets\Select2;
use yii\jui\AutoComplete;
use yii\web\JsExpression;
use app\models\Calon;
use app\models\Perkembangan;
use app\models\AnakAsuh;
use kartik\widgets\DatePicker;

$this->title = 'Form Perkembangan Anak Asuh';

?>

<h1 align="center">Entry Perkembangan Anak Asuh</h2>
<?php
echo "&nbsp";
echo "&nbsp";
?>

<?php $form = ActiveForm::begin([
    'layout' => 'horizontal', 
    'id' => 'create-form',
    'fieldConfig' => [
        'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
            'horizontalCssClasses' => [
            'label' => 'col-sm-4',
            'offset' => 'col-sm-offset-4',
            'wrapper' => 'col-sm-8',
            'error' => '',
            'hint' => '',
            'button' => 'col-sm-4'
        ],
    ],
    ]); 
?>

<div class="panel panel-default"> 

<div class="panel-heading"><b><h4 align="center">Form Perkembangan Anak Asuh</h4></b></div>

<?php if (Yii::$app->session->hasFlash('success')): ?>
  <div class="alert alert-success alert-dismissable">
  <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
  <h4><i class="icon fa fa-check"></i>Informasi!</h4>
  <?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>

<div class="panel-body">  

<table class="table table-striped"> 

<?php 
    echo $form->field($perkembangan, 'kode_anak_asuh')->dropDownList(
        ArrayHelper::map(AnakAsuh::find()->all(), 'kode_anak_asuh', 'kode_anak_asuh'),
        [
            'prompt' => 'Pilih',
        ]);
?>

<?php 
    echo $form->field($calon, 'nama_calon')->textInput(['style'=>'width:350px', 'disabled' => true]);
?>

<?= $form->field($perkembangan, 'tanggal')->widget(DatePicker::classname(), [
    'options' => [
        'id' => 'tanggal',
        'style' => 'width:350px',
        'disabled' => true
    ],
    'type' => DatePicker::TYPE_INPUT,
    'language' => 'id',
    'pluginOptions' => [
        'autoclose'=>true,
        ]
    ]); 
?>

<?= $form->field($perkembangan, 'kategori')->dropDownList(['Akademis' => 'Akademis', 'Kesehatan' => 'Kesahatan', 'Lain-lain' => 'Lain-lain'],
    ['prompt'=>'Pilih', 'style' => 'width:350px']) ?>

<?= $form->field($perkembangan, 'keterangan')->textArea(['style' => 'width:350px']) ?>

<div class="form-group">
    <div class="col-sm-offset-4">
<?= Html::submitButton('Simpan', ['class' => 'btn btn-primary']) ?>
<?php
echo "&nbsp";
echo "&nbsp";
echo Html::a('Keluar', ['/'], ['class' => 'btn btn-success']);
?> 
    </div>
</div>

</table>

</div>

</div> <!-- /panel -->

</div> <!-- /container -->

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

<?php
$script = <<< JS
$('input#calon-alamat').change(function() {
        var kodeId = $(this).val();
        $.get('get-calon', { kodeId : kodeId }, function(data) {
            var data = $.parseJSON(data);
            $('#calon-nama_calon').attr('value',data.nama_calon);
        });  
    });
JS;
$this->registerJs($script);
?>  

<?php
$script = <<< JS
$("#perkembangan-kode_anak_asuh").change(function() {
    var terpilih = $(this).find("option:selected").text();
    $("#create-form :select[name='kode_calon']").val(terpilih);
JS;
$this->registerJs($script);
?>     

在控制器中:

namespace app\controllers;

use Yii;
use app\models\Perkembangan;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\models\Calon;
use yii\helpers\Json;

class PerkembanganController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create'],
                'rules' => [
                    [
                        'actions' => ['create'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->redirect(['create']);
    }

    public function actionGetCalon($kodeId)
    {
        $calon = Calon::findOne($kodeId);
        echo Json::encode($calon);
    }

    public function actionGetAnak($kodeAnak)
    {
        $anak = Anak::findOne($kodeAnak);
        echo Json::encode($anak);
    }

    public function actionCreate()
    {
        $perkembangan = new \yii\base\DynamicModel(['kode_anak_asuh','kode_calon',]);
        $perkembangan->addRule(['kode_anak_asuh'],'string');
        $perkembangan->addRule(['kode_calon'],'string');

        $perkembangan = new Perkembangan();
        if (!$perkembangan) {
            throw new NotFoundHttpException("The perkembangan was not found.");
        }

        $calon = new Calon();
        if (!$calon) {
            throw new NotFoundHttpException("The calon has perkembangan.");
        }

        // Display datetime in form and save to table
        $perkembangan->tanggal = date('Y-m-d H:i:s');

        if ($perkembangan->load(Yii::$app->request->post()) && $perkembangan->save()) {
                Yii::$app->session->setFlash('success', 'Data berhasil disimpan!');
                return $this->redirect(['index']);
                return $this->refresh();
        } 

        return $this->render('create', [
            'perkembangan' => $perkembangan,
            'calon' => $calon,
        ]);

    }
}

模特:

namespace app\models;

use Yii;
use app\models\Perkembangan;
use yii\db\ActiveRecord;
use app\models\AnakAsuh;

class Perkembangan extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%perkembangan}}';
    }

    public function rules()
    {
        return [
            [['kode_anak_asuh', 'keterangan', 'kategori'], 'required'],
            [['tanggal'], 'safe'],
        ];
    }

    public function attributeLabels()
    {
        return [
            [
                'kode_anak_asuh' => 'Kode Anak Asuh',
                'tanggal' => 'Tanggal Entry Perkembangan',
                'keterangan' => 'Keterangan',
                'kategori' => 'Kategori',
                ],
        ];    
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAnak()
    {
        return $this->hasOne(AnakAsuh::className(), ['tanggal' => 'kode_anak_asuh']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCalon()
    {
        return $this->hasOne(Calon::className(), ['tanggal' => 'kode_calon']);
    }
}

1 个答案:

答案 0 :(得分:0)

您是否也可以发布模型和搜索模型,因为连接和关系可以在模型中完成而不是在控制器中完成。也许你可以看here。在此链接中,您将看到相关表格中的pasing数据是如何完成的,因此您可以进行小的更改并在应用程序中使用它。我有这样一个dependend下拉列表baset,并能够在客户设置app条件后传递所有数据。