0

I am trying to create dynamic attributes, properties and rules in model class from one table values as columns.

Consider i have one table named "XXX" which has column "Name" now i want to create model class with rules,properties and attributes using the Name values stored in DB.

I am new to YII Framework Can anybody give idea to this ?

1
  • i'll mock sonething up to pint you in the right direction, give me 10 mins Commented Jan 8, 2014 at 15:07

1 Answer 1

1

This is something i mocked up quickly, I hope it points ou in the right direction

$sql="SELECT 'Name' FROM XXX";
$names =$connection->createCommand($sql)->query()->readAll();

$myDynamicObject = new DynamicModel($names);

class DynamicModel extends CModel
{
    protected $_members = array();


    public function __construct($nameFields)
    {
        foreach ($nameFields as $member) {
            $this->_members[$member] = null;
        }

        parent::__construct();
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        $allMembers = implode(', ', array_keys($this->_members));
        return array(
            array($allMembers, 'required'),
        );
    }

    public function __get($attribute)
    {

        if (in_array($attribute, array_keys($this->_members))) {
            return $this->_members[$attribute];
        } else {
            return parent::__get($attribute);
        }
    }

    public function __set($attribute, $value)
    {
        if (in_array($attribute, array_keys($this->_members))) {
            return $this->_members[$attribute] = $value;
        } else {
            return parent::__set($attribute, $value);
        }
    }

    public function getAttributes()
    {
        return $this->_members;
    }

    public function setAttributes($attributes)
    {
        $this->_members = $attributes;
    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

I am getting this error Fatal error: Class 'COutputProcessor' not found in D:\xampp\htdocs\ccvv7\protected\models\DynamicModel.php on line 56
@Manadh : no idea why though, i dont see it has anything to do with the code i wrote
the first 2 lines ? and as i said, dont use it as a script, use it as inspiration to make your own script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.