FieldType's element attribute is null 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' =&gt; 1, 
    'typeId' =&gt; 2
));

$entry-&gt;getContent()-&gt;setAttribute('reference', craft()-&gt;request-&gt;getPost('someReferenceField'));

craft()-&gt;entries-&gt;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-&gt;element)
    {
        $this-&gt;element = new EntryModel();
    }

    $existing = craft()-&gt;elements-&gt;getCriteria($this-&gt;element-&gt;elementType)-&gt;first(array(
        $this-&gt;model-&gt;handle =&gt; $value
    ));

    return ($existing &amp;&amp; $existing-&gt;id != $this-&gt;element-&gt;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?
Found a solution by how Entry Form handles it.

Assuming you've posted fields with names such as jobData[reference]:

$fieldsLocation = craft()-&gt;request-&gt;getParam('fieldsLocation', 'jobData');

$this-&gt;entry-&gt;setContentFromPost($fieldsLocation);


The setContentFromPost() method of the EntriesController class sets the ElementType.