#StackBounty: #8 #drupal-commerce How to display the "Add To Cart" button on a entity implementing the PurchasableEntityInter…

Bounty: 100

The product entity than come with Drupal Commerce 2.0 don’t feet my needs. Following the documentation, I made a custom entity that implement the PurchasableEntityInterface (Work in progress).

But how I’m suppose to create the “Add to Cart” button?

This is my entity code that represent a copy of a book:

<?php

namespace Drupalbook_marketEntity;

use DrupalCoreEntityEntityStorageInterface;
use DrupalCoreFieldBaseFieldDefinition;
use DrupalCoreEntityContentEntityBase;
use DrupalCoreEntityEntityChangedTrait;
use DrupalCoreEntityEntityTypeInterface;
use DrupaluserUserInterface;
use DrupalcommercePurchasableEntityInterface;
use Drupalcommerce_pricePrice;


/**
 * Defines the Copy entity entity.
 *
 * @ingroup book_market
 *
 * @ContentEntityType(
 *   id = "copy_entity",
 *   label = @Translation("Copy entity"),
 *   handlers = {
 *     "view_builder" = "DrupalCoreEntityEntityViewBuilder",
 *     "list_builder" = "Drupalbook_marketCopyEntityListBuilder",
 *     "views_data" = "Drupalbook_marketEntityCopyEntityViewsData",
 *
 *     "form" = {
 *       "default" = "Drupalbook_marketFormCopyEntityForm",
 *       "add" = "Drupalbook_marketFormCopyEntityForm",
 *       "edit" = "Drupalbook_marketFormCopyEntityForm",
 *       "delete" = "Drupalbook_marketFormCopyEntityDeleteForm",
 *     },
 *     "access" = "Drupalbook_marketCopyEntityAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupalbook_marketCopyEntityHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "copy_entity",
 *   admin_permission = "administer copy entity entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/copy_entity/{copy_entity}",
 *     "add-form" = "/admin/structure/copy_entity/add",
 *     "edit-form" = "/admin/structure/copy_entity/{copy_entity}/edit",
 *     "delete-form" = "/admin/structure/copy_entity/{copy_entity}/delete",
 *     "collection" = "/admin/structure/copy_entity",
 *   },
 *   field_ui_base_route = "copy_entity.settings"
 * )
 */
class CopyEntity extends ContentEntityBase implements CopyEntityInterface, PurchasableEntityInterface {

  use EntityChangedTrait;


  /**
   * {@inheritdoc}
   */
  public function getStores() {
    $stores = $this->get('stores')->referencedEntities();
    return $this->ensureTranslations($stores);
  }

  /**
   * {@inheritdoc}
   */
  public function setStores(array $stores) {
    $this->set('stores', $stores);
    return $this;
  }

  /**
   * Gets the purchasable entity's order item type ID.
   *
   * Used for finding/creating the appropriate order item when purchasing a
   * product (adding it to an order).
   *
   * @return string
   *   The order item type ID.
   */
  public function getOrderItemTypeId(){

  }

  /**
   * Gets the purchasable entity's order item title.
   *
   * Saved in the $order_item->title field to protect the order items of
   * completed orders against changes in the referenced purchased entity.
   *
   * @return string
   *   The order item title.
   */
  public function getOrderItemTitle(){

  }

  /**
   * {@inheritdoc}
   */
  public function getPrice() {
    if (!$this->get('price')->isEmpty()) {
      return $this->get('price')->first()->toPrice();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setPrice(Price $price) {
    $this->set('price', $price);
    return $this;
  }

  /**
   * {@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 postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    // @todo get the correct book id from ISBN, get the old code.
    $this->set('book_id', 1);
  }

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

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    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 ? TRUE : FALSE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Copy entity entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->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['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the Copy 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);

    // The price is not required because it's not guaranteed to be used
    // for storage (there might be a price per currency, role, country, etc).
    $fields['price'] = BaseFieldDefinition::create('commerce_price')
      ->setLabel(t('Price'))
      ->setDescription(t('The copy price'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'commerce_price_default',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'commerce_price_default',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    // The copy backreference, populated by ::postSave().
    $fields['book_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Book'))
      ->setDescription(t('The parent book.'))
      ->setSetting('target_type', 'node')
      ->setSetting('handler_settings', ['target_bundles' => ['book' => 'book']])
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('view', TRUE);


    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('A boolean indicating whether the Copy entity is published.'))
      ->setDefaultValue(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;
  }

}


Get this bounty!!!

Leave a Reply