Yii2在另一个视图中从控制器获取参数到_form

时间:2016-09-29 12:19:05

标签: model-view-controller yii2 parameter-passing

我在Yii有问题。

示例:

客户和Joboffers都有CRUD。我想点击Customer-Index上的一个创建按钮,该按钮将我重定向到Joboffer-Create-Form,其中我点击的员工ID可以访问。任何以正确的方式发送给我的提示?

<?php

/* @var $this yii\web\View */
/* @var $searchModel app\models\CustomersSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

use yii\helpers\Html;
use yii\helpers\Url;
use kartik\export\ExportMenu;
use kartik\grid\GridView;

$this->title = Yii::t('app', 'Customers');
$this->params['breadcrumbs'][] = $this->title;
$search = "$('.search-button').click(function(){
	$('.search-form').toggle(1000);
	return false;
});";
$this->registerJs($search);
?>
<div class="customers-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a(Yii::t('app', 'Create Customers'), ['create'], ['class' => 'btn btn-success']) ?>
        <?= Html::a(Yii::t('app', 'Advance Search'), '#', ['class' => 'btn btn-info search-button']) ?>
    </p>
    <div class="search-form" style="display:none">
        <?=  $this->render('_search', ['model' => $searchModel]); ?>
    </div>
    <?php 
    $gridColumn = [
        'id_kunde',       
        [
                'label' => 'Kunde',
                'attribute' => 'id_kunde',
                'format' => 'raw',
                'value' => function($model){
                    if($model->webseite == "") {
                    return '<div>'.$model->firma.'<br>'.$model->created_at.'<br>'.$model->contactPeople->vorname.' '.$model->contactPeople->nachname.'<br>'.$model->contactPeople->geschaeftsadresse_email_1.'<br>'.$model->contactPeople->geschaeftsadresse_mobil.'</div>';
                    } else {
                    return '<div>'.$model->firma.'<br>'.Html::a('<small class="btn btn-sm btn-primary">'.$model->webseite.'</small>', $model->webseite, ['target'=>'_blank'], ['class' => 'btn btn-danger']).'<br>'.$model->contactPeople->vorname.' '.$model->contactPeople->nachname.'<br>'.$model->contactPeople->geschaeftsadresse_email_1.'<br>'.$model->contactPeople->geschaeftsadresse_mobil.'</div>';
                    }
                    
                    },
                'filterType' => GridView::FILTER_SELECT2,
                'filter' => \yii\helpers\ArrayHelper::map(\app\models\Customers::find()->asArray()->all(), 'id_kunde', 'firma'),
                'filterWidgetOptions' => [
                    'pluginOptions' => ['allowClear' => true],
                ],
                'filterInputOptions' => ['placeholder' => 'Kunden auswählen', 'id' => 'grid-customers-search-id_ansprwechpartner']
            ],

        [
                'attribute' => 'id_mitarbeiter',
                'label' => Yii::t('app', 'Id Mitarbeiter'),
                'value' => function($model){
                    return $model->mitarbeiter->id_mitarbeiter;
                },
                'filterType' => GridView::FILTER_SELECT2,
                'filter' => \yii\helpers\ArrayHelper::map(\app\models\Employee::find()->asArray()->all(), 'id_mitarbeiter', 'id_mitarbeiter'),
                'filterWidgetOptions' => [
                    'pluginOptions' => ['allowClear' => true],
                ],
                'filterInputOptions' => ['placeholder' => 'Pers tbl employee', 'id' => 'grid-customers-search-id_mitarbeiter']
            ],
        'interner_hinweis',
        ['attribute' => 'lock', 'visible' => false],
        [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{create}',
            'contentOptions'=>['style'=>'width: 25px;'],
            'buttons' => [
                'create' => function ($url, $index, $key) {
                    return Html::a('<span class="glyphicon glyphicon-copy"></span>', Url::to(['joboffer/create', 'id' => $this->id_kunde]), ['title' => 'Create Joboffer']);
                },
            ],
        ],
        [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{save-as-new} {view} {update} {delete}',
            'buttons' => [
                'save-as-new' => function ($url) {
                    return Html::a('<span class="glyphicon glyphicon-copy"></span>', $url, ['title' => 'Save As New']);
                },
            ],
        ],
    ]; 
    ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => $gridColumn,
        'pjax' => true,
        'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container-customers']],
        // your toolbar can include the additional full export menu
        'toolbar' => [
            '{export}',
            ExportMenu::widget([
                'dataProvider' => $dataProvider,
                'columns' => $gridColumn,
                'target' => ExportMenu::TARGET_BLANK,
                'fontAwesome' => true,
                'dropdownOptions' => [
                    'label' => 'Full',
                    'class' => 'btn btn-default',
                    'itemsBefore' => [
                        '<li class="dropdown-header">Export All Data</li>',
                    ],
                ],
            ]) ,
        ],
    ]); ?>

</div>

<?php

namespace app\controllers;

use Yii;
use app\models\Customers;
use app\models\CustomersSearch;
use app\models\Joboffer;
use app\models\JobofferSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CustomersController implements the CRUD actions for Customers model.
 */
class CustomersController extends Controller
{
    
