Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edwardchan/9016938e587534528870d9459599b9bb to your computer and use it in GitHub Desktop.
Save edwardchan/9016938e587534528870d9459599b9bb to your computer and use it in GitHub Desktop.
AdClickCommand module
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library name="PHP">
<CLASSES>
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/core/includes" />
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/core/lib" />
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/core/modules" />
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/modules" />
</CLASSES>
<SOURCES>
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/core/includes" />
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/core/lib" />
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/core/modules" />
<root url="file://$USER_HOME$/Sites/thr_thrillist/web/modules" />
</SOURCES>
</library>
</orderEntry>
</component>
</module>
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="Project Default" />
<option name="USE_PROJECT_PROFILE" value="true" />
<version value="1.0" />
</settings>
</component>
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="BladeClosingSection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="BladeControlDirectives" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptArgumentsOutsideFunction" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptFunctionSignatures" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptInfiniteLoop" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptLiteralNotFunction" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptSillyAssignment" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptSwitchStatementWithNoDefaultBranch" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CoffeeScriptUnusedLocalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CucumberExamplesColon" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="CucumberMissedExamples" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="CucumberTableInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CucumberUndefinedStep" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="EmptyEventHandler" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="FileHeaderInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="GherkinBrokenTableInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="GherkinMisplacedBackground" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="HamlNestedTagContent" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="LessResolvedByNameOnly" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="LessUnresolvedMixin" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="LessUnresolvedVariable" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="MissingSinceTagDocInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="PhingDomInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false" />
</profile>
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/adclickcommand.iml" filepath="$PROJECT_DIR$/.idea/adclickcommand.iml" />
</modules>
</component>
</project>
name: AdClickCommand
type: module
description: 'Urls For Sales Team.'
package: Group Nine
version: '8.x-1.0'
core: '8.x'
<?php
/**
* @file
* Install, update and uninstall functions for the adclickcommand module.
*/
/**
* Implements hook_install().
*
* Creates some default entries on this module custom table.
*
* @see hook_install()
*
* @ingroup adclickcommand
*/
function adclickcommand_install() {
drupal_install_schema('adclickcommand');
}
/**
* Implements hook_schema().
*
* Defines the database tables used by this module.
*
* @see hook_schema()
*
* @ingroup adclickcommand
*/
function adclickcommand_schema() {
if (db_table_exists('click_command_clicks')) {
return;
}
$schema['click_command_clicks'] = array(
'fields' => array(
'ad' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'ccid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => FALSE,
),
'unique_clicks' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => FALSE,
),
),
'primary key' => array('ad','ccid'),
'indexes' => array(
'click_command_clicks_ad_idx' => array('ad'),
'click_command_clicks_ccid_idx' => array('ccid')
)
);
return $schema;
}
<?php
/**
* @file
* Contains Drupal\adclickcommand\adclickcommand.module.
*/
/**
* @defgroup adclickcommand
* @ingroup examples
* @{
* Module file for the adclickcommand module.
*
* Should handle all the functionality for click commands.
*
* }
*/
'delete adclickcommand':
title: Delete click command.
'add adclickcommand':
title: Add click command
'view adclickcommand':
title: View click command
'edit adclickcommand':
title: Edit click command
'administer adclickcommand':
title: Administer settings
# Route name can be used in several places; e.g. links, redirects, and local
# actions.
entity.adclickcommand.canonical:
path: '/adclickcommand/{adclickcommand}'
defaults:
# Calls the view controller, defined in the annotation of the contact entity
_entity_view: 'adclickcommand'
_title: 'Click Command Content'
requirements:
# Calls the access controller of the entity, $operation 'view'
_entity_access: 'adclickcommand.view'
entity.adclickcommand.collection:
path: '/adclickcommand/list'
defaults:
# Calls the list controller, defined in the annotation of the entity.
_entity_list: 'adclickcommand'
_title: 'Click Command List'
_controller: '\Drupal\adclickcommand\Entity\Controller\AdClickCommandController::list'
requirements:
# Checks for permission directly.
_permission: 'view click command'
adclickcommand.add:
path: '/adclickcommand/add'
defaults:
# Calls the form.add controller, defined in the contact entity.
_entity_form: adclickcommand.add
_title: 'Add click command'
requirements:
_entity_create_access: 'adclickcommand'
entity.adclickcommand.edit_form:
path: '/adclickcommand/{adclickcommand}/edit'
defaults:
# Calls the form.edit controller, defined in the contact entity.
_entity_form: adclickcommand.edit
_title: 'Edit click command'
requirements:
_entity_access: 'adclickcommand.edit'
entity.adclickcommand.delete_form:
path: '/adclickcommand/{adclickcommand}/delete'
defaults:
# Calls the form.delete controller, defined in the contact entity.
_entity_form: adclickcommand.delete
_title: 'Delete click command'
requirements:
_entity_access: 'adclickcommand.delete'
adclickcommand.settings:
path: 'admin/structure/adclickcommand_settings'
defaults:
_form: '\Drupal\adclickcommand\Form\AdClickCommandSettingsForm'
_title: 'Click Command Settings'
requirements:
_permission: 'administer click command'
<?php
namespace Drupal\adclickcommand;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Access controller for the comment entity.
*
* @see \Drupal\comment\Entity\Comment.
*/
class AdClickCommandAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*
* Link the activities to the permissions. checkAccess is called with the
* $operation as defined in the routing.yml file.
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
switch ($operation) {
case 'view':
return AccessResult::allowedIfHasPermission($account, 'view click command');
case 'edit':
return AccessResult::allowedIfHasPermission($account, 'edit click command');
case 'delete':
return AccessResult::allowedIfHasPermission($account, 'delete click command');
}
return AccessResult::allowed();
}
/**
* {@inheritdoc}
*
* Separate from the checkAccess because the entity does not yet exist, it
* will be created during the 'add' process.
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessResult::allowedIfHasPermission($account, 'add adclickcommand');
}
}
<?php
namespace Drupal\adclickcommand;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\user\EntityOwnerInterface;
use Drupal\Core\Entity\EntityChangedInterface;
/**
* Provides an interface defining an entity.
*
* We have this interface so we can join the other interfaces it extends.
*
* @ingroup adclickcommand
*/
interface AdClickCommandInterface extends ContentEntityInterface, EntityOwnerInterface, EntityChangedInterface {
}
<?php
namespace Drupal\adclickcommand\Entity;
use Drupal\adclickcommand\AdClickCommandInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\UserInterface;
/**
* Defines the AdClickCommand entity.
*
* @ingroup adclickcommand
*
* .... @TODO
*
* id: The unique identifier of this entityType. It follows the pattern
* 'moduleName_xyz' to avoid naming conflicts.
*
* label: Human readable name of the entity type.
*
* handlers: Handler classes are used for different tasks. You can use
* standard handlers provided by D8 or build your own, most probably derived
* from the standard class. In detail:
*
* - view_builder: we use the standard controller to view an instance. It is
* called when a route lists an '_entity_view' default for the entityType
* (see routing.yml for details. The view can be manipulated by using the
* standard drupal tools in the settings.
*
* - list_builder: We derive our own list builder class from the
* entityListBuilder to control the presentation.
* If there is a view available for this entity from the views module, it
* overrides the list builder. @todo: any view? naming convention?
*
* - form: We derive our own forms to add functionality like additional fields,
* redirects etc. These forms are called when the routing list an
* '_entity_form' default for the entityType. Depending on the suffix
* (.add/.edit/.delete) in the route, the correct form is called.
*
* - access: Our own accessController where we determine access rights based on
* permissions.
*
* More properties:
*
* - base_table: Define the name of the table used to store the data. Make sure
* it is unique. The schema is automatically determined from the
* BaseFieldDefinitions below. The table is automatically created during
* installation.
*
* - fieldable: Can additional fields be added to the entity via the GUI?
* Analog to content types.
*
* - entity_keys: How to access the fields. Analog to 'nid' or 'uid'.
*
* - links: Provide links to do standard tasks. The 'edit-form' and
* 'delete-form' links are added to the list built by the
* entityListController. They will show up as action buttons in an additional
* column.
*
* There are many more properties to be used in an entity type definition. For
* a complete overview, please refer to the '\Drupal\Core\Entity\EntityType'
* class definition.
*
* The following construct is the actual definition of the entity type which
* is read and cached. Don't forget to clear cache after changes.
*
* @ContentEntityType(
* id = "adclickcommand",
* label = @Translation("Ad Click Command"),
* handlers = {
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "list_builder" = "Drupal\adclickcommand\Entity\Controller\AdClickCommandListBuilder",
* "form" = {
* "add" = "Drupal\adclickcommand\Form\AdClickCommandForm",
* "edit" = "Drupal\adclickcommand\Form\AdClickCommandForm",
* "delete" = "Drupal\adclickcommand\Form\AdClickCommandDeleteForm",
* },
* "access" = "Drupal\adclickcommand\AdClickCommandAccessControlHandler",
* },
* list_cache_contexts = { "user" },
* base_table = "click_command",
* admin_permission = "administer click command",
* entity_keys = {
* "id" = "id",
* "name" = "name",
* "url" = "url",
* "uuid" = "uuid"
* },
* links = {
* "canonical" = "/adclickcommand/{adclickcommand}",
* "edit-form" = "/adclickcommand/{adclickcommand}/edit",
* "delete-form" = "/adclickcommand/{adclickcommand}/delete",
* "collection" = "/adclickcommand/list"
* },
* field_ui_base_route = "adclickcommand.settings",
* )
*
* The 'links' above are defined by their path. For core to find the
* corresponding route, the route name must follow the correct pattern:
*
* entity.<entity-name>.<link-name> (replace dashes with underscores)
* Example: 'entity.adclickcommand.canonical'
*
* See routing file above for the corresponding implementation
*
* The Contact class defines methods and fields for the contact entity.
*
* Being derived from the ContentEntityBase class, we can override the methods
* we want. In our case we want to provide access to the standard fields about
* creation and changed time stamps.
*
* Our interface (see AdClickCommandInterface) also exposes the EntityOwnerInterface.
* This allows us to provide methods for setting and providing ownership
* information.
*
* The most important part is the definitions of the field properties for this
* entity type. These are of the same type as fields added through the GUI, but
* they can by changed in code. In the definition we can define if the user with
* the rights privileges can influence the presentation (view, edit) of each
* field.
*
* The class also uses the EntityChangedTrait trait which allows it to record
* timestamps of save operations.
*/
class AdClickCommand extends ContentEntityBase implements AdClickCommandInterface {
use EntityChangedTrait;
/**
* {@inheritdoc}
*
* When a new entity instance is added, set the user_id entity reference to
* the current user as the creator of the instance.
*/
public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
parent::preCreate($storage_controller, $values);
$values += array(
'user_id' => \Drupal::currentUser()->id(),
);
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function getChangedTime() {
return $this->get('changed')->value;
}
/**
* {@inheritdoc}
*/
public function getOwner() {
return $this->get('user_id')->entity;
}
/**
* {@inheritdoc}
*/
public function getOwnerId() {
return $this->get('user_id')->target_id;
}
/**
* {@inheritdoc}
*/
public function generateURL($id) {
return 'http://ad.thrillist.com/ad/0/click/' . $id;
}
/**
* Get command clicks.
*
* @param int $ccid
* An id of a click command.
*
* @return int
* An int.
*/
public function getClicks($id) {
return $this->entityQuery('click_command_clicks')->condition('ccid', $id)->execute()->fetchAll();
}
/**
* {@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}
*
* Define the field properties here.
*
* Field name, type and size determine the table structure.
*
* In addition, we can define how the field and its content can be manipulated
* in the GUI. The behaviour of the widgets used can be determined here.
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
// Standard field, used as unique if primary index.
$fields['id'] = BaseFieldDefinition::create('integer')
->setLabel(t('CCID'))
->setDescription(t('The CCID of the AdClickCommand.'))
->setReadOnly(TRUE);
// Name field for the contact.
// We set display options for the view as well as the form.
// Users with correct privileges can change the view and edit configuration.
$fields['name'] = BaseFieldDefinition::create('string')
->setLabel(t('Name'))
->setDescription(t('The name of the AdClickCommand.'))
->setSettings(array(
'default_value' => '',
'max_length' => 255,
'text_processing' => 0,
))
->setDisplayOptions('view', array(
'label' => 'above',
'type' => 'string',
'weight' => -6,
))
->setDisplayOptions('form', array(
'type' => 'string_textfield',
'weight' => -6,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['url'] = BaseFieldDefinition::create('string')
->setLabel(t('URL'))
->setDescription(t('The URL of the AdClickCommand.'))
->setSettings(array(
'default_value' => '',
'max_length' => 255,
'text_processing' => 0,
))
->setDisplayOptions('view', array(
'label' => 'above',
'type' => 'string',
'weight' => -5,
))
->setDisplayOptions('form', array(
'type' => 'string_textfield',
'weight' => -5,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['uuid'] = BaseFieldDefinition::create('uuid')
->setLabel(t('UUID'))
->setDescription(t('Universally Unique ID'))
->setReadOnly(TRUE);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Created'))
->setDescription(t('The time that the user was created.'));
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time that the user was last edited.'))
->setTranslatable(TRUE);
return $fields;
}
}
<?php
namespace Drupal\adclickcommand\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for PuSH module routes.
*/
class AdClickCommandController extends ControllerBase implements ContainerInjectionInterface {
/**
* The key value expirable factory.
*
* @var \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface
*/
protected $keyValueExpireFactory;
/**
* Constructs a AdClickCommandController object.
*
* @param \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface $key_value_expire_factory
* The key value expirable factory.
*/
public function __construct(KeyValueExpirableFactoryInterface $key_value_expire_factory, EntityTypeManagerInterface $entity_type_manager) {
$this->keyValueExpireFactory = $key_value_expire_factory;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('keyvalue.expirable'),
$container->get('entity_type.manager')
);
}
public static function commandList() {
return self::entityQuery('click_command_clicks')->condition('ccid', $id)->execute()->fetchAll();
}
}
<?php
namespace Drupal\adclickcommand\Entity\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a list controller for adclickcommand entity.
*
* @ingroup adclickcommand
*/
class AdClickCommandListBuilder extends EntityListBuilder {
/**
* The url generator.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
//die("entity_type $entity_type");
return new static(
$entity_type,
$container->get('entity.manager')->getStorage($entity_type->id()),
$container->get('url_generator')
);
}
/**
* Constructs a new AdClickCommandListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
* The url generator.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, UrlGeneratorInterface $url_generator) {
parent::__construct($entity_type, $storage);
$this->urlGenerator = $url_generator;
}
/**
* {@inheritdoc}
*
* We override ::render() so that we can add our own content above the table.
* parent::render() is where EntityListBuilder creates the table using our
* buildHeader() and buildRow() implementations.
*/
public function render() {
$build['description'] = array(
// '#markup' => $this->t('AdClickCommand implements a .... These contacts are fieldable entities. You can manage the fields on the <a href="@adminlink">AdClickCommand admin page</a>.', array(
'#markup' => $this->t('AdClickCommand implements a .... .', array(
'@adminlink' => $this->urlGenerator->generateFromRoute('adclickcommand.settings'),
)),
);
$build['table'] = parent::render();
return $build;
}
/**
* Render a filtered list of entries in the database.
*/
public function entryAdvancedList() {
$content = array();
$content['message'] = array(
'#markup' => $this->t('A more complex list of entries in the database.') . ' ' .
$this->t('Only the entries with name = "John" and age older than 18 years are shown, the username of the person who created the entry is also shown.'),
);
$headers = array(
t('Id'),
t('Created by'),
t('Name'),
t('Surname'),
t('Age'),
);
$rows = array();
foreach ($entries = DbtngExampleStorage::advancedLoad() as $entry) {
// Sanitize each entry.
$rows[] = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $entry);
}
$content['table'] = array(
'#type' => 'table',
'#header' => $headers,
'#rows' => $rows,
'#attributes' => array('id' => 'dbtng-example-advanced-list'),
'#empty' => t('No entries available.'),
);
// Don't cache this page.
$content['#cache']['max-age'] = 0;
return $content;
}
/**
* {@inheritdoc}
*
* Building the header and content lines for the contact list.
*
* Calling the parent::buildHeader() adds a column for the possible actions
* and inserts the 'edit' and 'delete' links as defined for the entity type.
*/
public function buildHeader() {
$header['id'] = $this->t('CCID');
$header['name'] = $this->t('Name');
$header['url'] = $this->t('URL');
$header['clicks'] = $this->t('Total Clicks');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/* @var $entity \Drupal\adclickcommand\Entity\AdClickCommand */
$row['id'] = $entity->id();
$row['name'] = $entity->name->value;
$row['url'] = $entity->url->value;
$row['clicks'] = $entity->getClicks($row['id']);
return $row + parent::buildRow($entity);
}
}
<?php
namespace Drupal\adclickcommand\Form;
use Drupal\Core\Entity\AdClickCommandConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Provides a form for deleting a adclickcommand entity.
*
* @ingroup adclickcommand
*/
class AdClickCommandDeleteForm extends ContentEntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete entity %name?', array('%name' => $this->entity->label()));
}
/**
* {@inheritdoc}
*
* If the delete command is canceled, return to the contact list.
*/
public function getCancelUrl() {
return new Url('entity.adclickcommand.collection');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*
* Delete the entity and log the event. logger() replaces the watchdog.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$entity = $this->getEntity();
$entity->delete();
$this->logger('adclickcommand')->notice('@type: deleted %title.',
array(
'@type' => $this->entity->bundle(),
'%title' => $this->entity->label(),
));
$form_state->setRedirect('entity.adclickcommand.collection');
}
}
<?php
namespace Drupal\adclickcommand\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Language\Language;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for the adclickcommand entity edit forms.
*
* @ingroup adclickcommand
*/
class AdClickCommandForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
/* @var $entity \Drupal\adclickcommand\Entity\AdClickCommand */
$form = parent::buildForm($form, $form_state);
$entity = $this->entity;
$form['langcode'] = array(
'#title' => $this->t('Language'),
'#type' => 'language_select',
'#default_value' => $entity->getUntranslated()->language()->getId(),
'#languages' => Language::STATE_ALL,
);
if ($entity->id()) {
$form['generated'] = array(
'#markup' => 'Generated URL ' . $entity->generateURL($entity->id()),
'#weight' => 10,
);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$form_state->setRedirect('entity.adclickcommand.collection');
$entity = $this->getEntity();
$entity->save();
}
}
<?php
namespace Drupal\adclickcommand\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class AdClickCommandSettingsForm.
*
* @package Drupal\adclickcommand\Form
*
* @ingroup adclickcommand
*/
class AdClickCommandSettingsForm extends FormBase {
/**
* Returns a unique string identifying the form.
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'adclickcommand_settings';
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Empty implementation of the abstract submit class.
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['contact_settings']['#markup'] = 'Settings form for adclickcommand. Manage field settings here.';
return $form;
}
}
<?php
namespace Drupal\adclickcommand\Tests;
use Drupal\adclickcommand\Entity\Contact;
use Drupal\Tests\examples\Functional\ExamplesBrowserTestBase;
/**
* Tests the basic functions of the AdClickCommand module.
*
* @package Drupal\adclickcommand\Tests
*
* @ingroup adclickcommand
*
* @group adclickcommand
* @group examples
*/
class AdClickCommandTest extends ExamplesBrowserTestBase {
public static $modules = array('adclickcommand', 'block', 'field_ui');
/**
* Basic tests for AdClickCommand.
*/
public function testAdClickCommand() {
$assert = $this->assertSession();
$web_user = $this->drupalCreateUser(array(
'add click command',
'edit click command',
'view click command',
'delete click command',
'administer click command',
'administer click command display',
'administer click command fields',
'administer click command form display',
));
// Anonymous User should not see the link to the listing.
$assert->pageTextNotContains('Click Command: Listing');
$this->drupalLogin($web_user);
// Web_user user has the right to view listing.
$assert->linkExists('Click Command: Listing');
$this->clickLink('Click Command: Listing');
// WebUser can add entity content.
$assert->linkExists('Add click command');
$this->clickLink(t('Add click command'));
$assert->fieldValueEquals('name[0][value]', '');
$assert->fieldValueEquals('name[0][value]', '');
$assert->fieldValueEquals('name[0][value]', '');
$user_ref = $web_user->name->value . ' (' . $web_user->id() . ')';
$assert->fieldValueEquals('user_id[0][target_id]', $user_ref);
// Post content, save an instance. Go back to list after saving.
$edit = array(
'name[0][value]' => 'test name',
'url[0][value]' => 'http://test.url',
);
$this->drupalPostForm(NULL, $edit, t('Save'));
// Entity listed.
$assert->linkExists('Edit');
$assert->linkExists('Delete');
$this->clickLink('test name');
// Entity shown.
$assert->pageTextContains('test name');
$assert->pageTextContains('http://test.url');
$assert->linkExists('Add click command');
$assert->linkExists('Edit');
$assert->linkExists('Delete');
// Delete the entity.
$this->clickLink('Delete');
// Confirm deletion.
$assert->linkExists('Cancel');
$this->drupalPostForm(NULL, array(), 'Delete');
// Back to list, must be empty.
$assert->pageTextNotContains('test name');
// Settings page.
$this->drupalGet('admin/structure/adclickcommand_settings');
$assert->pageTextContains('Contact Settings');
// Make sure the field manipulation links are available.
$assert->linkExists('Settings');
$assert->linkExists('Manage fields');
$assert->linkExists('Manage form display');
$assert->linkExists('Manage display');
}
/**
* Test all paths exposed by the module, by permission.
*/
public function testPaths() {
$assert = $this->assertSession();
// Generate a contact so that we can test the paths against it.
$contact = AdClickCommand::create(
array(
'name' => 'somename',
'url' => 'http://www.testurl.org',
)
);
$contact->save();
// Gather the test data.
$data = $this->providerTestPaths($contact->id());
// Run the tests.
foreach ($data as $datum) {
// drupalCreateUser() doesn't know what to do with an empty permission
// array, so we help it out.
if ($datum[2]) {
$user = $this->drupalCreateUser(array($datum[2]));
$this->drupalLogin($user);
}
else {
$user = $this->drupalCreateUser();
$this->drupalLogin($user);
}
$this->drupalGet($datum[1]);
$assert->statusCodeEquals($datum[0]);
}
}
/**
* Data provider for testPaths.
*
* @param int $contact_id
* The id of an existing adclickcommand.
*
* @return array
* Nested array of testing data. Arranged like this:
* - Expected response code.
* - Path to request.
* - Permission for the user.
*/
protected function providerTestPaths($_id) {
return array(
array(
200,
'/adclickcommand/' . $_id,
'view adclickcommand',
),
array(
403,
'/adclickcommand/' . $_id,
'',
),
array(
200,
'/adclickcommand/list',
'view adclickcommand',
),
array(
403,
'/adclickcommand/list',
'',
),
array(
200,
'/adclickcommand/add',
'add adclickcommand',
),
array(
403,
'/adclickcommand/add',
'',
),
array(
200,
'/adclickcommand/' . $_id . '/edit',
'edit adclickcommand',
),
array(
403,
'/adclickcommand/' . $_id . '/edit',
'',
),
array(
200,
'/adclickcommand/' . $_id . '/delete',
'delete adclickcommand',
),
array(
403,
'/adclickcommand/' . $_id . '/delete',
'',
),
array(
200,
'admin/structure/adclickcommand_settings',
'administer adclickcommand',
),
array(
403,
'admin/structure/adclickcommand_settings',
'',
),
);
}
/**
* Test add new fields to the adclickcommand.
*/
public function testAddFields() {
$web_user = $this->drupalCreateUser(array(
'administer adclickcommand',
'administer adclickcommand display',
'administer adclickcommand fields',
'administer adclickcommand form display',
));
$this->drupalLogin($web_user);
$entity_name = 'adclickcommand';
$add_field_url = 'admin/structure/' . $entity_name . '_settings/fields/add-field';
$this->drupalGet($add_field_url);
$field_name = 'test_name';
$edit = array(
'new_storage_type' => 'list_string',
'label' => 'test name',
'field_name' => $field_name,
);
$this->drupalPostForm(NULL, $edit, t('Save and continue'));
$expected_path = $this->buildUrl('admin/structure/' . $entity_name . '_settings/fields/' . $entity_name . '.' . $entity_name . '.field_' . $field_name . '/storage');
// Fetch url without query parameters.
$current_path = strtok($this->getUrl(), '?');
$this->assertEquals($expected_path, $current_path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment