Set values of Dropdown/Select Attribute Programatically

David ReederBy David Reeder, 27 October 2024

There may be a time when it's easier to set attribute values programmatically, rather than in the Dashboard.  We can do the following:

use Concrete\Core\Attribute\Type as AttributeType;
use Concrete\Attribute\Select\Option as SelectAttributeTypeOption;

// Check if exists, if not create it
$attr = CollectionAttributeKey::getByHandle('attr_handle'); // by handle
if (!is_object($attr)) {
    $type = AttributeType::getByHandle('select'); 
    $args = array ( 
        'akHandle' => 'attr_handle',
        'akName'=> t('Attribute Name'),
    );
    $attr = CollectionAttributeKey::add($type, $args, $pkg = null);
}

Next, we want to add values to it:

$attrOption = SelectAttributeTypeOption::add($attr, 'My Option 1');
$attrOption = SelectAttributeTypeOption::add($attr, 'My Option 2');

Add from an array:

$catValues = array(
  "Accounting/Finance",
  "Advertising/Public Relations",
  "Aerospace/Aviation",
  "Arts/Entertainment/Publishing",
);

foreach($catValues as $catVal) {
   $attrOption = SelectAttributeTypeOption::add($attr, $catVal);
}

Back