    public $param = '';
    
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['joboffer','index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new', 'add-application', 'add-contact-person', 'add-job-suggestion', 'add-joboffer'],
                        'roles' => ['@']
                    ],
                    [
                        'allow' => false
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all Customers models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CustomersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Customers model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $providerApplication = new \yii\data\ArrayDataProvider([
            'allModels' => $model->applications,
        ]);
        $providerContactPerson = new \yii\data\ArrayDataProvider([
            'allModels' => $model->contactPeople,
        ]);
        $providerJobSuggestion = new \yii\data\ArrayDataProvider([
            'allModels' => $model->jobSuggestions,
        ]);
        $providerJoboffer = new \yii\data\ArrayDataProvider([
            'allModels' => $model->joboffers,
        ]);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'providerApplication' => $providerApplication,
            'providerContactPerson' => $providerContactPerson,
            'providerJobSuggestion' => $providerJobSuggestion,
            'providerJoboffer' => $providerJoboffer,
        ]);
    }

    /**
     * Creates a new Customers model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Customers();

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->id_kunde]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Customers model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (Yii::$app->request->post('_asnew') == '1') {
            $model = new Customers();
        }else{
            $model = $this->findModel($id);
        }

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->id_kunde]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Customers model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->deleteWithRelated();

        return $this->redirect(['index']);
    }
    
    /**
     * 
     * Export Customers information into PDF format.
     * @param integer $id
     * @return mixed
     */
    public function actionPdf($id) {
        $model = $this->findModel($id);
        $providerApplication = new \yii\data\ArrayDataProvider([
            'allModels' => $model->applications,
        ]);
        $providerContactPerson = new \yii\data\ArrayDataProvider([
            'allModels' => $model->contactPeople,
        ]);
        $providerJobSuggestion = new \yii\data\ArrayDataProvider([
            'allModels' => $model->jobSuggestions,
        ]);
        $providerJoboffer = new \yii\data\ArrayDataProvider([
            'allModels' => $model->joboffers,
        ]);

        $content = $this->renderAjax('_pdf', [
            'model' => $model,
            'providerApplication' => $providerApplication,
            'providerContactPerson' => $providerContactPerson,
            'providerJobSuggestion' => $providerJobSuggestion,
            'providerJoboffer' => $providerJoboffer,
        ]);

        $pdf = new \kartik\mpdf\Pdf([
            'mode' => \kartik\mpdf\Pdf::MODE_CORE,
            'format' => \kartik\mpdf\Pdf::FORMAT_A4,
            'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
            'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
            'content' => $content,
            'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
            'cssInline' => '.kv-heading-1{font-size:18px}',
            'options' => ['title' => \Yii::$app->name],
            'methods' => [
                'SetHeader' => [\Yii::$app->name],
                'SetFooter' => ['{PAGENO}'],
            ]
        ]);

        return $pdf->render();
    }

    /**
    * Creates a new Customers model by another data,
    * so user don't need to input all field from scratch.
    * If creation is successful, the browser will be redirected to the 'view' page.
    *
    * @param type $id
    * @return type
    */
    public function actionSaveAsNew($id) {
        $model = new Customers();

        if (Yii::$app->request->post('_asnew') != '1') {
            $model = $this->findModel($id);
        }
    
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id_kunde]);
        } else {
            return $this->render('saveAsNew', [
                'model' => $model,
            ]);
        }
    }
    
    /**
     * Finds the Customers model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Customers the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Customers::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }
    
    /**
    * Action to load a tabular form grid
    * for Application
    * @author Yohanes Candrajaya <moo.tensai@gmail.com>
    * @author Jiwantoro Ndaru <jiwanndaru@gmail.com>
    *
    * @return mixed
    */
    public function actionAddApplication()
    {
        if (Yii::$app->request->isAjax) {
            $row = Yii::$app->request->post('Application');
            if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
                $row[] = [];
            return $this->renderAjax('_formApplication', ['row' => $row]);
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }
    
    /**
    * Action to load a tabular form grid
    * for ContactPerson
    * @author Yohanes Candrajaya <moo.tensai@gmail.com>
    * @author Jiwantoro Ndaru <jiwanndaru@gmail.com>
    *
    * @return mixed
    */
    public function actionAddContactPerson()
    {
        if (Yii::$app->request->isAjax) {
            $row = Yii::$app->request->post('ContactPerson');
            if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
                $row[] = [];
            return $this->renderAjax('_formContactPerson', ['row' => $row]);
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }
    
    /**
    * Action to load a tabular form grid
    * for JobSuggestion
    * @author Yohanes Candrajaya <moo.tensai@gmail.com>
    * @author Jiwantoro Ndaru <jiwanndaru@gmail.com>
    *
    * @return mixed
    */
    public function actionAddJobSuggestion()
    {
        if (Yii::$app->request->isAjax) {
            $row = Yii::$app->request->post('JobSuggestion');
            if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
                $row[] = [];
            return $this->renderAjax('_formJobSuggestion', ['row' => $row]);
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }
    
    /**
    * Action to load a tabular form grid
    * for Joboffer
    * @author Yohanes Candrajaya <moo.tensai@gmail.com>
    * @author Jiwantoro Ndaru <jiwanndaru@gmail.com>
    *
    * @return mixed
    */
    public function actionAddJoboffer()
    {
        if (Yii::$app->request->isAjax) {
            $row = Yii::$app->request->post('Joboffer');
            if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
                $row[] = [];
            return $this->renderAjax('_formJoboffer', ['row' => $row]);
        } else {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您应该使用该函数返回HTML代码

  function ($url, $model, $key) {
    // return the button HTML code
  }

这样

   [
        'class' => 'yii\grid\ActionColumn',
        'template' => '{create}',
        'contentOptions'=>['style'=>'width: 25px;'],
        'buttons' => [
            'create' => function ($url, $model, $key) {
                return Html::a('<span class="glyphicon glyphicon-copy"></span>', 
                          Url::to(['joboffer/create',
                            'id' => $model->id_kunde]), ['title' => 'Create Joboffer']);
            },
        ],
    ],