<p>I am not really clear on what you are trying to do. My guess is you are trying to add your own validation to saving an element and trying to block that with your own custom checking of content values etc?</p>

<p>I don't think listening to the event will help as you cannot send a message to say this element is not valid from an event listener - the event does pass you a element that is about to be saved but you cant return the modified element from the listener.</p>

<p>What I would suggest is building a custom fieldType that contains some validation rules that peeks in at the content of other fields.</p>

<pre><code>class My_CustomFieldType extends BaseFieldType
{

/**
 All the normal filetype stuff like name etc here.
*/

public function validate($value)
{
  $errors = parent::validate($value);

  if (!is_array($errors))
  {
    $errors = array();
  }

  // DO you logic here to test then set an $variable to true or false
  // if your conditions are met then add to the $errors array below if there is a problem.
  // if you want to access other field in this element do this:
  // 
  //   $owner     = $this-&gt;element;
  //   $fieldData = $owner-&gt;getContent()-&gt;getAttribute(array('sectionId'));
  //


  if ($variable){
    $errors[] = Craft::t('You are not allowed to edit this element.');
  }


  if ($errors)
  {
    return $errors;
  }
  else
  {
    return true;
  }
}

}
</code></pre>

<p>Im thinking that this will be able to stop the entry being saved. Hopefully thats what you were looking for.</p>

