Save dynamic data to two tables using relationship in Laravel - laravel

I have two tables Students and Hobbies. I've all details in one form but I want to save details to separate tables on submit. How can I achieve this?
My Student model
<?php
namespace App;
class Students extends Model {
protected $fillable = ['name', 'address'];
public function hobbies() {
return $this->hasMany(Hobby::class);
}
}
Hobby model:
<?php
namespace App;
use App\Product;
class Hobby extends Model
{
protected $fillable = [
'entertainment', 'sports'
];
public function hobby()
{
return $this->belongsTo(Student::class);
}
}
Controller:
public function save(Request $request, Student $student)
{
$students= new Student;
$students->name= request('name');
$students->address= request('address');
$students->save();
if($students->save())
{
$hobbies= [];
$images = $request->file('hob_img');
$hob_desc = $request->hob_desc;
foreach ($request->hob_name as $key => $hobby) {
$hob_img = '';
{
$hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
$files[$key]->move(public_path('/assets/images/'), $hob_img);
}
$hobbies[] = [
'hob_name' => $hobby,
'hob_desc' => $hob_desc[$key],
'hob_img' => $hob_img
];
}
$hobbies[] = new Hobby;
$hobbies->hob_name = request('hob_name')[$key];
$hobbies->hob_desc= request('hob_desc')[$key];
$hobbies->hob_img = request($hob_img)[$key];
$hobbies->save();
}
}
But I cannot save it. It says SQLSTATE[HY000]: General error: 1364 Field 'student_id' doesn't have a default value

Try the insert to save many records at onece :
public function save(Request $request, Student $student)
{
$student= new Student;
$student->name= request('name');
$student->address= request('address');
if($student->save())
{
$hobbies= [];
$images = $request->file('hob_img');
$hob_desc = $request->hob_desc;
foreach ($request->hob_name as $key => $hobby) {
$hob_img = '';
$hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
// $files i think it should be $images
$files[$key]->move(public_path('/assets/images/'), $hob_img);
$hobbies[] = [
'hob_name' => $hobby,
'hob_desc' => $hob_desc[$key],
'hob_img' => $hob_img,
'student_id'=> $student->id
];
}
Hobby::insert($hobbies); // useing Eloquent
// Or you can use Query Builder
// DB::table('hobbies')->insert($hobbies);
}
}

Related

Data not inserted to Mysql using Eloquent laravel

I have problem with insert data to Database table using Eloquent Model insert() method in Larvel. But when I click on submit button then data not inserted in database.
Here is my implemented code:-
Controller
public function receivedAll(Request $request, ItemPR $item_code)
{
$item_code = $request->item_code;
$pr_qty = $request->pr_qty;
$uploadFile = $request->file('file_document');
$update_data = ItemPR::whereIn('item_code', explode(",", $item_code))->update(['receive'=> 'received']);
$get_data = ItemPR::whereIn('item_code', explode(",", $item_code))->orWhereIn('pr_qty', explode(",", $pr_qty))->get();
$data = [];
foreach($get_data as $value) {
if(is_array($uploadFile)) {
foreach($uploadFile as $file) {
$filename = $file->getClientOriginalName();
$folder[] = $file->storeAs('uploads', $filename);
}
$data[] =
[
'item_code' => $value->item_code,
'qty' => $value->pr_qty,
'file_document' => $filename,
'created_at' => Carbon::now(),
'created_by' => Auth::user()->nick_name,
'last_update' => Carbon::now(),
'last_update_by' => Auth::user()->nick_name,
];
}
WarehouseInventory::insert($data);
}
// Model elequent insert
return response()->json(['success'=>"Products Updated successfully."]);
}
Model:- WarehouseInventory.php
class WarehouseInventory extends Model
{
protected $table = 'warehouse_inventori';
protected $primaryKey = 'pr_item';
public $incrementing = false;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'last_update';
protected $fillable = [
'pr_item', 'item_code', 'qty', 'po_number', 'warehouse_id', 'file_document', 'created_at', 'last_update', 'last_update_by', 'created_by'
];
}
Any idea or what's in my code is wrong?
You are using insert() method on eloquent, insert() is the method of DB class, Eloquent has create() method instead,
WarehouseInventory::create($data);
src: https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models

Not updating database and not throwing error in laravel

