add user CRUD

This commit is contained in:
rocho 2015-09-19 08:29:47 +02:00
parent 271835ae6b
commit 5163f1a9a9
15 changed files with 653 additions and 14 deletions

View File

@ -0,0 +1,74 @@
<?php
namespace backend\components;
use Yii;
use common\models\Order;
use yii\helpers\Html;
class AdminMenuStructure{
public $menuItems;
public function AdminMenu(){
$this->menuItems = [];
}
protected function can($authItem){
$result = false;
if (\Yii::$app->user->can($authItem)) {
$result = true;
}
return $result;
}
protected function addUserMainMenu(){
$userMainMenu = null;
$items = [];
// if ( $this->can('backend.user.index')){
$items[] = ['label' => 'Felhasználók', 'url' =>['/user/index']];
// }
if ( count($items) > 0 ){
$userMainMenu = ['label' => 'Beállítások', 'url' => null,
'items' => $items
];
}
if ( isset($userMainMenu)){
$this->menuItems[] = $userMainMenu;
}
}
protected function addLoginMainMenu(){
if (Yii::$app->user->isGuest) {
$mainMenuItem= ['label' => 'Login', 'url' => ['/site/login']];
} else {
$mainMenuItem= [
'label' => 'Kijelentkezés (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
$this->menuItems[] = $mainMenuItem;
}
public function run(){
$this->addUserMainMenu();
$this->addLoginMainMenu();
return $this->menuItems;
}
}

View File

@ -0,0 +1,132 @@
<?php
namespace backend\controllers;
use Yii;
use common\models\User;
use backend\models\UserSearch;
use backend\models\UserCreate;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Object;
use backend\models\UserUpdate;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all User models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single User model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new UserCreate();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = UserUpdate::findOne(['id' => $id]);
if ( $model == null ){
throw new NotFoundHttpException('The requested page does not exist.');
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing User 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)->delete();
$user = $this->findModel($id);
$user->updateAttributes(['status' => User::STATUS_DELETED]);
return $this->redirect(['index']);
}
/**
* Finds the User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace backend\models;
use Yii;
use common\models\User;
class UserCreate extends User{
public $password_plain;
public $password_repeat;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username','email','password_plain','password_repeat'], 'required' ],
['email' ,'email' ],
['email' ,'unique' ],
['username' ,'unique' ],
[['password_plain' ,'password_repeat'] ,'string','min' =>6 ],
[['password_repeat'] ,'validatePasswordRepeat' ]
];
}
public function validatePasswordRepeat($attribute,$params){
if ( !$this->hasErrors()){
if ( $this->password_plain != $this->password_repeat ){
$this->addError($attribute, Yii::t('app', 'Jelszó és jelszó újra nem egyezik!') );
}
}
}
public function attributeLabels(){
return [
'email' =>'E-mail',
'username' =>'Felhasználónév',
'created_at' =>'Létrehozás dátuma',
'password_plain' => Yii::t('app','Jelszó'),
'password_repeat' => Yii::t('app','Jelszó újra'),
];
}
public function beforeSave($insert){
if ( parent::beforeSave($insert)){
if ( $insert ){
$this->setPassword($this->password_plain);
$this->generateAuthKey();
return true;
}
}else{
return false;
}
}
public function afterSave($insert, $changedAttributes){
parent::afterSave($insert, $changedAttributes);
// $am = Yii::$app->authManager;
// $role = $am->getRole('admin');
// Yii::$app->authManager->assign($role, $this->id);
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\User;
/**
* UserSearch represents the model behind the search form about `common\models\User`.
*/
class UserSearch extends User
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'status', 'created_at', 'updated_at'], 'integer'],
[['username', 'auth_key', 'password_hash', 'password_reset_token', 'email'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = User::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$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' => $this->id,
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'username', $this->username])
->andFilterWhere(['like', 'auth_key', $this->auth_key])
->andFilterWhere(['like', 'password_hash', $this->password_hash])
->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
->andFilterWhere(['like', 'email', $this->email]);
return $dataProvider;
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace backend\models;
use Yii;
use common\models\User;
class UserUpdate extends User {
public $password_plain;
public $password_repeat;
/**
* @inheritdoc
* @formatter:off
*/
public function rules()
{
return [
[['username','email'], 'required' ],
['email' ,'email' ],
['email' ,'unique' , 'targetClass' => User::className(), 'targetAttribute' => 'email'],
['username' ,'unique', 'targetClass' => User::className(), 'targetAttribute' => 'username'],
[['password_plain' ,'password_repeat'] ,'string','min' =>6 ],
[['password_repeat'] ,'validatePasswordRepeat' ]
];
}
/**
* @formatter:on
*/
public function validatePasswordRepeat($attribute, $params) {
if (! $this->hasErrors ()) {
if ( !empty($this->password_plain) || !empty($this->password_repeat) ){
if ($this->password_plain != $this->password_repeat) {
$this->addError ( $attribute, Yii::t ( 'app', 'Jelszó és jelszó újra nem egyezik!' ) );
}
}
}
}
public function attributeLabels() {
return [
'email' => 'E-mail',
'username' => 'Felhasználónév',
'created_at' => 'Létrehozás dátuma',
'password_plain' => Yii::t ( 'app', 'Jelszó' ),
'password_repeat' => Yii::t ( 'app', 'Jelszó újra' )
]
;
}
public function beforeSave($insert) {
if (parent::beforeSave ( $insert )) {
if (! $insert) {
if ( !empty( $this->password_plain ) ) {
$this->setPassword($this->password_plain);
return true;
}
}
return true;
} else {
return false;
}
}
public function afterSave($insert, $changedAttributes) {
parent::afterSave ( $insert, $changedAttributes );
// $am = Yii::$app->authManager;
// $role = $am->getRole('admin');
// Yii::$app->authManager->assign($role, $this->id);
}
}

