首页 > 解决方案 > 试图获取非对象 yii2 的属性“id”

问题描述

我正在尝试将导航栏(从 _tabs.php)渲染到index.php(查看)正在使用的控制器是ImportController.php. 该_tabs.php文件使用client_id基本上是获取客户端 ID 的函数,因此它可以适当地创建带有 ID 的 URL。我得到的问题是 Trying to get property 'id' of non-object

index.php(查看)

<?php 
use yii\bootstrap\Html;
use common\components\ActiveForm;
use common\models\User;
use common\models\Client;

$Client= null;

$this->title = 'Import Offline Data Capture data';

?>
<!-- capture partial Nav -->
<br>

<?php if(in_array(Yii::$app->user->identity->role, User::MHM_ROLES)): ?>
        <?= $this->render('/client/_tabs', ['Client' => $Client]); ?>
<?php endif; ?>
<?php if(in_array(Yii::$app->user->identity->role, User::CLIENT_ROLES)): ?>
        <?= $this->render('//client/partialNavs/appendNav', ['Client' => $Client]); ?>
<?php endif; ?>

<div class="page-header">
    <h2>Import data</h2>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-body" id="survey-import-container">

                <h4 class="text-info">Please select a file to import</h4>

                <?php if(count($ImportForm->getErrors('dataErrors'))): ?>
                    
                    <div class="alert alert-warning">
                        <p><strong>Sorry, we were unable to process your import. Please revise the following errors and try again:</strong><p><br />
                        <ul>
                            <?php foreach($ImportForm->getErrors('dataErrors') as $e): ?>
                                <li><?= $e; ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <p>The file must follow the exported template, and must be a XLSX document with a maximum of 10,000 rows.</p>

                <?php $form = ActiveForm::begin([
                    'id' => 'import-form',
                    'options' => [
                        'enctype' => 'multipart/form-data',
                        'class' => 'clearfix',
                    ]
                ]) ?>

                    <?= $form->field($ImportForm, 'importFile')->fileInput() ?><hr />

                    <?= Html::submitButton('<span class="glyphicon glyphicon-import"></span> Import & Process Data', ['class' => 'btn btn-primary col-md-6', 'id' => 'import-data-btn']); ?>

                    <?= Html::a('<span class="glyphicon glyphicon-repeat"></span> Reset', ['import/index'], ['class' => 'btn btn-link col-md-6']); ?>

                <?php ActiveForm::end() ?>
                
                <div class="alert alert-danger" style="margin-top: 20px;">Please note: This application does not store any of your imported data. Keep your original spreadsheet to avoid losing data.</div>
            </div>
        </div>
    </div>
</div>

导入控制器.PHP

<?php

namespace admin\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\UploadedFile;
use admin\components\Controller;
use admin\models\ImportForm;
use common\models\User;
use common\models\Client;


class ImportController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index'],
                        // All actions are access controlled. 
                        'roles' => [
                            User::ROLE_MHM_ADMIN,
                            User::ROLE_MHM_USER,
                            User::ROLE_CLIENT_ADMIN,
                            User::ROLE_CLIENT_USER,
                        ]
                    ],
                ],
            ],
        ];
    }
            
    public function actionIndex($client_id = null)
    {

        // Get client
        $Client = $this->getClient($client_id);

        // Ensure client exists for logged in user
        if(is_null($Client)) {
            throw new BadRequestHttpException('This page does not exist.');
        }

        $ImportForm = new ImportForm;
        
        // Form posted, validate
        if(Yii::$app->request->isPost) {
            $ImportForm->importFile = UploadedFile::getInstance($ImportForm, 'importFile');

            // Process upload
            $ImportForm->upload();
        }

        return $this->render('index', array(
            'ImportForm' => $ImportForm,
        ));
    }

    public function actionRenderSuccess()
    {
        return $this->renderPartial('_success');
    }

    private function getClient($id, $restriction = null)
    {
        if(Yii::$app->user->identity->client_id)
        {
            $id = Yii::$app->user->identity->client_id;
        }

        $ClientQuery = Client::find()
            ->andWhere(['id' => $id]);

        if ($restriction == 'patronbase') {
            $ClientQuery->andWhere(['license_type' => Client::LICENSE_PATRONBASE]);

        } else if ($restriction == 'live') {
            $ClientQuery->andWhere(Client::LIVE_OR_UPGRADING_CONDITION);
        }

        $Client = $ClientQuery->one();

        if(is_null($Client))
        {
            throw new NotFoundHttpException('');
        }

        return $Client;
    }
}

_tabs.php

<?php

use yii\bootstrap\Html;
use common\models\Client;
use common\models\User;
use common\models\SurveyInstance;
use common\models\Consent;
use yii\bootstrap\Tabs;
use yii\bootstrap\Nav;


if (Yii::$app->user->isGuest) return;

$getRoute = function($route, $clientParamName, $otherParams = []) use ($Client)
{
    $routeParams = [$route];

    
    if (!isset(Yii::$app->user->identity->client_id)) {
        $routeParams[$clientParamName] = $Client->id;
    }

    return array_merge($routeParams, $otherParams);
};

$route = Yii::$app->controller->module->requestedRoute;

$mhmOrClientAdmin = in_array(Yii::$app->user->identity->role, [User::ROLE_MHM_ADMIN, User::ROLE_MHM_USER, User::ROLE_CLIENT_ADMIN]);
$mhmUser = in_array(Yii::$app->user->identity->role, User::MHM_ROLES);