I have an issue while updating the user. When I try to update the user after clicking the save button then it redirect me to the same page and not throwing me any error but also its not updating anything in the database. Below is my code. I have no idea what's going on here. Help me :)
Controller
public function update(ReportRequest $request, $id)
{
$report = Report::findOrFail($id);
$input = $request->all();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$report->update($input);
return redirect()->back();
}
Route
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
'edit'=>'admin.reports.edit',
]]);
Models
class Report extends Model
{
protected $fillable = [
'student_id',
'student_name',
'class_id',
'subject',
'teacher_name',
'report_categories_id',
'total_marks',
'obtained_marks',
'percentage',
'position',
'photo_id',
];
public function photo() {
return $this->belongsTo('App\Photo');
}
public function studentsClass() {
return $this->belongsTo('App\StudentsClass', 'class_id');
}
public function student() {
return $this->belongsToMany('App\Student');
}
}
Make sure you have your $fillable properties in your Photo and Report models, otherwise the create() and update() methods won't work as expected.
Check the $fillable fields in the Model as above. If the error persists check your laravel log on storage/logs/laravel.log.
In controller:
public function update(ReportRequest $request, $id){
$report = Report::findOrFail($id);
$input = $request->all();
try{
if ($request->photo_id != '') {
$path = 'images/';
$file = $request->photo_id;
$name = time() . $file->getClientOriginalName();
$file->move($path, $name);
$photo = Photo::create(['file' => $name]);
$report->update(['photo_id' => $photo->id]);
}
return redirect()->back();
}catch(\Exception $e){
return redirect()->back()->with('error_message', $e->getMessage());
}
}

Laravel 5.6 Many To Many Polymorphic Relations Insert Not Work

I'm use laravel 5.6 on this project. Categories value not recorded 'categorizables' pivot table. I check with f12 or bug but I do not get any errors. all of them ok but not recorded pivot table. Where I have
been mistake.
My Blog project sql structure is below
--blogs
id
title
description
...
-- categorizables
category_id
categorizable_id
categorizable_type
Below code belong to Category.php Model
class Category extends Model
{
protected $primaryKey='category_id';
public function blogs(){
return $this->morphedByMany('App\Blog', 'categorizable', 'categorizables', 'category_id');
}
}
Above code belong to Blog.php
public function category($categories)
{
$categories = Blog::buildCatArray($categories);
foreach ($categories as $catName) {
$this->addOneCat($catName);
$this->load('categories');
}
return $this;
}
public function buildCatArray($categories): array
{
if (is_array($categories)) {
$array = $categories;
} elseif ($categories instanceof BaseCollection) {
$array = $this->buildCatArray($categories->all());
} elseif (is_string($categories)) {
$array = preg_split(
'#[' . preg_quote(',;', '#') . ']#',
$categories,
null,
PREG_SPLIT_NO_EMPTY
);
} else {
throw new \ErrorException(
__CLASS__ . '::' . __METHOD__ . ' expects parameter 1 to be string, array or Collection; ' .
gettype($categories) . ' given'
);
}
return array_filter(
array_map('trim', $array)
);
}
protected function addOneCat(string $catName)
{
$cat = Self::findOrCreate($catName);
$catKey = $cat->getKey();
if (!$this->cats->contains($catKey)) {
$this->categories()->attach($catKey);
}
}
public function find(string $catName)
{
return $this->Category::$catName->first();
}
public function findOrCreate(string $catName): Category
{
$cat = $this->find($catName);
if (!$cat) {
$cat = $this->Category::create(['name' => $catName]);
}
return $cat;
}
This my Blog Controller file store class
BlogController.php
public function store(Request $request)
{
$data = new Blog;
$data->title = $request->title;
$data->content = $request->content;
$tags = explode(',',$request->tag);
$categories = explode(',',$request->category);
$data->save();
$data->tag($tags);
$data->category($categories);
}
Best wishes

Laravel belongsTo with condition and eager load

