yii 用户管理编辑字段

问题描述 投票:0回答:1

我已经成功设置了 yii-user-management。感谢这里的帮助。

但是,当我在个人资料/字段/管理中时。

我单击编辑字段,然后在下拉列表中将该字段从必需的“否”更改为“是”,然后保存,但没有任何反应。

我也明白:

CDbCommand 无法执行 SQL 语句: SQLSTATE[42000]: 语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行“(0) NOT NULL DEFAULT 0”附近使用的正确语法。执行的 SQL 语句是: ALTER TABLE profile ADD `` (0) NOT NULL DEFAULT 0

创建字段时。

如果您需要一些代码或文件,请告诉我。任何帮助表示赞赏。

这里是配置文件/models/YumProfileField.php

class YumProfileField extends YumActiveRecord
{
const VISIBLE_HIDDEN=0;
const VISIBLE_ONLY_OWNER=1;
const VISIBLE_REGISTER_USER=2;
const VISIBLE_USER_DECISION=3;
const VISIBLE_PUBLIC=4; // Field is public even if the user decides to hide it

/**
 * Returns the static model of the specified AR class.
 * @param string $className
 * @return YumProfileField
 */
public static function model($className=__CLASS__)
{
    return parent::model($className);
}

public function isPublic($user = null) {
    if($user == null)
        $user = Yii::app()->user->id;

    if(!$this->visible)
        return false;

    if($privacy = YumUser::model()->findByPk($user)->privacy) {
        if($privacy->public_profile_fields & pow(2, $this->id))
            return true;
    }

    return false;
}

public function tableName()
{
    $this->_tableName = Yum::module('profile')->profileFieldTable;
    return $this->_tableName;
}
public function scopes()
{
    return array(
            'forAll'=>array(
                'condition'=>'visible='.self::VISIBLE_PUBLIC,
                ),
            'forUser'=>array(
                'condition'=>'visible>='.self::VISIBLE_REGISTER_USER,
                ),
            'forOwner'=>array(
                'condition'=>'visible>='.self::VISIBLE_ONLY_OWNER,
                ),
            );
}

public static function itemAlias($type,$code=NULL) {
    $_items = array(
            'field_type' => array(
                'INTEGER' => Yum::t('INTEGER'),
                'VARCHAR' => Yum::t( 'VARCHAR'),
                'TEXT'=> Yum::t( 'TEXT'),
                'DATE'=> Yum::t( 'DATE'),
                'DROPDOWNLIST' => Yum::t('DROPDOWNLIST'),
                'FLOAT'=> Yum::t('FLOAT'),
                'BOOL'=> Yum::t('BOOL'),
                'BLOB'=> Yum::t('BLOB'),
                'BINARY'=> Yum::t('BINARY'),
                'FILE'=> 'FILE',
                ),
            'required' => array(
                '0' => Yum::t('No'),
                '1' => Yum::t('Yes'),
                ),
            'visible' => array(
                self::VISIBLE_USER_DECISION => Yum::t('Let the user choose in privacy settings'),
                self::VISIBLE_PUBLIC => Yum::t('For all'),
                self::VISIBLE_REGISTER_USER => Yum::t('Registered users'),
                self::VISIBLE_ONLY_OWNER => Yum::t('Only owner'),
                self::VISIBLE_HIDDEN => Yum::t('Hidden'),
                ),
            );
    if (isset($code))
        return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
    else
        return isset($_items[$type]) ? $_items[$type] : false;
}
}

YumFieldsController:

