4

In a plugin I am creating I want to add a property to some entries.

Ideally this property would be hidden from the admin user, as I don't want them to edit it.

At the moment I am trying to do something like this (simplified):

$criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'dogs';
$entries = $criteria->find();

foreach ($entries as $entry) {
    $entry->secretName = urlencode($entry->title);
    craft()->entries->saveEntry($entry);
endforeach;

But this produces the error 'Property "Craft\EntryModel.secretName" is not defined.'

Does anyone know how to do what I am trying to do? Is there a way to set a new property to just this section?

mattl
  • 330
  • 2
  • 6

1 Answers1

5

You need to create the field in the CMS, however you don't need to assign it to any section. It should still be available to your plugin and twig templates.

The other reason your code will result in an error is because $entry->secretName is in fact being processed by the BaseElementModel magic getter method, so is the same as writing $entry->getFieldValue('secretName'), which obviously cannot be set to a new value.

The proper way to do this is using the setContent method as follows:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'dogs';
$entries = $criteria->find();

foreach ($entries as $entry) {
    $entry->setContent(array(
        'secretName' => urlencode($entry->title)
    ));
    craft()->entries->saveEntry($entry);
endforeach;

See this answer for a more thorough explanation on setting entry content.

Ben Croker
  • 7,341
  • 26
  • 55