View File

@ -9,8 +9,12 @@ use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use common\widgets\Alert;
use backend\components\AdminMenuStructure;
AppAsset::register($this);
$adminMenu = new AdminMenuStructure();
$items = $adminMenu->run();
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
@ -28,27 +32,15 @@ AppAsset::register($this);
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandLabel' => 'Botond Fitness WebAdmin',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
'items' => $items,
]);
NavBar::end();
?>

View File

@ -0,0 +1,28 @@
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\User */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="user-form">
<?php $form = ActiveForm::begin(); ?>
<?php echo Yii::t('common', 'Create')?>
<?= $form->field($model, 'username')->textInput() ?>
<?= $form->field($model, 'email')->textInput() ?>
<?= $form->field($model, 'password_plain')->passwordInput() ?>
<?= $form->field($model, 'password_repeat')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Mentés') : Yii::t('app', 'Mentés'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

View File

@ -0,0 +1,35 @@
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model frontend\models\UserSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="panel panel-default">
<div class="panel-heading">
<?= Yii::t('app','Keresés')?>
</div>
<div class="panel-body">
<div class="user-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'username') ?>
<?php echo $form->field($model, 'email') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Keresés'), ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

View File

@ -0,0 +1,21 @@
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\User */
$this->title = Yii::t('app', 'Új felhasználó');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Felhasználók'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>

View File

@ -0,0 +1,35 @@
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel frontend\models\UserSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Felhasználók');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Új felhasználó'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'username',
'email:email',
'created_at:datetime',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>

View File

@ -0,0 +1,23 @@
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\User */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'User',
]) . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Users'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="user-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>

View File

@ -0,0 +1,38 @@
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\User */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Felhasználók'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'username',
'email:email',
'statusHuman',
'created_at:datetime',
],
]) ?>
</div>

View File

@ -1,6 +1,8 @@
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
// 'language' => 'hu-HU',
'language' => 'hu',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',

View File

@ -185,4 +185,20 @@ class User extends ActiveRecord implements IdentityInterface
{
$this->password_reset_token = null;
}
static function statuses() {
return [
self::STATUS_ACTIVE => Yii::t('app', 'Aktív'),
self::STATUS_DELETED => Yii::t('app', 'Inaktív'),
] ;
}
public function getStatusHuman(){
$result = null;
$s = self::statuses($this->status);
if ( array_key_exists($this->status, $s)){
$result = $s[$this->status];
}
return $result;
}
}

View File

@ -0,0 +1,34 @@
<?php
use yii\db\Schema;
use yii\db\Migration;
use yii\base\Object;
use common\models\User;
class m150828_200317_add_default_admin_user extends Migration
{
public function up()
{
$user = new User();
$user->username = "admin";
$user->email = "admin@rocho-net.hu";
$user->setPassword("test");
$user->generateAuthKey();
$user->save();
}
public function down()
{
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}