CC BY-SA 3.0
2014-08-07T20:56:42.053Z
Not really trying to stop an element from beeing saved, I'd like to stop it from getting populated. Eg. I have an internal authorisation subsystem certain users of certain companies are not allowed to see certain entries not beloning to their companies. I'll give it a try using a custom field type. Thanks for the extensive answer.
pythic
CC BY-SA 3.0
2014-08-07T23:17:07.730Z
When you say that you don't want the entry being populated are you saying that you still want the entry to be saved but remove data from some fields before saving?
Luke Holder
CC BY-SA 3.0
2014-08-08T08:38:27.047Z
Luke, no I do not want the entry saved. I just want the out of the box entrylist overview (the menu item "Enrties" not to show certain rows based on x
pythic
CC BY-SA 3.0
2014-08-08T15:52:38.787Z
Oh, there is no way of doing that with events or hooks as far as I know.
Luke Holder
CC BY-SA 3.0
2014-08-08T15:55:15.040Z
Populating does not mean listing though. So I think the your using the word populating incorrectly in this instance. The craft onelementpopulation refers to when an element is instantiating with all it's data as an object.
Luke Holder
CC BY-SA 3.0
2014-08-07T08:33:03.300Z
2014-08-07T08:33:03.300Z
Luke Holder
<p>I have an event listener on elements.onPopulateElement, what I want is make a last minute decision if I want to populate or not. I have certain customfields on an admin CP user (eg company). All entries (in this case in the section "normalUsers", these are entries not actual users) have that same field company (companiesDropdown). I can detect in the code below that the entries' companiesDropdown field does not match the currentUsers companyDropdown field. But how can I tell the calling piece of code not the populate this element?</p>

<p>The following code it initialised in the plugin init method</p>

<pre><code>private function _initEventPopulateNormalUser() {
    craft()-&gt;on('elements.onPopulateElement', function(Event $event) {
        $this-&gt;_getNormalUserSection();
        // HERE we check if we actually save a normalUser section entry, may be a bit brute force, we will polish that later
        $lCompanyIdEntry = $event-&gt;params['element']-&gt;getAttributes(array('sectionId'));
        if (! isset($lCompanyIdEntry['sectionId'])) return;
        if ($lCompanyIdEntry['sectionId'] != $this-&gt;mNormalUsersSection) return;

        $lCurrentUser = craft()-&gt;userSession-&gt;getUser();
        $lCompanyIdUser = $lCurrentUser-&gt;companiesDropdown[0]-&gt;id;

        $lEntryCompanyId = $event-&gt;params['element']-&gt;companiesDropdown-&gt;first()-&gt;id;

        if ($lCompanyIdUser != $lEntryCompanyId) {
            /*
                Somewhere here I want the element to be emptied and
                all functionality calling it, like a elementindex template,
                to not show the element in its listing
            */
        }
    });
}


private function _getNormalUserSection()
{
    if (is_null($this-&gt;mNormalUsersSection)) {
        $lSection = craft()-&gt;sections-&gt;getSectionByHandle('normalUsers');
        $this-&gt;mNormalUsersSection = $lSection-&gt;id;
    }
}
</code></pre>

<plugin-development><elementtype><events>
How do I stop an element from populating?
# How do I stop an element from populating?

(Asked by: username_0 on 2014-07-30)

I have an event listener on elements.onPopulateElement, what I want is make a last minute decision if I want to populate or not. I have certain customfields on an admin CP user (eg company). All entries (in this case in the section "normalUsers", these are entries not actual users) have that same field company (companiesDropdown). I can detect in the code below that the entries' companiesDropdown field does not match the currentUsers companyDropdown field. But how can I tell the calling piece of code not the populate this element?
The following code it initialised in the plugin init method
private function _initEventPopulateNormalUser() {
    craft()->on('elements.onPopulateElement', function(Event $event) {
        $this->_getNormalUserSection();
        // HERE we check if we actually save a normalUser section entry, may be a bit brute force, we will polish that later
        $lCompanyIdEntry = $event->params['element']->getAttributes(array('sectionId'));
        if (! isset($lCompanyIdEntry['sectionId'])) return;
        if ($lCompanyIdEntry['sectionId'] != $this->mNormalUsersSection) return;

        $lCurrentUser = craft()->userSession->getUser();
        $lCompanyIdUser = $lCurrentUser->companiesDropdown[0]->id;

        $lEntryCompanyId = $event->params['element']->companiesDropdown->first()->id;

        if ($lCompanyIdUser != $lEntryCompanyId) {
            /*
                Somewhere here I want the element to be emptied and
                all functionality calling it, like a elementindex template,
                to not show the element in its listing
            */
        }
    });
}


private function _getNormalUserSection()
{
    if (is_null($this->mNormalUsersSection)) {
        $lSection = craft()->sections->getSectionByHandle('normalUsers');
        $this->mNormalUsersSection = $lSection->id;
    }
}

**Tags:** plugin-development, elementtype, events


---

## 1 answers

### Answer by username_1 on 2014-08-07. Score: 5

I am not really clear on what you are trying to do. My guess is you are trying to add your own validation to saving an element and trying to block that with your own custom checking of content values etc?
I don't think listening to the event will help as you cannot send a message to say this element is not valid from an event listener - the event does pass you a element that is about to be saved but you cant return the modified element from the listener.
What I would suggest is building a custom fieldType that contains some validation rules that peeks in at the content of other fields.
class My_CustomFieldType extends BaseFieldType
{

/**
 All the normal filetype stuff like name etc here.
*/

public function validate($value)
{
  $errors = parent::validate($value);

  if (!is_array($errors))
  {
    $errors = array();
  }

  // DO you logic here to test then set an $variable to true or false
  // if your conditions are met then add to the $errors array below if there is a problem.
  // if you want to access other field in this element do this:
  // 
  //   $owner     = $this->element;
  //   $fieldData = $owner->getContent()->getAttribute(array('sectionId'));
  //


  if ($variable){
    $errors[] = Craft::t('You are not allowed to edit this element.');
  }


  if ($errors)
  {
    return $errors;
  }
  else
  {
    return true;
  }
}

}

Im thinking that this will be able to stop the entry being saved. Hopefully thats what you were looking for.

> **Comments:**
> **username_0**: Not really trying to stop an element from beeing saved, I'd like to stop it from getting populated. Eg. I have an internal authorisation subsystem certain users of certain companies are not allowed to see certain entries not beloning to their companies. I'll give it a try using a custom field type. Thanks for the extensive answer.  
> **username_1**: When you say that you don't want the entry being populated are you saying that you still want the entry to be saved but remove data from some fields before saving?  
> **username_0**: Luke, no I do not want the entry saved. I just want the out of the box entrylist overview (the menu item "Enrties" not to show certain rows based on x  
> **username_1**: Oh, there is no way of doing that with events or hooks as far as I know.  
> **username_1**: Populating does not mean listing though. So I think the your using the word populating incorrectly in this instance. The craft onelementpopulation refers to when an element is instantiating with all it's data as an object.  

---

