Skip to content

Profile and custom registration

webvimark edited this page Feb 3, 2015 · 4 revisions

Let's say you want to have profile for your users with following fields

age: integer,
pet: string,
favorite_food: string,

stored in "user_profile" table.

Also you want user on registration write they age + age should be bigger than 18 (yep, we'll create porno site 🎱 )

  1. Create migration --

Do not forget to add foreign key for "user" table

<?php

use yii\db\Migration;

class m150203_154807_create_user_profile extends Migration
{
	public function safeUp()
	{
		$this->createTable('user_profile', array(
			'id'      => 'pk',
			'user_id' => 'int',

			'age'           => 'int not null',
			'pet_name'      => 'string not null',
			'favorite_food' => 'string not null',

			'created_at' => 'int',
			'updated_at' => 'int',
		));

		$this->addForeignKey('fk_user_profile_user_id', 'user_profile', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE');
	}

	public function safeDown()
	{
		$this->dropForeignKey('fk_user_profile_user_id', 'user_profile');
		
		$this->dropTable('user_profile');

	}
}
  1. Generate model via gii --
<?php

namespace app\models;

use webvimark\modules\UserManagement\models\User;
use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "user_profile".
 *
 * @property integer $id
 * @property integer $user_id
 * @property integer $age
 * @property string $pet_name
 * @property string $favorite_food
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property User $user
 */
class UserProfile extends \yii\db\ActiveRecord
{
	/**
	* @inheritdoc
	*/
	public static function tableName()
	{
		return 'user_profile';
	}

	/**
	* @inheritdoc
	*/
	public function behaviors()
	{
		return [
			TimestampBehavior::className(),
		];
	}

	/**
	* @inheritdoc
	*/
	public function rules()
	{
		return [
			[['user_id', 'age'], 'integer'],
			[['age', 'pet_name', 'favorite_food'], 'required'],
			[['pet_name', 'favorite_food'], 'string', 'max' => 255],
			[['pet_name', 'favorite_food'], 'trim']
		];
	}

	/**
	* @inheritdoc
	*/
	public function attributeLabels()
	{
		return [
			'id' => 'ID',
			'user_id' => 'User ID',
			'age' => 'Age',
			'pet_name' => 'Pet Name',
			'favorite_food' => 'Favorite Food',
			'created_at' => 'Created',
			'updated_at' => 'Updated',
		];
	}

	/**
	* @return \yii\db\ActiveQuery
	*/
	public function getUser()
	{
		return $this->hasOne(User::className(), ['id' => 'user_id']);
	}
}
  1. To be continued... --
Clone this wiki locally