I am new to yii2 and I cannot find a solution please help mi
controller
class ReporteController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
],
'rules' => [
[
'actions' => ['estudiantes'],
'allow' => true,
'roles' => ['#'],
],
],
];
}
public function actionEstudiantes()
{
$user_id = Yii::$app->user->identity->id;
//echo $user_id;
$userdistrito = \common\models\UserDistrito::find()->where(['user_id'=>$user_id])->one();
if (empty($userdistrito)) {
$dataProvider = new ActiveDataProvider([
'query' => Estudiante::find()
]);
}else{
$dist = $userdistrito->distrito_id;
$condition = "instructorbiblico_id in (SELECT id FROM instructorbiblico where iglesia_id in (SELECT id FROM iglesia WHERE distrito_id = $dist))";
$dataProvider = new ActiveDataProvider([
'query' => Estudiante::find()->where($condition),
]);
}
return $this->render('estudiantes', [
'dataProvider' => $dataProvider,
]);
}
...
views in backend\views\reporte
estudiantes.php
<?php
use yii\helpers\Html;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\EstudianteSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Estudiantes');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="estudiante-index">
</div>
<div>
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
//'id',
//'nombres',
[
'attribute' => 'iglesia',
'label' => 'Iglesia',
'value' => 'instructorbiblico.unidadaccion.iglesia.nombre',
],
//'iglesia.nombre',
[
'attribute' => 'unidadaccion',
'label' => 'Unidad Accion',
'value' => 'instructorbiblico.unidadaccion.nombre',
],
[
'attribute' => 'Instructor ',
'label' => 'Instructor',
'value' =>'instructorbiblico.nombre',
],
'nombres',
'celular',
'edad',
[
'attribute' => 'sexo',
'label' => 'sexo',
'value' => function($model){
if ($model->sexo == 0){
return 'M';
}
if ($model->sexo == 1){
return 'F';
}
else {
return '';
}
},
],
[
'attribute' => 'estado',
'label' => 'Estado',
'value' => function($model){
if ($model->estado == 0){
return 'Inactivo';
}
if ($model->estado == 1){
return 'Activo';
}
else {
return '';
}
},
],
];
?>
</div>
<div>
<?php
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'exportConfig' => [
ExportMenu::FORMAT_TEXT => false,
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_EXCEL => false,
ExportMenu::FORMAT_PDF => [
'pdfConfig' => [
'methods' => [
'SetTitle' => 'Grid Export - Krajee.com',
'SetSubject' => 'Generating PDF files via yii2-export extension has never been easy',
'SetHeader' => ['Krajee Library Export||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
'SetAuthor' => 'Kartik Visweswaran',
'SetCreator' => 'Kartik Visweswaran',
'SetKeywords' => 'Krajee, Yii2, Export, PDF, MPDF, Output, GridView, Grid, yii2-grid, yii2-mpdf, yii2-export',
]
]
],
],
'dropdownOptions' => [
'label' => 'Export All',
'class' => 'btn btn-outline-secondary'
]
]) . "<hr>\n".
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
]);
?>
</div>
1 error
yii\web\HttpException:404 exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "reporte/estudiantes".' in /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/base/Module.php:537
Stack trace:
#0 /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('reporte/estudia...', Array)
#1 /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /home/sebdcom/public_html/proy/backend/web/index.php(17): yii\base\Application->run()
#3 {main}
Next exception 'yii\web\NotFoundHttpException' with message 'Página no encontrada.' in /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/web/Application.php:115
Stack trace:
#0 /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /home/sebdcom/public_html/proy/backend/web/index.php(17): yii\base\Application->run()
#2 {main}
2 error
yii\web\HttpException:404 exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "css/Bootstrap.min.css".' in /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/base/Module.php:537
Stack trace:
#0 /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('css/Bootstrap.m...', Array)
#1 /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /home/sebdcom/public_html/proy/backend/web/index.php(17): yii\base\Application->run()
#3 {main}
Next exception 'yii\web\NotFoundHttpException' with message 'Página no encontrada.' in /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/web/Application.php:115
Stack trace:
#0 /home/sebdcom/public_html/proy/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /home/sebdcom/public_html/proy/backend/web/index.php(17): yii\base\Application->run()
#2 {main}
Related
I am working on an application with user platform shown below:
Controller
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Model
public function attributeLabels()
{
return [
'user_id' => Yii::t('app', 'User ID'),
'user_login_id' => Yii::t('app', 'User Login ID'),
'user_password' => Yii::t('app', 'Password'),
'user_type' => Yii::t('app', 'User Type'),
'is_block' => Yii::t('app', 'Block Status'),
'is_confirmed' => Yii::t('app', 'Block Status'),
'confirmed_at' => Yii::t('app', 'Date Confirmed'),
'created_at' => Yii::t('app', 'Created At'),
'created_by' => Yii::t('app', 'Created By'),
'updated_at' => Yii::t('app', 'Updated At'),
'updated_by' => Yii::t('app', 'Updated By'),
'current_pass' => Yii::t('app','Current Password'),
'new_pass' => Yii::t('app','New Password'),
'retype_pass' => Yii::t('app', 'Retype Password'),
'admin_user' => Yii::t('app', 'Admin Username'),
'create_password' => Yii::t('app', 'Password'),
'confirm_password' => Yii::t('app', 'Confirm Password'),
];
}
View
<?php Pjax::begin() ?>
<div class="box box-primary">
<div class="box-body">
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout' => "{items}\n{pager}",
'columns' => [
'user_login_id',
'user_type',
[
'attribute' => 'created_at',
'value' => function ($data) {
return (!empty($data->created_at) ? Yii::$app->formatter->asDate($data->created_at) : ' - ');
},
],
[
'header' => Yii::t('urights', 'Confirmation'),
'value' => function ($model) {
if (!$model->is_confirmed) {
return '<div class="text-center"><span class="text-success">' . Yii::t('urights', 'Confirmed') . '</span></div>';
} else {
return Html::a(Yii::t('urights', 'Confirm'), ['confirm', 'id' => $model->user_id], [
'class' => 'btn btn-xs btn-success btn-block',
'data-method' => 'post',
'data-confirm' => Yii::t('urights', 'Are you sure you want to confirm this user?'),
]);
}
},
'format' => 'raw',
],
[
'header' => Yii::t('urights', 'Block status'),
'value' => function ($model) {
if ($model->is_block) {
return Html::a(Yii::t('urights', 'Unblock'), ['block', 'id' => $model->user_id], [
'class' => 'btn btn-xs btn-success btn-block',
'data-method' => 'post',
'data-confirm' => Yii::t('urights', 'Are you sure you want to unblock this user?'),
]);
} else {
return Html::a(Yii::t('urights', 'Block'), ['block', 'id' => $model->user_id], [
'class' => 'btn btn-xs btn-danger btn-block',
'data-method' => 'post',
'data-confirm' => Yii::t('urights', 'Are you sure you want to block this user?'),
]);
}
},
'format' => 'raw',
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}',
],
],
]);
?>
</div>
</div>
<?php Pjax::end() ?>
As shown in the diagram, when I click on Confirm (Green Button), it shown disable the button and turn it to Confirmed. Then set is_confimred to 0 (zero).
Also, if I click on Block (Red Button), it should change the button caption to unblock and set is_block to 0.
However, I am not getting result, but I have the page shown below:
How do I resolve it?
You should add toggle functions for both confirm and block to the controller.
public function actionConfirm($id)
{
if(($model = User::findOne($id)) !== null) {
$model->is_confirmed = $model->is_confirmed ? false : true;
$model->update();
}
return $this->redirect(['index']);
}
public function actionBlock($id)
{
if(($model = User::findOne($id)) !== null) {
$model->is_block = $model->is_block ? false : true;
$model->update();
}
return $this->redirect(['index']);
}
When I try to access app it get error after use yii2-authclient.
I follow Facebook Authentication using Yii2 authclient
All is setup, but this error occur:
Setting unknown property: yii\web\Application::authClientCollection
My frontend/main.php is:
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
// 'urlManager' => [
// 'enablePrettyUrl' => true,
// 'showScriptName' => false,
// 'rules' => [
// ],
// ],
],
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId' => '2061735130522390',
'clientSecret' => '2f302dc7358730820c091ca4444afbae',
'attributeNames' => ['name', 'email', 'first_name', 'last_name'],
],
],
],
My site controller is:
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public $successUrl = "success";
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* {#inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'successCallback'],
],
];
}
public function successCallback($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
$user = User::find()->where(['email'=>$userAttributes['email']])->one();
if (!empty($user))
{
Yii::$app->user->login($user);
}
else{
$session = Yii::$app->session;
$session['attribute'] = $userAttributes;
$this->successUrl = Url::to(['signup']);
}
die(print_r($userAttributes));
// do some thing with user data. for example with $userAttributes['email']
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
.
.
.
}
login.php is:
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div style="color:#999;margin:1em 0">
If you forgot your password you can <?= Html::a('reset it', ['site/request-password-reset']) ?>.
</div>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<p>OR</p>
<?= yii\authclient\widgets\AuthChoice::widget([
'baseAuthUrl' => ['site/auth']
]) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
Your config is incorrect, authClientCollection config should be inside of components array - in your case it is outside of it. You should move authClientCollection element one line up and change this:
],
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId' => '2061735130522390',
'clientSecret' => '2f302dc7358730820c091ca4444afbae',
'attributeNames' => ['name', 'email', 'first_name', 'last_name'],
],
],
],
To this:
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId' => '2061735130522390',
'clientSecret' => '2f302dc7358730820c091ca4444afbae',
'attributeNames' => ['name', 'email', 'first_name', 'last_name'],
],
],
],
],
Fighting form last 3 days not able to find what exactly problem is. When after search I export data it export all data, expected to export search result.Please help!
My Controller
public function actionAdvancesearch()
{
$searchModel = new CandidateSearch();
$model = new Candidate();
$dataProvider1 = $searchModel->search(Yii::$app->request->queryParams);
if(Yii::$app->request->post()){
$postedData=Yii::$app->request->post();
$searchModel = new CandidateSearch();
$dataProvider1 = $searchModel->searchAdvanced();
return $this->render('candidateAdvSearch', ['dataProvider1' => $dataProvider1,
'model' => $model ,
'searchModel' => $searchModel,
'posted'=>"posted",
'postedData'=>$postedData]);
}else{
return $this->render('candidateAdvSearch', ['searchModel' => $searchModel, 'model' => $model, 'dataProvider1' => $dataProvider1]);
}
}
View
Pjax::begin();
if($dataProvider1){
$gridColumns = [
[
'attribute'=>'HRMS_candidateID',
'label'=>'Candidate ID',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateID;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateFirstName',
'label'=>'Candidate FirstName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateFirstName;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateLastName',
'label'=>'Candidate LastName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateLastName; },
'format'=>'raw'
],
];
$fullExportMenu = ExportMenu::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'target' => ExportMenu::TARGET_POPUP,
'fontAwesome' => true,
'pjaxContainerId' => 'kv-pjax-container',
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]);
// Generate a bootstrap responsive striped table with row highlighted on hover
echo GridView::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container']],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Candidate Advanced Search</h3>',
],
'toolbar' => [
$fullExportMenu,
],
'striped'=>true,
'hover'=>true,
'responsive'=>true,
'hover'=>true,
'resizableColumns'=>true,
'persistResize'=>false,
'columns' => $gridColumns,
]);
}
Pjax::end();
i have model from "feedbackmodel" :
public function search($params)
{
$query = Feedback::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['TANGGAL'=>SORT_DESC]],
'pagination' => array('pageSize' => 10),
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'ID_KOMENTAR' => $this->ID_KOMENTAR,
'id' => $this->id,
'TANGGAL' => $this->TANGGAL,
]);
$query->andFilterWhere(['like', 'KOMENTAR', $this->KOMENTAR]);
return $dataProvider;
}
and the gridview code like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=>"{items}",
'tableOptions' => ['class' => 'table table-bordered table-hover'],
'showFooter'=>false,
'showHeader' => false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
'columns' => [
[ 'attribute' => 'iduser.photo',
'format' => 'html',
'value'=> function($data) { return Html::img($data->imageurl) . " <p class='feedback-username'>" . $data->username . "</p>"; },
'contentOptions'=>['style'=>'max-width: 10px; max-height: 10px'],
],
[ 'attribute' => 'KOMENTAR',
'format' => 'raw',
'value' => function($model) { return $model->KOMENTAR ."<br><p class='feedback-date'>". $model->TANGGAL ."</p>";},
],
[ 'class' => 'yii\grid\ActionColumn',
'contentOptions'=>['style'=>'width: 5px;'],
'template' => '{update} {delete}'
],
],
]); ?>
But why the page button is not shown, its limited but i can see the other data bcos the i cant find the button next or prev to the other page
I test your code
if I remove the layout=>"{items}", the page buttons are show otherwise not (i think your layout assignment mean show only the item and not the pager) try simply comment it
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'layout'=>"{items}",
'tableOptions' => ['class' => 'table table-bordered table-hover'],
'showFooter'=>false,
'showHeader' => false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
..........
I try to show data from database in view using gridview, but i got problem
error message
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: yii\db\ActiveQuery::getCount()
my controller
public function actionIndex()
{
$sql = "SELECT presensi.presensi_tanggal 'tanggal', sum(if( hadir.keteranganhadir_id='1',1,0)) 'hadir', sum(if( hadir.keteranganhadir_id='2',1,0)) 'tidak_hadir', count(*) 'total' FROM hadir, keteranganhadir, presensi where hadir.keteranganhadir_id = keteranganhadir.keteranganhadir_id and hadir.presensi_id = presensi.presensi_id group by presensi.presensi_tanggal";
$model = Hadir::findBySql($sql)->all();
return $this->render('index', [
'hadir' => $model,
]);
}
my view
<?= GridView::widget([
'dataProvider' => $hadir,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'tanggal',
'hadir',
'tidak_hadir',
'total',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How can i fix the problem?
Gridview looks for dataprovider, not array of activerecord models you have sent:
http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html
in your controller/actionIndex
$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM user WHERE status=:status
', [':status' => 1])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM user WHERE status=:status',
'params' => [':status' => 1],
'totalCount' => $count,
'sort' => [
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
],
'pagination' => [
'pageSize' => 20,
],
]);
return $this->render('index', [
'hadir' => $dataProvider,
]);
You can try this:
In Controller.php file:
public function actionIndex()
{
$searchModel = new InvoiceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Your view file seems to be true. Just add above code in your controller file.