1

The example below will continue to save entries with the same title and slug.

Is there a built in validation when using craft()->entries->saveEntry?

$entry = new EntryModel();
$entry->sectionId = $sectionId;
$entry->getContent()->setAttributes(array(
            'title' => '123',
        ));
$re = craft()->entries->saveEntry($entry);

1 Answer 1

2

You could hook into the entries.beforeSaveEntry event like this:

craft()->on('entries.beforeSaveEntry', function (Event $e) {

    // Get the entry we're saving, and it's title
    $entry = $e->params['entry'];
    $title = $entry->getContent()->title;

    // Look for existing entries with the same title
    $existingEntry = craft()->elements->getCriteria(ElementType::Entry, [
      'title' => $title,
      'id' => $entry->id ? 'not '.$entry->id : null
    ])->first();

    // If an existing entry is found, prevent saving and pass an error message
    if ($existingEntry) {
      $entry->addErrors([
        'title' => Craft::t("An entry titled $title already exists"),
      ]);
      $e->performAction = false;
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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