Skip to content

Manage sets of EAV attributes

iAchilles edited this page Oct 8, 2014 · 1 revision

EavSet class represents methods to manipulate a set of EAV attributes (creating a new set, adding an attribute to a set, removing an attribute from a set, removing an attribute set).

To create a new attribute set and save data to the database, you need to write the following code:

$set = new EavSet();
$set->name = 'Set'; // Required field
$set->save();

To add a new EAV attribute to the set, you need to write the following code:

$attribute = new EavAttribute(); //Create an instance of the class EavAttribute
$attribute->name = 'attr1';
$attribute->label = 'Attribute Label';
$attribute->type = EavAttribute::TYPE_SINGLE;
$attribute->data_type = EavAttribute::DATA_TYPE_INT;

$set = new EavSet();
$set->name = 'Set';
$set->addEavAttribute($attribute);
$set->save();

When you add a new attribute to the set it will be automatically saved (if the attribute is valid). But you still may call the method EavAttribute::save() before adding an attribute to the set. The following code example is equivalent to the previous example:

$attribute = new EavAttribute();
$attribute->name = 'attr1';
$attribute->label = 'Attribute Label';
$attribute->type = EavAttribute::TYPE_SINGLE;
$attribute->data_type = EavAttribute::DATA_TYPE_INT;
$attribute->save(); // Call the method EavAttribute::save()

$set = new EavSet();
$set->name = 'Set';
$set->addEavAttribute($attribute);
$set->save();

You also can add an existing attribute to the set:

$set = new EavSet();
$set->name = 'Set';
$set->addEavAttribute(EavAttribute::model()->findByPk(1)); //Adding an instance of the class EavAttribute
$set->addEavAttribute(5); //You can specify a primary key value of the attribute you want to add
$set->save();

To remove an attribute from the set you must call the method EavSet::removeEavAttribute() and specify the attribute that must be removed:

$set = EavSet::model()->findByPk(1);
$set->removeEavAttribute(5); //Primary key value of the attribute that must be removed
$set->removeEavAttribute(EavAttribute::model()->findByPk(2)); // Or an instance of the class EavAttribute
$set->save();

The following code fragment shows how to delete an existing set of EAV attributes:

$set = EavSet::model()->findByPk(1);
$set->delete();

To delete an existing set of EAV attributes you also can call methods CActiveRecord::deleteAll(), CActiveRecord::deleteByPk(), CActiveRecord::deleteAllByAttributes(), these methods are available in the class EavAttribute because it is derived from CActiveRecord.

Note, the set of EAV attributes cannot be deleted if some records (EavActiveRecord) are referenced to the set (foreign key constraint).