I have a Post model associated to a Section model, which depend on an extra condition to work:
<?php
class Post extends Base
{
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat')->where('website', $this->website);
}
}
When I want to retrieve a Post and get it's associated section, I can do it as:
$post = Post::first();
echo $post->section->name; // Output the section's name
However, when trying to get the section using an eager load:
Post::with(['section'])->chunk(1000, function ($posts) {
echo $post->section->name;
});
Laravel throw the following exception :
PHP error: Trying to get property of non-object
When I do a debug of a Post object returned by the above eager load query, I notice that the section relationship is null.
Note that it is working fine if I remove the condition from the belongsTo association.
Do you guys have any ideas why it's happening?
As mentioned in my comment, where shouldn't be used in the relationship definition. Hence, your relation definition is good with just
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat');
}
and you can eager load in this way (not giving out the exact query with chunk etc)
Post::with(['section' => function ($query) use ($request) {
$query->where('website', $request['website'])
}])->get()->first();
i.e. when you pass the variable website in request or else use any other variable in a similar way.
I hope that explains. Please add comments if anything is unclear.
You can achieve it by defining custom relationship.
BelongsToWith.php
<?php
declare(strict_types=1);
namespace App\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BelongsToWith extends BelongsTo
{
/**
* #var array [$foreignColumn => $ownerColumn, ...] assoc or [$column, ...] array
*/
protected $conditions = [];
public function __construct(array $conditions, Builder $query, Model $child, string $foreignKey, string $ownerKey, string $relation)
{
$this->conditions = $conditions;
parent::__construct($query, $child, $foreignKey, $ownerKey, $relation);
}
public function addConstraints()
{
if (static::$constraints) {
// Add base constraints
parent::addConstraints();
// Add extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$this->getQuery()->where($this->related->getTable() . '.' . $value, '=', $this->child->{$key});
}
}
}
public function addEagerConstraints(array $models)
{
// Ignore empty models
if ([null] === $this->getEagerModelKeys($models)) {
parent::addEagerConstraints($models);
return;
}
$this->getQuery()->where(function (Builder $query) use ($models) {
foreach ($models as $model) {
$query->orWhere(function (Builder $query) use ($model) {
// Add base constraints
$query->where($this->related->getTable() . '.' . $this->ownerKey, $model->getAttribute($this->foreignKey));
// Add extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$query->where($this->related->getTable() . '.' . $value, $model->getAttribute($key));
}
});
}
});
}
public function match(array $models, Collection $results, $relation)
{
$dictionary = [];
foreach ($results as $result) {
// Base constraints
$keys = [$result->getAttribute($this->ownerKey)];
// Extra constraints
foreach ($this->conditions as $key => $value) {
$keys[] = $result->getAttribute($value);
}
// Build nested dictionary
$current = &$dictionary;
foreach ($keys as $key) {
$current = &$current[$key];
}
$current = $result;
unset($current);
}
foreach ($models as $model) {
$current = $dictionary;
// Base constraints
if (!isset($current[$model->{$this->foreignKey}])) {
continue;
}
$current = $current[$model->{$this->foreignKey}];
// Extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
if (!isset($current[$model->{$key}])) {
continue 2;
}
$current = $current[$model->{$key}];
}
// Set passed result
$model->setRelation($relation, $current);
}
return $models;
}
}
HasExtendedRelationships.php
<?php
declare(strict_types=1);
namespace App\Database\Eloquent\Concerns;
use App\Database\Eloquent\Relations\BelongsToWith;
use Illuminate\Support\Str;
trait HasExtendedRelationships
{
public function belongsToWith(array $conditions, $related, $foreignKey = null, $ownerKey = null, $relation = null): BelongsToWith
{
if ($relation === null) {
$relation = $this->guessBelongsToRelation();
}
$instance = $this->newRelatedInstance($related);
if ($foreignKey === null) {
$foreignKey = Str::snake($relation) . '_' . $instance->getKeyName();
}
$ownerKey = $ownerKey ?: $instance->getKeyName();
return new BelongsToWith($conditions, $instance->newQuery(), $this, $foreignKey, $ownerKey, $relation);
}
}
Then:
class Post extends Base
{
use HasExtendedRelationships;
public function section(): BelongsToWith
{
return $this->belongsToWith(['website'], App\Models\Section::class, 'id_cat');
}
}
$posts = Post::with('section')->find([1, 2]);
Your Eager Loading query will be like:
select * from `sections`
where (
(
`sections`.`id` = {$posts[0]->id_cat}
and `sections`.`website` = {$posts[0]->website}
)
or
(
`sections`.`id` = {$posts[1]->id_cat}
and `sections`.`website` = {$posts[1]->website}
)
)

yii user: upload image on registration form