$urlsForConsentSurveyTypes = Consent::getUrlForSurveyTypes();

$items = [

            [
                'label' => 'Checkout / Enrich',
                'url' =>  $getRoute('dashboard/mhm-rels-dashboard', 'client_id'),
                'active' => in_array($route, [
                    'dashboard/mhm-rels-dashboard',
                    'survey-instance/api-logs',
                    'client/activity',
                    'client/update',
                    'client/api-settings'
                ]) || ($route =='consent/index' && Yii::$app->request->get('type')=='cs-tag-tool-consent'),
                'encode' => false,
                'visible' => $Client->isFullOrUpgrading,
            ],
            [
                'label' => 'Checkout / Enrich',
                'url' =>  $getRoute('dashboard/patronbase-dashboard', 'client_id'),
                'active' => in_array($route, [
                    'dashboard/mhm-rels-dashboard',
                    'dashboard/patronbase-dashboard',
                    'survey-instance/api-logs',
                    'client/activity',
                    'client/update',
                    'client/api-settings',
                    'client/patronbase-settings'
                ]) || ($route =='consent/index' && Yii::$app->request->get('type')=='cs-tag-tool-consent'),
                'encode' => false,
                'visible' => $Client->license_type === Client::LICENSE_PATRONBASE,
            ],
            [
                'label' => 'Capture',
                'url' => $getRoute('dashboard/capture-dashboard', 'client_id'),
                'active' => in_array($route, [
                    'dashboard/capture-dashboard',
                    'client/survey-settings',
                    'consent/create',
                    'consent/update',
                    'question/index',
                    'client/legal',
                    'question/create',
                    'question/update'
                ]) || ($route =='consent/index' && Yii::$app->request->get('type')=='capture-consent'),
                'encode' => false,
            ],
            [
                'label' => 'Append',
                'url' => $getRoute('dashboard/append-dashboard', 'client_id'),
                'active' => in_array($route, [
                    'dashboard/append-dashboard',
                     'client/append-settings',
                     'import/index'
                ]),
                'encode' => false,

            ],

//Info
            [
                'label' => '<span class="glyphicon glyphicon-stats"></span> Info',
                'options' => ['class' => 'pull-right'],
                'active' => in_array($route, [
                    'client/stats',
                    'client/survey-urls',
                ]),
                'encode' => false,
                'items' => [
                    [
                        'label' => '<span class="glyphicon glyphicon-stats"></span> Stats',
                        'url' =>  $getRoute('client/stats', 'client_id'),
                        'active' => in_array($route, ['client/stats',]),
                        'encode' => false,
                        'visible' => $mhmOrClientAdmin,
                    ],
                    [
                        'label' => '<span class="glyphicon glyphicon-file"></span>  Guides',
                        'url' => '/guides/' . $Client->hash,
                        'encode' => false,
                        'linkOptions' => [ 'target' => '_blank'],
                        'visible' => $Client->isFullOrUpgrading,
                    ],
                    [
                        'label' => '<span class="glyphicon glyphicon-link"></span> Survey URLs',
                        'url' => $mhmUser ? ['client/survey-urls', 'client_id' => $Client->id] : ['client/survey-urls'],
                        'encode' => false,
                    ],
                ],
            ],
    

//Settings
            [
                'label' => '<span class="glyphicon glyphicon-cog"></span> Account settings',
                'options' => ['class' => 'pull-right'],
                'active' => in_array($route, [
                    'client/anonymisation',
                    'contact/index',
                    'contact/update',
                    'contact/create',
                    'contact/delete',
                    'user/index',
                    'user/create-update',
                ]),
                'encode' => false,
                'items' => [
                    [
                        'label' => '<span class="glyphicon glyphicon-erase"></span> Anonymisation',
                        'url' => $getRoute('client/anonymisation', 'id'),
                        'active' => in_array($route, ['client/anonymisation']),
                        'encode' => false,
                    ],
                    [
                        'label' => '<span class="glyphicon glyphicon-envelope"></span> Email List',
                        'url' =>  $getRoute('contact/index', 'client_id'),
                        'active' => in_array($route, [
                            'contact/index',
                            'contact/update',
                            'contact/create',
                            'contact/delete',
                        ]),
                        'encode' => false,
                    ],
                    [
                        'label' => '<span class="glyphicon glyphicon-user"></span> Users <span class="badge">'.count($Client->clientUsers).'</span>',
                        'url' =>  $getRoute('user/index', 'client_id'),
                        'active' => in_array($route, [
                            'user/index',
                            'user/create-update',
                        ]),
                        'encode' => false,
                        'visible' => $mhmOrClientAdmin,
                        
                    ],
                ],
            ],


];


echo Nav::widget([
    'options' => [
        'class' => 'nav nav-pills',
        'id'=>'nav-bar',
        
    ],
    'items' => $items,
]);

?>

<style> 
#nav-bar {
    background-color: aliceblue
}
</style>

标签: phpyiiyii2

解决方案


希望这个答案会有所帮助:

return $this->render('index', array(
            'ImportForm' => $ImportForm,
            'Client' => $Client
        ));

专注于 ImportController 上的 Index 操作。我想你忘了把它$Client传给index.php. $Client= null;此外,在您的视图文件 (index.php) 中删除$this->title


推荐阅读