I am trying to create a new entry via a form post that will come from a third party, by doing this in my plugin's service class:
$entry = EntryModel::populateModel(array(
'sectionId' => 1,
'typeId' => 2
));
$entry->getContent()->setAttribute('reference', craft()->request->getPost('someReferenceField'));
craft()->entries->saveEntry($entry);
The reference field is a custom FieldType (https://github.com/fuel-digital/Craft-Unique-Text-FieldType/blob/develop/uniquetextfield/fieldtypes/UniqueTextField_UniqueTextFieldType.php) where I am validating the submitted value is unique for this EntryType (in this case an Entry rather than a User/Asset/etc).
That FieldType works fine in the control panel but I'm getting an error when submitting via my plugin as $this->element is null within the FieldType's valueExists() method.
I can get around this by creating a new EntryModel like so:
/**
* Checks if another entry exists with the given value
*
* @param string $value The value to check
* @return bool
*/
private function valueExists($value)
{
if ( ! $this->element)
{
$this->element = new EntryModel();
}
$existing = craft()->elements->getCriteria($this->element->elementType)->first(array(
$this->model->handle => $value
));
return ($existing && $existing->id != $this->element->id);
}
But that means the FieldType will only work with Entry elements, and not Users, Assets etc.
As the plugin works fine in the control panel, I assume I'm missing something in my plugin service?