I want to upload profile picture in yii user. By so much digging, i came to know that i need to make a profilefield, which i did and called "picture" and then in view of modules/user/registrtaion i need to write this code, given below is my registration view file.
<?php
$profileFields=$profile->getFields();
if ($profileFields) {
foreach($profileFields as $field) {
?>
<div class="row">
<?php
if ($widgetEdit = $field->widgetEdit($profile)) {
echo $widgetEdit;
} elseif ($field->range) {
echo $form->dropDownListControlGroup($profile,$field->varname,Profile::range($field->range));
} elseif ($field->field_type=="TEXT") {
echo$form->textArea($profile,$field->varname,array('rows'=>6, 'cols'=>50));
}
// I added this below elseif for picture upload
elseif ($field->field_type=="VARCHAR" && $field->field_size=="500") {
echo$form->fileField($profile,$field->varname,array('rows'=>6, 'cols'=>50));
}else {
echo $form->textFieldControlGroup($profile,$field->varname,array('size'=>60,'maxlength'=>(($field->field_size)?$field->field_size:255)));
}
?>
and i am hanlding this profile picture in modules/model/registration.php like this. Given below is the code.
<?php
class RegistrationForm extends User {
public $verifyPassword;
public $verifyCode;
public function rules() {
$rules = array(
array('username, password, verifyPassword, email', 'required'),
array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
array('password', 'length', 'max'=>128, 'min' => 4,'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
array('email', 'email'),
array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
//array('verifyPassword', 'compare', 'compareAttribute'=>'password', 'message' => UserModule::t("Retype Password is incorrect.")),
array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
// adding this liine
array('picture', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'), //
);
if (!(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')) {
array_push($rules,array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')));
}
array_push($rules,array('verifyPassword', 'compare', 'compareAttribute'=>'password', 'message' => UserModule::t("Retype Password is incorrect.")));
return $rules;
}
}
and finally in the controller i handle the picture like this given below is the code.
<?php
class RegistrationController extends Controller
{
public $defaultAction = 'registration';
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
/**
* Registration user
*/
public function actionRegistration() {
$model = new RegistrationForm;
$profile=new Profile;
$profile->regMode = true;
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')
{
echo UActiveForm::validate(array($model,$profile));
Yii::app()->end();
}
if (Yii::app()->user->id) {
$this->redirect(Yii::app()->controller->module->profileUrl);
} else {
if(isset($_POST['RegistrationForm'])) {
// handling picture
$rnd = rand(0, 9999); // generate random number between 0-9999
$model->attributes = $_POST['RegistrationForm'];
$uploadedFile = CUploadedFile::getInstance($model, 'picture');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->picture = $fileName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../img/' . $fileName);
$this->redirect(array('view', 'id' => $model->id));
}
// hanlding picture ends
$profile->attributes=((isset($_POST['Profile'])?$_POST['Profile']:array()));
if($model->validate()&&$profile->validate())
{
$soucePassword = $model->password;
$model->activkey=UserModule::encrypting(microtime().$model->password);
$model->password=UserModule::encrypting($model->password);
$model->verifyPassword=UserModule::encrypting($model->verifyPassword);
$model->superuser=0;
$model->status=((Yii::app()->controller->module->activeAfterRegister)?User::STATUS_ACTIVE:User::STATUS_NOACTIVE);
if ($model->save()) {
$profile->user_id=$model->id;
$profile->save();
if (Yii::app()->controller->module->sendActivationMail) {
$activation_url = $this->createAbsoluteUrl('/user/activation/activation',array("activkey" => $model->activkey, "email" => $model->email));
UserModule::sendMail($model->email,UserModule::t("You registered from {site_name}",array('{site_name}'=>Yii::app()->name)),UserModule::t("Please activate you account go to {activation_url}",array('{activation_url}'=>$activation_url)));
}
if ((Yii::app()->controller->module->loginNotActiv||(Yii::app()->controller->module->activeAfterRegister&&Yii::app()->controller->module->sendActivationMail==false))&&Yii::app()->controller->module->autoLogin) {
$identity=new UserIdentity($model->username,$soucePassword);
$identity->authenticate();
Yii::app()->user->login($identity,0);
$this->redirect(Yii::app()->controller->module->returnUrl);
} else {
if (!Yii::app()->controller->module->activeAfterRegister&&!Yii::app()->controller->module->sendActivationMail) {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Contact Admin to activate your account."));
} elseif(Yii::app()->controller->module->activeAfterRegister&&Yii::app()->controller->module->sendActivationMail==false) {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Please {{login}}.",array('{{login}}'=>CHtml::link(UserModule::t('Login'),Yii::app()->controller->module->loginUrl))));
} elseif(Yii::app()->controller->module->loginNotActiv) {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Please check your email or login."));
} else {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Please check your email."));
}
$this->refresh();
}
}
} else $profile->validate();
}
$this->render('/user/registration',array('model'=>$model,'profile'=>$profile));
}
}
}
so the problem is,, when i enter the details on registraion form and upload a picture i get this error Property "RegistrationForm.picture" is not defined. The problem lies in controller line number 45 which is
$model->picture = $fileName;
I already have picture field in "profiles" table. But the thing is i am totally confused, and neither at yii framework forum nor at stackoverflow i found a proper documentation over this thing. Please help.
My profile.php (model) code
<?php
class Profile extends UActiveRecord
{
/**
* The followings are the available columns in table 'profiles':
* #var integer $user_id
* #var boolean $regMode
*/
public $regMode = false;
private $_model;
private $_modelReg;
private $_rules = array();
/**
* Returns the static model of the specified AR class.
* #return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return Yii::app()->getModule('user')->tableProfiles;
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
if (!$this->_rules) {
$required = array();
$numerical = array();
$float = array();
$decimal = array();
$rules = array();
$model=$this->getFields();
foreach ($model as $field) {
$field_rule = array();
if ($field->required==ProfileField::REQUIRED_YES_NOT_SHOW_REG||$field->required==ProfileField::REQUIRED_YES_SHOW_REG)
array_push($required,$field->varname);
if ($field->field_type=='FLOAT')
array_push($float,$field->varname);
if ($field->field_type=='DECIMAL')
array_push($decimal,$field->varname);
if ($field->field_type=='INTEGER')
array_push($numerical,$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'] = UserModule::t($field->error_message);
array_push($rules,$field_rule);
}
if ($field->other_validator) {
if (strpos($field->other_validator,'{')===0) {
$validator = (array)CJavaScript::jsonDecode($field->other_validator);
foreach ($validator as $name=>$val) {
$field_rule = array($field->varname, $name);
$field_rule = array_merge($field_rule,(array)$validator[$name]);
if ($field->error_message) $field_rule['message'] = UserModule::t($field->error_message);
array_push($rules,$field_rule);
}
} else {
$field_rule = array($field->varname, $field->other_validator);
if ($field->error_message) $field_rule['message'] = UserModule::t($field->error_message);
array_push($rules,$field_rule);
}
} elseif ($field->field_type=='DATE') {
$field_rule = array($field->varname, 'type', 'type' => 'date', 'dateFormat' => 'yyyy-mm-dd', 'allowEmpty'=>true);
if ($field->error_message) $field_rule['message'] = UserModule::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'] = UserModule::t($field->error_message);
array_push($rules,$field_rule);
}
if ($field->range) {
$field_rule = array($field->varname, 'in', 'range' => self::rangeRules($field->range));
if ($field->error_message) $field_rule['message'] = UserModule::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(',',$float), 'type', 'type'=>'float'));
array_push($rules,array(implode(',',$decimal), 'match', 'pattern' => '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/'));
$this->_rules = $rules;
}
return $this->_rules;
}
/**
* #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.
$relations = array(
'user'=>array(self::HAS_ONE, 'User', 'id'),
);
if (isset(Yii::app()->getModule('user')->profileRelations)) $relations = array_merge($relations,Yii::app()->getModule('user')->profileRelations);
return $relations;
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
$labels = array(
'user_id' => UserModule::t('User ID'),
);
$model=$this->getFields();
foreach ($model as $field)
$labels[$field->varname] = ((Yii::app()->getModule('user')->fieldsMessage)?UserModule::t($field->title,array(),Yii::app()->getModule('user')->fieldsMessage):UserModule::t($field->title));
return $labels;
}
private function rangeRules($str) {
$rules = explode(';',$str);
for ($i=0;$i<count($rules);$i++)
$rules[$i] = current(explode("==",$rules[$i]));
return $rules;
}
static public function range($str,$fieldValue=NULL) {
$rules = explode(';',$str);
$array = array();
for ($i=0;$i<count($rules);$i++) {
$item = explode("==",$rules[$i]);
if (isset($item[0])) $array[$item[0]] = ((isset($item[1]))?$item[1]:$item[0]);
}
if (isset($fieldValue))
if (isset($array[$fieldValue])) return $array[$fieldValue]; else return '';
else
return $array;
}
public function widgetAttributes() {
$data = array();
$model=$this->getFields();
foreach ($model as $field) {
if ($field->widget) $data[$field->varname]=$field->widget;
}
return $data;
}
public function widgetParams($fieldName) {
$data = array();
$model=$this->getFields();
foreach ($model as $field) {
if ($field->widget) $data[$field->varname]=$field->widgetparams;
}
return $data[$fieldName];
}
public function getFields() {
if ($this->regMode) {
if (!$this->_modelReg)
$this->_modelReg=ProfileField::model()->forRegistration()->findAll();
return $this->_modelReg;
} else {
if (!$this->_model)
$this->_model=ProfileField::model()->forOwner()->findAll();
return $this->_model;
}
}
}
Your registration form model extends user class. Your field picture is not the attribute of any of them.
It will be the attribute of profile model. You should move your rule to profile model.
Edit: In your profile model put this line
array_push($rules,array('picture', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'));
before the line
$this->_rules = $rules;
this code is not tested but it should work.

Resources