You are here

protected function CerFieldHandler::validate in Corresponding Entity References 7.3

Validates a potential reference. After doing a cardinality check, the reference is validated through the Field Attach API, allowing the module which owns the field to do its normal validation logic. If validation fails, the error(s) are logged.

Parameters

EntityDrupalWrapper $entity: The wrapped entity to validate.

Return value

boolean

1 call to CerFieldHandler::validate()
CerFieldHandler::add in includes/CerFieldHandler.inc
Adds a reference to $entity, validating it first.

File

includes/CerFieldHandler.inc, line 96
Contains CerFieldHandler.

Class

CerFieldHandler
@class Handles low-level operations for a single field on a single entity. Exposes methods to add, delete and check for references. This will also iterate over the references, returning each one as an EntityDrupalWrapper object.

Code

protected function validate(EntityDrupalWrapper $entity) {

  // Before we do anything else, check that the field has enough space to add the
  // reference. If there isn't, bail out so we don't blindly overwrite existing
  // field data.
  if ($this
    ->checkCardinality()) {

    // Keep the previous value so we can restore it if validation fails.
    $prev_value = $this->value
      ->value();
    if ($this->isMultiValue) {
      $value = $this->value
        ->value();
      $value[] = $entity
        ->value();
      $this->value
        ->set($value);
    }
    else {
      $this->value
        ->set($entity
        ->value());
    }

    // Leverage the Field Attach API to validate the reference. If errors occur,
    // field_attach_validate() throws FieldValidationException, containing an array
    // of every validation error.
    try {

      // Only validate this field.
      field_attach_validate($this->entity
        ->type(), $this->entity
        ->value(), array(
        'field_name' => $this->field->name,
      ));
      return TRUE;
    } catch (FieldValidationException $e) {
      foreach ($e->errors as $field) {
        foreach ($field as $language) {
          foreach ($language as $errors) {
            foreach ($errors as $error) {
              $this
                ->logError($error['message'], $entity);
            }
          }
        }
      }
      $this->value
        ->set($prev_value);
    }
  }
  else {
    $this
      ->logError('Cannot add reference to !that_link from !field_label on !this_link because there are no more slots available.', $entity);
  }
  return FALSE;
}