class YumFieldsController extends YumController
{
const PAGE_SIZE=10;

public function accessRules()
{
    return array(
        array('allow', 
            'actions'=>array('index', 'create', 'update', 'view', 'admin','delete'),
            'users'=>array(Yii::app()->user->name),
            'expression' => 'Yii::app()->user->isAdmin()'
            ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

public function actionView()
{
    $this->layout = Yum::module()->adminLayout;
    $this->render('view',array(
        'model'=>$this->loadModel('YumProfileField'),
    ));
}

public function actionCreate() {
    $this->layout = Yum::module()->adminLayout;
    $model = new YumProfileField;

    // add to group?
    if(isset($_GET['in_group']))
        $model->field_group_id=$_GET['in_group'];

    if(isset($_POST['YumProfileField'])) {
        $model->attributes = $_POST['YumProfileField'];

        $field_type = $model->field_type;
        if($field_type == 'DROPDOWNLIST')
            $field_type = 'INTEGER';

        if($model->validate()) {
            $sql = 'ALTER TABLE '.YumProfile::model()->tableName().' ADD `'.$model->varname.'` ';
            $sql .= $field_type;
            if ($field_type!='TEXT' && $field_type!='DATE')
                $sql .= '('.$model->field_size.')';
            $sql .= ' NOT NULL ';
            if ($model->default)
                $sql .= " DEFAULT '".$model->default."'";
            else
                $sql .= (($field_type =='TEXT' || $model->field_type=='VARCHAR')?" DEFAULT ''":" DEFAULT 0");

            $model->dbConnection->createCommand($sql)->execute();
            $model->save();
            $this->redirect(array('view','id'=>$model->id));
        }
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

public function actionUpdate()
{
    $this->layout = Yum::module()->adminLayout;

    $model = $this->loadModel('YumProfileField');
    if(isset($_POST['YumProfileField']))
    {
        $model->attributes=$_POST['YumProfileField'];

        // ALTER TABLE `test` CHANGE `profiles` `field` INT( 10 ) NOT NULL 
        // ALTER TABLE `test` CHANGE `profiles` `description` INT( 1 ) NOT NULL DEFAULT '0'
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('update',array(
        'model'=>$model,
    ));
}

public function actionDelete()
{
    $this->layout = Yum::module()->adminLayout;
    if(Yii::app()->request->isPostRequest)
    {
        // we only allow deletion via POST request
        $model = $this->loadModel('YumProfileField');
        $sql = 'ALTER TABLE '.YumProfile::model()->tableName().' DROP `'.$model->varname.'`';
        if ($model->dbConnection->createCommand($sql)->execute()) {
            $model->delete();
        }

        if(!isset($_POST['ajax']))
            $this->redirect(array('index'));
    }
    else
        throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}

public function actionIndex()
{
    $this->layout = Yum::module()->adminLayout;
    $dataProvider=new CActiveDataProvider('YumProfileField', array(
        'pagination'=>array(
            'pageSize'=>self::PAGE_SIZE,
        ),
        'sort'=>array(
            'defaultOrder'=>'position',
        ),
    ));

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

public function actionAdmin()
{
    $this->layout = Yum::module()->adminLayout;

    $dataProvider=new CActiveDataProvider('YumProfileField', array(
        'pagination'=>array(
            'pageSize'=>self::PAGE_SIZE,
        ),
        'sort'=>array(
            'defaultOrder'=>'position',
        ),
    ));

    $this->render('admin',array(
        'dataProvider'=>$dataProvider,
    ));
}

}

YumProfile.php 模型

class YumProfile extends YumActiveRecord
{
const PRIVACY_PRIVATE = 'private';
const PRIVACY_PUBLIC = 'public';

/**
 * @var array of YumProfileFields
 */
static $fields=null;

public function init()
{
    parent::init();
    // load profile fields only once
    $this->loadProfileFields();
}

public function afterSave() {
    if($this->isNewRecord) 
        Yii::log(Yum::t( 'A profile been created: {profile}', array(
                        '{profile}'   =>json_encode($this->attributes))));
    else
        Yii::log(Yum::t( 'A profile been update: {profile}', array(
                        '{profile}' => json_encode($this->attributes))));

    return parent::afterSave();
}

public function recentComments($count = 3) {
    $criteria = new CDbCriteria;
    $criteria->condition = 'id = ' .$this->id;
    $criteria->order = 'createtime DESC';
    $criteria->limit = $count;
    return YumProfileComment::model()->findAll($criteria);
}

public function beforeValidate() {
    if($this->isNewRecord)
        $this->timestamp = time();
    return parent::beforeValidate();
}

/**
 * @param string $className
 * @return YumProfile
 */
public static function model($className=__CLASS__)
{
    return parent::model($className);
}

// All fields that the user has activated in his privacy settings will
// be obtained and returned for the use in the profile view
public function getPublicFields() {
    if(!Yum::module('profile')->enablePrivacySetting)
        return false;

    $fields = array();

    if($privacy = YumUser::model()
            ->cache(500)
            ->with('privacy')
            ->findByPk($this->user_id)
            ->privacy->public_profile_fields) {
        $i = 1;
        foreach(YumProfileField::model()->cache(3600)->findAll() as $field) {
            if(
                    (($i & $privacy) 
                     && $field->visible != YumProfileField::VISIBLE_HIDDEN) 
                    || $field->visible == YumProfileField::VISIBLE_PUBLIC)
                $fields[] = $field;
            $i*=2;
        }
    }
    return $fields;
}

/**
 * Returns resolved table name 
 * @return string
 */
public function tableName()
{
    $this->_tableName = Yum::module('profile')->profileTable;
    return $this->_tableName;
}

public function rules()
{
    $required = array();
    $numerical = array();
    $rules = array();
    $safe = array();

    foreach (self::$fields as $field) {
        $field_rule = array();

        if ($field->required == 1)
            array_push($required, $field->varname);

        if ($field->field_type == 'int'
                || $field->field_type == 'FLOAT'
                || $field->field_type =='INTEGER'
                || $field->field_type =='BOOLEAN')
            array_push($numerical, $field->varname);

        if ($field->field_type == 'DROPDOWNLIST')
            array_push($safe, $field->varname);

        if ($field->field_type == 'VARCHAR' || $field->field_type == 'TEXT') {
            $field_rule = array($field->varname,
                    'length',
                    'max'=>$field->field_size,
                    'min' => $field->field_size_min);

            if ($field->error_message)
                $field_rule['message'] = Yum::t($field->error_message);

            array_push($rules,$field_rule);
        }

        if ($field->match) {
            $field_rule = array($field->varname,
                    'match',
                    'pattern' => $field->match);

            if ($field->error_message)
                $field_rule['message'] = Yum::t( $field->error_message);

            array_push($rules,$field_rule);
        }

        if ($field->range) {
            // allow using commas and semicolons
            $range=explode(';',$field->range);
            if(count($range)===1)
                $range=explode(',',$field->range);
            $field_rule = array($field->varname,'in','range' => $range);

            if ($field->error_message)
                $field_rule['message'] = Yum::t( $field->error_message);
            array_push($rules,$field_rule);
        }

        if ($field->other_validator) {
            $field_rule = array($field->varname,
                    $field->other_validator);

            if ($field->error_message)
                $field_rule['message'] = Yum::t( $field->error_message);
            array_push($rules, $field_rule);
        }

    }

    array_push($rules,
            array(implode(',',$required), 'required'));
    array_push($rules,
            array(implode(',',$numerical), 'numerical', 'integerOnly'=>true));
    array_push($rules,
            array(implode(',',$safe), 'safe'));

    $rules[] = array('allow_comments, show_friends', 'numerical');
    $rules[] = array('email', 'unique');
    $rules[] = array('email', 'CEmailValidator');
    $rules[] = array('privacy', 'safe');

    return $rules;
}

public function relations()
{
    $relations = array(
            'user' => array(self::BELONGS_TO, 'YumUser', 'user_id'),
            'comments' => array(self::HAS_MANY, 'YumProfileComment', 'profile_id'),
            );

    $fields = Yii::app()->db->cache(3600)->createCommand(
            "select * from ".YumProfileField::model()->tableName()." where field_type = 'DROPDOWNLIST'")->queryAll();

    foreach($fields as $field) {
        $relations[ucfirst($field['varname'])] = array(
                self::BELONGS_TO, ucfirst($field['varname']), $field['varname']);

    }

    return $relations;
}

// Retrieve a list of all users that have commented my profile
// Do not show my own profile visit
public function getProfileCommentators() {
    $commentators = array();
    foreach($this->comments as $comment)
        if($comment->user_id != Yii::app()->user->id)
            $commentators[$comment->user_id] = $comment->user;

    return $commentators;
}

public function getProfileFields() {
    $fields = array();

    if(self::$fields)
        foreach(self::$fields as $field) {
            $varname = $field->varname;
            $fields[$varname] = Yum::t($varname);
        }
    return $fields;
}

public function name() {
    return sprintf('%s %s', $this->firstname, $this->lastname);
}

public function attributeLabels()
{
    $labels = array(
            'id' => Yum::t('Profile ID'),
            'user_id' => Yum::t('User ID'),
            'privacy' => Yum::t('Privacy'),
            'show_friends' => Yum::t('Show friends'),
            'allow_comments' => Yum::t('Allow profile comments'),
            );

    if(self::$fields)
        foreach (self::$fields as $field)
            $labels[$field->varname] = Yum::t($field->title);

    return $labels;
}

/**
 * Load profile fields.
 * Overwrite this method to get another set of fields
 * Makes use of cache so the amount of sql queries per request is reduced
 * @since 0.6
 * @return array of YumProfileFields or empty array
 */
public function loadProfileFields()
{
    if(self::$fields===null)
    {
        self::$fields=YumProfileField::model()->cache(3600)->findAll();
        if(self::$fields==null)
            self::$fields=array();
    }
    return self::$fields;
}

}
php yii
1个回答
1
投票

您似乎正在尝试添加没有名称或类型的列? MySQL ALTER TABLE 示例.

另外,检查您的数据库用户是否具有

ALTER TABLE
的权限。

© www.soinside.com 2019 - 2024. All rights reserved.