How to show content for the users using CGridView? - yii

I have a page with the list of categories on my site and I want to show them using Cgridview as right now they displayed with CListView. I'm using Yii 1.1. I see that CGridView used only if you want to manage content but is it possible to use it if you want to show it, on the index pages?
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'status',
array(
'class'=>'CButtonColumn',
),
),
)); ?>

You can used this code for your cgridview
Categories Model
File Path : protected/model/categories.php
Categories.php
<?php
/**
* This is the model class for table "categories".
*
* The followings are the available columns in table 'categories':
* #property integer $id
* #property string $title
* #property string $status
*/
class Categories extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'area';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, status', 'required'),
array('status', 'numerical', 'integerOnly'=>true),
array('title', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, title, status', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'title' => 'Title',
'status' => 'Status'
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('status',$this->status);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return Area the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Categories Controller
File Path : protected/model/CategoriesController.php
CategoriesController.php
<?php
class CategoriesController extends Controller
{
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
* #access Public
*/
public function accessRules()
{
return array(
array('allow',
'actions' => array('index'),
'users' => array('*'),
),
array('deny',
'users' => array('*'),
),
);
}
public function actionIndex()
{
$model = new Categories();
$model->unsetAttributes();
if(isset($_REQUEST['Categories']))
$model->attributes = $_REQUEST['Categories'];
$this->render('index',array('model'=>$model));
}
}
Categories View File
File Path : protected/view/index.php
index.php
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'status',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
you can add your design in index.php file.
refere this link for design

Related

Issue With Laravel 8 Auth Email Verification

I'm Using Laravel 8.x And i'm trying to make login/register With Email verification
I followed Some Tutorials,Blogs but didn't get desired output
I want:-
Whenever User Register themselve An Verification Email must send to there email
(Email Is Sent but not able to verify by that url so i follow some laracast blog by that i'm able to verify by that verification url)
but the issue is if i didn't verified my self i'm still able to login into my application
Here Is Codes
HomeController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth','verified']);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
','--------------------------------------------------------------------------
',' Register Controller
','--------------------------------------------------------------------------
','
',' This controller handles the registration of new users as well as their
',' validation and creation. By default this controller uses a trait to
',' provide this functionality without requiring any additional code.
','
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'contact' => ['required','min:10'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required','string','min:8','confirmed','regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{6,}$/'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'contact' => $data['contact'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Veification Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;
use App\Models\User;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// $this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function verify(Request $request)
{
// if ($request->route('id') != $request->user()->getKey()) {
// throw new AuthorizationException;
// }
$user = User::find($request->route('id'));
auth()->login($user);
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
}
Route
Auth::routes(['verify' => true]);
Route::group(['prefix'=>'user', 'middleware' => 'auth'],function(){});

Eloquent model User doesn't returns the right array

I currently have trouble in making a site page on which every user is displayed in order to manage them.
The users will be displayed with name, email, permission and links to modify, reset their password and delete them on the other page
I made a function in my controller for the page "manage-user":
public function getManageUsers(){
$users = User::all();
var_dump($users);
return View::make('UsersManagement.manage-users')->with('users', '$users');
}
but the result of the var_dump() is actually:
object(Illuminate\Database\Eloquent\Collection)[163]
protected 'items' =>
array (size=3)
0 =>
object(User)[159]
protected 'table' => string 'users' (length=5)
protected 'hidden' =>
array (size=2)
...
protected 'connection' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=9)
...
protected 'original' =>
array (size=9)
...
protected 'relations' =>
array (size=0)
...
protected 'visible' =>
array (size=0)
...
protected 'appends' =>
array (size=0)
...
protected 'fillable' =>
array (size=0)
...
protected 'guarded' =>
array (size=1)
...
protected 'dates' =>
array (size=0)
...
protected 'touches' =>
array (size=0)
...
protected 'observables' =>
array (size=0)
...
protected 'with' =>
array (size=0)
...
protected 'morphClass' => null
public 'exists' => boolean true
here is the model if it helps :
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
I don't understand where the problem is since I always used this line of code to retrieve every data of of a database and it always worked with the DB's indexes.
I'm really lost on this situation and don't know what to do.
Any help is welcomed.
Thanks in advance.
Damien

upload image to content in Yii

I have 2 tables, postimage and post. Postimage has fields post_id, id and image. I need to create upload form of the image and show it when content created. This image should be lincked to the content(though post_id field). Uploading form appears but images don't uploading. I tried such a way:
class PostImageController extends Controller
{
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new PostImage;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PostImage']))
{
$model->attributes=$_POST['PostImage'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
$path=Yii::getPathOfAlias('webroot').'/images/'.$model->image->getName();
$model->image->saveAs($path);
//$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PostImage']))
{
$model->attributes=$_POST['PostImage'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('PostImage');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new PostImage('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['PostImage']))
$model->attributes=$_GET['PostImage'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return PostImage the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=PostImage::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param PostImage $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='post-image-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
PostImage model:
<?php
/**
* This is the model class for table "PostImage".
*
* The followings are the available columns in table 'PostImage':
* #property integer $id
* #property string $image
* #property integer $post_id
*
* The followings are the available model relations:
* #property Post $post
*/
class PostImage extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public $image;
public function tableName()
{
return 'PostImage';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//array('image', 'required'),
array('post_id', 'numerical', 'integerOnly'=>true),
array('image', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, image, post_id', 'safe', 'on'=>'search'),
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'post' => array(self::BELONGS_TO, 'Post', 'post_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'image' => 'Image',
'post_id' => 'Post',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('image',$this->image,true);
$criteria->compare('post_id',$this->post_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return PostImage the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
And this is view of the form:
<?php
echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));
echo CHtml::activeFileField($model, 'image');
echo CHtml::endForm();
?>

PHPStorm property-read for Yii model relations

How can I do this in PHPStorm so hinting works correctly when calling the model() method?
For instance:
/**
* #property-read \Stores $store
*/
class Items extends CActiveRecord
{
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function relations()
{
return array('store' => array(self::BELONGS_TO, 'Stores', array('store_id' => 'id')),
}
}
$items = new Items;
$items->store; // PHPStorm type hints this correctly
Items::model()->store; // PHPStorm does NOT type hint correctly.
Model above minimalist for focus of this post.
You just have to 'tell' PhpStorm what this method returns.
/**
* #param $className
* #returns Items
*/
public static function model( $className = __CLASS__ ) {
return parent::model( $className );
}

Yii inherit attributeLabels

With Yii php framework, I use inheritance.
In my AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'0'=>Yii::t('default','No'),
'1'=>Yii::t('default','Yes'),
);
}
In my object who extends AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'username' => Yii::t('user', 'email'),
);
}
In a view file, I use:
<?php echo CHtml::activeLabel($model, $model->property);?>
But I never show 'No' or 'Yes' from asbtractModel. If I put all in my model it works. But I want to use inheritance.
How can I concat parent attributeLabels with current model attributeLabels?
Simply merge the return value of the parent method in MyObject (model class):
public function attributeLabels() {
return array_merge(
parent::attributeLabels(),
array(
'username' => Yii::t('user', 'email'),
)
);
}
You may also use CMap::mergeArray().