How to programmatically add keywords to an existing page

Permalink
Hi,
I'm trying to programmatically add keywords to an existing page.

I get keywords from a form, they look like $tags="kw1,kw2,kw3".

Then i try with this :
$importTags = explode(",", $tags);
   $ak = CollectionAttributeKey::getByHandle('tags');
   $tagValues = array();
   foreach ($importTags as $tag) {
      if (!$tagValueObject = SelectAttributeTypeOption::getByValue($tag, $ak)) {
         $tagValueObject = SelectAttributeTypeOption::add($ak, $tag);
      }
      $tagValues[] = $tagValueObject;
   }
   $newPage->setAttribute('tags', $tagValues);


This code seems to be used in 5.7, I work on 5.8.
I get this error : "concrete5 Class 'SelectAttributeTypeOption' not found"

If i declare this :
use Concrete\Core\Entity\Attribute\Value\Value\SelectValueOption as SelectAttributeTypeOption;


I get this error : "Call to undefined method Concrete\Core\Entity\Attribute\Value\Value\SelectValueOption::getByValue()"

I don't find any documentation to do this correctly.
Any idea ?

crostif
 
hutman replied on at Permalink Reply
hutman
Looking at how this works in the core I think this might work

use \Concrete\Core\Entity\Attribute\Value\Value\SelectValueOption;
$tagValues = array();
$importTags = explode(",", $tags);
$ak = CollectionAttributeKey::getByHandle('tags');
$orm = \Database::connection()->getEntityManager();
$repository = $orm->getRepository('\Concrete\Core\Entity\Attribute\Value\Value\SelectValueOption');
if ($ak) {
   $existingList = $ak->getAttributeKeySettings()->getOptionList();
}
foreach ($importTags as $tag) {
   if (isset($existingList) && is_object($existingList)) {
      $tagValueObject = $repository->findOneBy([
         'list' => $existingList,
         'value' => $tag,
      ]);
crostif replied on at Permalink Reply
crostif
Thank you for this code...
It give no error in response. But the tags aren't saved into the database, so they are not saved as attribute of the page.
hutman replied on at Permalink Reply
hutman
Have you tried dumping it out in different places to see what is going wrong?

I don't know 100% but I thought you just had to send in an array of values not an array of objects.
crostif replied on at Permalink Reply
crostif
I've just tried it as it. I don't really understand all these lines... In fact i don't understand how concrete5 proceed when saving tags and affects them to a page, so i am lost àt the moment... I can't find documentation...

Not sure it is the main thing i don't understand, but from where do you get $option at the end of the code ?
hutman replied on at Permalink Reply
hutman
Ah! That's a typo, should be $tagValueObject
crostif replied on at Permalink Reply
crostif
Ha ha !!! As a matter of fact, It was the main problem... Now it works very well.
Thank you very much ! I'll work on it !