3

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?

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.

1
  • I didn't know that you could set/access fields not assigned to the section's field Layout. That's good to know! – Douglas McDonald Feb 5 '15 at 22:58

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.