You are here

class Tag in Doubleclick for Publishers (DFP) 8

Same name in this branch
  1. 8 src/Form/Tag.php \Drupal\dfp\Form\Tag
  2. 8 src/Entity/Tag.php \Drupal\dfp\Entity\Tag

Form to edit and add DFP tags.

Hierarchy

Expanded class hierarchy of Tag

File

src/Form/Tag.php, line 18
Contains \Drupal\dfp\Form\Tag.

Namespace

Drupal\dfp\Form
View source
class Tag extends EntityForm {
  use BreakpointFormTrait;
  use TargetingFormTrait;

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    // @todo Implement vertical tabs like D7 module.
    // @todo Implement out_of_page setting like D7 module.
    $form = parent::form($form, $form_state);

    /** @var \Drupal\dfp\Entity\TagInterface $tag */
    $tag = $this->entity;
    if ($this->operation == 'add') {
      $form['#title'] = $this
        ->t('Add DFP tag');
    }
    else {
      $form['#title'] = $this
        ->t('Edit %label DFP tag', [
        '%label' => $tag
          ->label(),
      ]);
    }

    // Tag settings.
    $form['tag_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Tag Settings'),
      '#open' => TRUE,
    ];
    $form['tag_settings']['slot'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Ad Slot Name'),
      '#required' => TRUE,
      '#maxlength' => 64,
      '#default_value' => $tag
        ->slot(),
      '#description' => $this
        ->t('Example: leaderboard or box1'),
    ];
    $form['tag_settings']['id'] = [
      '#type' => 'machine_name',
      '#maxlength' => 128,
      '#default_value' => $tag
        ->id(),
      '#description' => $this
        ->t('A unique machine-readable name for this DFP tag. Only use letters, numbers and underscores. Example: top_banner'),
      '#machine_name' => [
        'exists' => [
          'Drupal\\dfp\\Entity\\Tag',
          'load',
        ],
        'source' => [
          'tag_settings',
          'slot',
        ],
      ],
    ];
    $form['tag_settings']['size'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Size(s)'),
      '#description' => $this
        ->t('Example: 300x600,300x250. For Out Of Page slots, use 0x0'),
      '#required' => TRUE,
      '#maxlength' => 64,
      '#default_value' => $tag
        ->size(),
    ];
    $form['tag_settings']['adunit'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Ad Unit Pattern'),
      '#required' => FALSE,
      '#maxlength' => 255,
      '#default_value' => $tag
        ->adunit(),
      '#description' => $this
        ->t('Use the tokens below to define how the ad unit should display. The network id will be included automatically. Example: [dfp_tag:url_parts:4]/[dfp_tag:slot]. Leave this field empty to use the default ad unit adunit as defined in <a href=":url">Global DFP Settings</a>.', [
        ':url' => Url::fromRoute('dfp.admin_settings')
          ->toString(),
      ]),
    ];

    // @todo Add token browser.
    // Global Display settings.
    $form['tag_display_options'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Display Options'),
      '#open' => TRUE,
    ];
    $form['tag_display_options']['slug'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Slug'),
      '#description' => $this
        ->t('Override the default slug for this ad tag. Use @none for no slug. Leave this field empty to use the default slug. Example: Advertisement', [
        '@none' => '<none>',
      ]),
      '#required' => FALSE,
      '#maxlength' => 64,
      '#default_value' => $tag
        ->slug(),
    ];
    $form['tag_display_options']['block'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Create a block for this ad tag'),
      '#description' => $this
        ->t('Display this ad in a block configurable. <a href=":url">Place the block</a>.', [
        ':url' => Url::fromRoute('block.admin_display')
          ->toString(),
      ]),
      '#default_value' => $tag
        ->hasBlock(),
    ];
    $form['tag_display_options']['short_tag'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Render this tag without javascript'),
      '#description' => $this
        ->t('Use this option for ads included in emails.'),
      '#default_value' => $tag
        ->shortTag(),
    ];

    // Responsive settings.
    $form['breakpoint_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Responsive Settings'),
      '#open' => TRUE,
    ];
    $existing_breakpoints = $this
      ->getExistingBreakpoints($form_state, $tag
      ->breakpoints());
    $this
      ->addBreakpointsForm($form['breakpoint_settings'], $existing_breakpoints);

    // Targeting options.
    $form['targeting_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Targeting'),
      '#open' => TRUE,
    ];
    $existing_targeting = $this
      ->getExistingTargeting($form_state, $tag
      ->targeting());
    $this
      ->addTargetingForm($form['targeting_settings'], $existing_targeting);

    // Backfill ad settings options.
    $form['adsense_backfill'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Backfill Ad Settings'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];
    $form['adsense_backfill']['ad_types'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('AdSense Ad Type'),
      '#empty_option' => $this
        ->t('- None -'),
      '#empty_value' => '',
      '#default_value' => $tag
        ->adsenseAdTypes(),
      '#options' => [
        TagInterface::ADSENSE_TEXT_IMAGE => $this
          ->t('Both image and text ads'),
        TagInterface::ADSENSE_IMAGE => $this
          ->t('Only image ads'),
        TagInterface::ADSENSE_TEXT => $this
          ->t('Only text ads'),
      ],
      '#description' => $this
        ->t('Choose what type of ads this tag can display when AdSense ads are used for backfill.'),
    ];
    $form['adsense_backfill']['channel_ids'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('AdSense Channel ID(s)'),
      '#default_value' => $tag
        ->adsenseChannelIds(),
      '#required' => FALSE,
      '#description' => $this
        ->t('Example: 271828183+314159265'),
      '#states' => [
        '!visible' => [
          [
            ':input[name="adsense_backfill[ad_types]"]' => [
              'value' => '',
            ],
          ],
        ],
      ],
    ];
    $form['adsense_backfill']['color'] = [
      '#type' => 'fieldgroup',
      '#title' => $this
        ->t('Color Settings for Text Ads'),
      '#attributes' => [
        'class' => [
          'form-item',
        ],
      ],
      '#states' => [
        'visible' => [
          [
            ':input[name="adsense_backfill[ad_types]"]' => [
              'value' => TagInterface::ADSENSE_TEXT,
            ],
          ],
          [
            ':input[name="adsense_backfill[ad_types]"]' => [
              'value' => TagInterface::ADSENSE_TEXT_IMAGE,
            ],
          ],
        ],
      ],
    ];
    $adsense_color_settings = [
      'background' => $this
        ->t('Background color'),
      'border' => $this
        ->t('Border color'),
      'link' => $this
        ->t('Link color'),
      'text' => $this
        ->t('Text color'),
      'url' => $this
        ->t('URL color'),
    ];
    foreach ($adsense_color_settings as $setting => $title) {

      // @todo integrate color picker if color module enabled.
      $form['adsense_backfill']['color'][$setting] = [
        '#type' => 'textfield',
        '#title' => $title,
        '#attributes' => [
          'class' => [
            'color-setting',
          ],
        ],
        '#field_prefix' => '#',
        '#default_value' => $tag
          ->adsenseColor($setting),
        '#size' => 6,
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (preg_match(TagInterface::ADUNIT_PATTERN_VALIDATION_REGEX, $form_state
      ->getValue('adunit'))) {
      $form_state
        ->setErrorByName('adunit', $this
        ->t('Ad Unit Patterns can only include letters, numbers, hyphens, dashes, periods, slashes and tokens.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $tag = $this->entity;
    $status = $tag
      ->save();
    $t_args['%slot'] = $tag
      ->label();
    if ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addMessage(t('The DFP tag %slot has been updated.', $t_args));
    }
    elseif ($status == SAVED_NEW) {
      $this
        ->messenger()
        ->addMessage(t('The DFP tag %slot has been added.', $t_args));
      $context = array_merge($t_args, [
        'link' => $tag
          ->toLink($this
          ->t('Edit DFP tag'), 'edit-form')
          ->toString(),
      ]);
      $this
        ->logger('dfp')
        ->notice('Added DFP tag %slot.', $context);
    }
    $form_state
      ->setRedirectUrl($tag
      ->toUrl('collection'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BreakpointFormTrait::addBreakpointForm protected function Helper form builder for an individual breakpoint.
BreakpointFormTrait::addBreakpointsForm protected function Helper form builder for the breakpoints form.
BreakpointFormTrait::breakpointFormValidate public static function Validation function used by an individual breakpoint.
BreakpointFormTrait::breakpointsFormValidate public static function Validation function used by the breakpoints form.
BreakpointFormTrait::breakpointsTrim protected static function Helper function that removes empty breakpoints from form values.
BreakpointFormTrait::getExistingBreakpoints protected function Returns the current breakpoints.
BreakpointFormTrait::moreBreakpointsJs public function Ajax callback for adding breakpoints to the breakpoint form.
BreakpointFormTrait::moreBreakpointsSubmit public function Submit handler to add more breakpoints to an ad tag.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
Tag::form public function Gets the actual form array to be built. Overrides EntityForm::form
Tag::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
Tag::validateForm public function Form validation handler. Overrides FormBase::validateForm
TargetingFormTrait::addTargetForm protected function Helper form builder for an individual target.
TargetingFormTrait::addTargetingForm protected function Helper form builder for the targeting form.
TargetingFormTrait::getExistingTargeting protected function Returns the current targets.
TargetingFormTrait::moreTargetsJs public function Ajax callback for adding targets to the targeting form.
TargetingFormTrait::targetFormValidate public static function Validation function used by an individual target in the targeting form.
TargetingFormTrait::targetingFormMoreTargetsSubmit public function Submit handler to add more targets to an ad tag.
TargetingFormTrait::targetingFormValidate public static function Validation function used by the targeting form.
TargetingFormTrait::trimTargetingValues protected static function Helper function that removes empty targets form form values.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.