2

I have an Entity in Drupal 8 named visual_tracker_entity Here is my entity,

/**
 * @file
 * Contains \Drupal\visual_tracker\Entity\VisaulTrackerEntity.
 */

namespace Drupal\visual_tracker\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\visual_tracker\VisaulTrackerEntityInterface;
use Drupal\user\UserInterface;

/**
 * Defines the Visaul tracker entity entity.
 *
 * @ingroup visual_tracker
 *
 * @ContentEntityType(
 *   id = "visaul_tracker_entity",
 *   label = @Translation("Visaul tracker entity"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\visual_tracker\VisaulTrackerEntityListBuilder",
 *     "views_data" = "Drupal\visual_tracker\Entity\VisaulTrackerEntityViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\visual_tracker\Form\VisaulTrackerEntityForm",
 *       "add" = "Drupal\visual_tracker\Form\VisaulTrackerEntityForm",
 *       "edit" = "Drupal\visual_tracker\Form\VisaulTrackerEntityForm",
 *       "delete" = "Drupal\visual_tracker\Form\VisaulTrackerEntityDeleteForm",
 *     },
 *     "access" = "Drupal\visual_tracker\VisaulTrackerEntityAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\visual_tracker\VisaulTrackerEntityHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "visaul_tracker_entity",
 *   admin_permission = "administer visaul tracker entity entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "address" = "address",
 *     "lat"="lat",
 *     "lng" = "lng"
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/visaul_tracker_entity/{visaul_tracker_entity}",
 *     "add-form" = "/admin/structure/visaul_tracker_entity/add",
 *     "edit-form" = "/admin/structure/visaul_tracker_entity/{visaul_tracker_entity}/edit",
 *     "delete-form" = "/admin/structure/visaul_tracker_entity/{visaul_tracker_entity}/delete",
 *     "collection" = "/admin/structure/visaul_tracker_entity",
 *   },
 *   field_ui_base_route = "visaul_tracker_entity.settings"
 * )
 */
class VisaulTrackerEntity extends ContentEntityBase implements VisaulTrackerEntityInterface {
  use EntityChangedTrait;
  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += array(
      'user_id' => \Drupal::currentUser()->id(),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }
  /**
   * {@inheritdoc}
   */
  public function getAddress() {
    return $this->get('address')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setAddress($address) {
    $this->set('address', $address);
    return $this;
  }
  /**
   * {@inheritdoc}
   */
  public function getLatittude() {
    return $this->get('lat')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setLatitude($lat) {
    $this->set('lat', $lat);
    return $this;
  }
  /**
   * {@inheritdoc}
   */
  public function getLongitude() {
    return $this->get('lng')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setLongitude($lng) {
    $this->set('lng', $lng);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isPublished() {
    return (bool) $this->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Visaul tracker entity entity.'))
      ->setReadOnly(TRUE);
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Visaul tracker entity entity.'))
      ->setReadOnly(TRUE);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Visaul tracker entity entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ),
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['my_new_file'] = BaseFieldDefinition::create('file')
      ->setLabel(t('My New File'))
      ->setDescription(t('The name of the Visaul tracker entity entity.'))
      ->setDefaultValue('')
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'file',
        'weight' => -4,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'file',
        'weight' => -4,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
    $fields['address'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Address'))
      ->setDescription(t('The addres of the Visaul tracker entity entity.'))
      ->setSettings(array(
        'max_length' => 250,
        'text_processing' => 0,
      ))
      ->setDefaultValue('')
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => -4,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
    $fields['lat'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Latitiude'))
      ->setDescription(t('The latiitude of the Visaul tracker entity entity.'))
      ->setSettings(array(
        'max_length' => 50,
        'text_processing' => 0,
      ))
      ->setDefaultValue('')
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => -4,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
    $fields['lng'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Longitude'))
      ->setDescription(t('The name of the Visaul tracker entity entity.'))
      ->setSettings(array(
        'max_length' => 50,
        'text_processing' => 0,
      ))
      ->setDefaultValue('')
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => -4,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('A boolean indicating whether the Visaul tracker entity is published.'))
      ->setDefaultValue(TRUE);

    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
      ->setDescription(t('The language code for the Visaul tracker entity entity.'))
      ->setDisplayOptions('form', array(
        'type' => 'language_select',
        'weight' => 10,
      ))
      ->setDisplayConfigurable('form', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    return $fields;
  }

}

I need add validation rule for file type field. The default file type is come with .txt extension. I want to only allow .xls and .xlsx . This is the file filed,

  $fields['my_new_file'] = BaseFieldDefinition::create('file')
          ->setLabel(t('My New File'))
          ->setDescription(t('The name of the Visaul tracker entity entity.'))
          ->setDefaultValue('')
          ->setDisplayOptions('view', array(
            'label' => 'above',
            'type' => 'file',
            'weight' => -4,
          ))
          ->setDisplayOptions('form', array(
            'type' => 'file',
            'weight' => -4,
          ))
          ->setDisplayConfigurable('form', TRUE)
          ->setDisplayConfigurable('view', TRUE);

Please help me.

2 Answers 2

4

If you're using a file field, then you can set the "file_extensions" setting. You can find out more information about a "file" type by going to the FileItem API page (or look it up in your IDE). The class annotation is helpful to learn about things such as the Constraint system if you need to add any additional constraints.

 $fields['my_new_file'] = BaseFieldDefinition::create('file')
   ->setSetting('file_extensions', 'xls xlsx');
2
  • 1
    For figuring out the documentation, I usually recommend to just configure it in the UI like you want and then look at the generated config entity/file and copy those settings into your base field definitions.
    – Berdir
    Commented Mar 3, 2016 at 19:51
  • 1
    @mradcliffe Thanks for your great help, BTW I'm new in drupal
    – Nisam
    Commented Mar 4, 2016 at 4:23
6

Separately, if you are building a Drupal 8 form that has a file upload, you can pass upload validators in the following manner:

$validators = array(
  'file_validate_extensions' => array('csv'),
  'file_validate_size' => array(file_upload_max_size()),
);
$form['csv']['csv_file'] = array(
  '#type' => 'file',
  '#title' => $this->t('CSV File'),
  '#description' => array(
    '#theme' => 'file_upload_help',
    '#description' => $this->t('The CSV file must include columns in the following order:'),
    '#upload_validators' => $validators,
  ),
  '#upload_validators' => $validators,
);

... and then validate those extensions during validateForm:

public function validateForm(array &$form, FormStateInterface $form_state) {
  $this->file = file_save_upload('csv_file', $form['csv']['csv_file']['#upload_validators'], FALSE, 0);

  // Ensure we have the file uploaded.
  if (!$this->file) {
    $form_state->setErrorByName('csv_file', $this->t('File to import not found.'));
  }
}

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.