douxing1969 2015-04-07 09:33
浏览 36
已采纳

yii 2.0 admin create无法使用ActiveForm

Okay first of all i am working with Yii 2 basic NOT the advanced version.

Okay i have made it so that my log in functionality works from pulling data from database as apposed to the users being hard coded. I then show in my index view a gridview of all the admins in my database with their id. I have tried to create a create page where an admin can create another admin.

I did manage to get this working however for the life of me i can not find out what i have done to make this functionality stop working.

Models\User.php

<?php

namespace app\models;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\data\ActiveDataProvider;
/**
* User model
*
* @property integer $id
* @property string $username
* @property string $authkey
* @property string $password 
* @property string $accessToken
*/
class User extends ActiveRecord implements IdentityInterface
{


/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'Users';
}


public function rules(){
        return [
            [['username','password'], 'required']
        ];
}



public static function findAdmins(){
    $query = self::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    return $dataProvider;

}


/**
 * @inheritdoc
 */
public static function findIdentity($id)
{
    return static::findOne(['id' => $id]);
}



/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $type = null)
{
    throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username)
{
    return static::findOne(['username' => $username]);
}

/**
 * @inheritdoc
 */
public function getId()
{
    return $this->id;
}

/**
 * @inheritdoc
 */
public function getAuthKey()
{
    return static::findOne('AuthKey');
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey)
{
    return static::findOne(['AuthKey' => $authKey]);
}

/**
 * Validates password
 *
 * @param  string  $password password to validate
 * @return boolean if password provided is valid for current user
 */
public function validatePassword($password)
{
    return $this->password === $password;
}
}

Views\admin\index.php

    <?php
    use yii\helpers\Html;
    use yii\grid\GridView;

    /* @var $this yii\web\View */
    $this->title = 'Admins';
    $this->params['breadcrumbs'][] = $this->title;
    ?>
    <div class="site-about">
        <h1><?= Html::encode($this->title) ?></h1>
        <p>
            <?= Html::a('Create Admin', ['create'], ['class' => 'btn btn-success']);?>  
        </p>
        <?php
            if(isset($user_id)){
                print_r($user_id);

            }
        ?>

        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                'id',
                'username',
                'password',

                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]); ?> 

    </div>

So this works and connects to my database fine. It displays the correct columns etc..

Now i will show you the two views which are not working, A create.php which renders _form.php

views\admin\create.php:

    <?php
    use yii\helpers\Html;


    /* @var $this yii\web\View */
    $this->title = 'Create Admin';
    $this->params['breadcrumbs'][] = ['label' => 'admin', 'url' => ['index']];
    $this->params['breadcrumbs'][] = $this->title;
    if(isset($username)){
    print_r($username);
    echo '</br>';
    print_r($password);   

    }
    ?>
    <div class="site-about">
        <h1><?= Html::encode($this->title) ?></h1>
        <?= $this->render('_form',[
            'model' => $model
        ]); 
        ?>



    </div>

views\admin_form.php:

    <?php

    use yii\helpers\Html;
    use yii\widgets\ActiveForm;



    /* @var $model app\models\Users */
    /* @var $form yii\widgets\ActiveForm */
    ?>

    <div class="admin-form">

        <?php $form = ActiveForm::begin(); ?>



        <?= $form->field($model, 'username')->textInput(); ?>
        <?= $form->field($model, 'password')->textInput(); ?>



        <div class="form-group">
            <?= Html::submitButton('create', ['class' => 'btn btn-success']) ?>
        </div>

        <?php ActiveForm::end(); ?>

    </div>

Now finally my controller:

controllers\AdminController.php:

    <?php

    namespace app\controllers;

    use Yii;
    use yii\web\Controller;
    use yii\filters\VerbFilter;
    use yii\filters\AccessControl;
    use app\models\User;





    class AdminController extends Controller
    {
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['post'],
                    ],
                ],
            ];
        }

        public function actions()
        {
            return [
                'error' => [
                    'class' => 'yii\web\ErrorAction',
                ],
                'captcha' => [
                    'class' => 'yii\captcha\CaptchaAction',
                    'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                ],
            ];
        }

        public function actionIndex()
        {
            $searchModel = new User;
            $dataProvider = $searchModel->findAdmins();

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

        public function actionCreate(){
            $model = new User;

            $request = Yii::$app->request;
            $post = $request->post(); 
            $username = "usernameStandard";
            $password = "passwordStandard";
            if($model->load(Yii::$app->request->post())){
                $username = $post['User']['username'];
                $password = $post['User']['password'];
            }
            return $this->render('create',[
                'model' => $model,
                'username' => $username,
                'password' => $password
                    ]);
        }

    }

Okay then so when i try and do this, i fill in the form from create.php(with rendered _form.php). and when i hit create button. I print_r() the post results to make sure that is fine and it does render the page again with the post results. However it does not create a new user in my database.

Really stuck here can anyone help?

  • 写回答

1条回答 默认 最新

  • duanjiao6731 2015-04-07 09:43
    关注

    Well, you should simply save your model... e.g. :

    public function actionCreate()
    {
        $model = new User;
    
        if($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
    
        return $this->render('create',[
            'model' => $model,
        ]);
    }
    

    Read more http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#save()-detail

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料