1

I'm currently creating a plugin for craft and have stumbled across a slight problem. I'll try summarise of what I am doing and what I am trying to achieve.

So, I'm trying creating a plugin which will update entries within craft via an external API. I have managed to get the initial save to work using these following lines:

$entry = new EntryModel();
$entry->getContent()->title = $project->name;
$entry->sectionId = 10;
craft()->entries->saveEntry($entry);

The issue arises when I'm trying to update the model. Obviously, I don't want to duplicate entries.

I can get the entry using this line:

EntryRecord::model()->findById(45);

(this is just used for testing, eventually I will be getting the record via a custom variable).

What I'm trying to do here is update the title of this record, from what I can see this is stored in the craft_content table.

Basically what I'd like to do is something like :

EntryModel::model()->findByAttributes(array('title'=>$project->name);

So I can then update the content title of that row. I can see I can't do it this way, would you be able point me in the right direction?

2

It sort of depends on what information you have to identify the entry. If your external service knows the entry id that would be the most direct — otherwise you would have to find the entry by some other unique property.

To update an entry (given $entryId, $newTitle):

$entry = craft()->entries->getEntryById($entryId);
if ($entry) {
    $entry->getContent()->setAttributes(array(
        'title' => $newTitle
    ));
    craft()->entries->saveEntry($entry);
}

To update an entry (given $sectionHandle, $title, and $newTitle - or other unique property):

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = $sectionHandle;
$criteria->title = $title;
$entries = craft()->elements->findElements($criteria);

foreach ($entries as $entry) {
    $entry->getContent()->setAttributes(array(
        'title' => $newTitle
    ));
    craft()->entries->saveEntry($entry);
}

Could also use the 'search' method (although less reliable):

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->search = 'fieldHandle:searchstring';

In the last two cases, would need to handle the possibility that more than 1 entry is returned.

Also, when creating entries might want to include the authorId and typeId, in addition to sectionId:

$entry = new EntryModel();
$entry->sectionId  = $sectionId
$entry->typeId     = $typeId
$entry->authorId   = $authorId;
$entry->enabled    = true;
$entry->getContent()->setAttributes(array(
    'title' => $title
));
craft()->entries->saveEntry($entry);

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.