2

Ok I'm buliding a plugin which changes the category of a news article if another article is set to the same category so that only one article is set as the featured category.

So far I have the onSaveBeforeEntry event working ok I'm just stuck on the updating the existing featured article. This is the flow so far followed by the code I'm having an issue with.

  1. First check the article being saved to see if the category is set.
  2. If it is check it has not changed.
  3. If it has changed and it has changed to 'Featured' use getCriteria to find the entry that is currently set to 'Featured'
  4. (the sticking point) set the existing featured entry category to 'Latest' and save it.
  5. Finish off saving the entry.

Point 4 is not changing the existing featured article data.

The code I have is:

// Get the current featured news entry
$entry_criteria = craft()->elements->getCriteria(ElementType::Entry);
$entry_criteria->section = 'news';
$entry_criteria->search = 'category:Featured';
$featuredEntry = $entry_criteria->first();

// update exiting featured article and mark as latest
$featuredEntry->setContentFromPost(array('category' => 'Latest'));
$success = craft()->entries->saveEntry($featuredEntry);

Getting the existing entry works, changing the category and re-saving does not.

What am I missing?

Any help appreciated.

Ta

1

You need to set an array of category IDs to your categories field.

$featuredEntry->setContentFromPost(array(
    'category' => array(42)
));

Query for it with an craft.categories criteria model or if you're hardcoding it anyways you could just look it up in the CP:

example.com/admin/categories/myCategoryGroup/42-myCategoryHandle

| improve this answer | |
  • cheers @carlcs perfect solution – Lettie Aug 26 '15 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.