How to redirect search result page in drupal Here, I am working in drupal Commons plugin. I already customized search form in that drupal header.Here i include modify search form in custom theme:

function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['custom_search_types']['#attributes'] = array('style' => 'display:none'); // Set a default value for the textfield
    $form['search_block_form']['#attributes']['class'][] = 'form-control'; // Set a default value for the textfield
    $form['actions']['submit']['#value'] = 'OK!'; // Change the text on the submit button

    $form['actions']['submit'] = array('#type' => 'button','#value' => 'OK!');

    // Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
    // Prevent user from searching the default text
    $form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";
    $form['actions']['submit']['#attributes']['class'][] = 'input-group-addon';

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
  }
}

And i need to redirect search result page using that above search form.But I type content and hit enter it remain same page.How to redirect into search result page with custom form values.I just customized form submit in custom theme

function mytheme_search_box_form_submit($form, &$form_state) {
print_r($form);//No results
}

How to achieve it. kindly guide me..

You can use the redirect attribute in form_state as follows,

function mytheme_search_box_form_submit($form, &$form_state) {
   $form_state['#redirect'] = 'Your path to redirect';
}


Passing path arguments to a form builder I'm trying to understand how to port the following D7 code to Drupal 8.

function x_menu() {
    $menu['x/form/test/%/%'] = [
        'page callback' => 'drupal_get_form',
        'page arguments' => ['x_form_test', 3, 4],
        'type' => MENU_CALLBACK,
        'title' => 'Test Form',
    ];
    return $menu;
}

function x_form_test(&$form, $form_state, $arg1, $arg2) {
    return $form;
}

From what I can glean from the documentation of the Routing and Form API, the new way to connect a path to a form is to put this in x.routing.yml:

x.form_test:
    path: 'x/form/{arg1}/{arg2}',
    defaults:
        _form: '\Drupal\x\XFormTest'
        _title: 'Test Form'

and then create a form class XFormTest that ultimately descends from FormBase.

However, it's clearly impossible* to add extra arguments to an inherited function signature like public FormInterface::buildForm(array $form, FormStateInterface $form_state)

How can I read $arg1 and $arg2 in XFormTest::buildForm(), preferably while still pointing the route at the form rather than putting a Controller around it?

(Routing API: https://www.drupal.org/node/2092643)

*Update: Maybe it's not so much impossible as that I'm not doing it correctly.

My function declaration

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class XBBCodeHandlerForm extends FormBase {
  public function buildForm(array $form, FormStateInterface &$form_state, $format = XBBCODE_GLOBAL) {
  }
}

generates the following fatal error:

PHP Fatal error:  Declaration of Drupal\xbbcode\Form\XBBCodeHandlerForm::buildForm()
must be compatible with
Drupal\Core\Form\FormInterface::buildForm(array $form,
Drupal\Core\Form\FormStateInterface $form_state)
 in /home/arancaytar/software/web/drupal/modules/xbbcode/src/Form/XBBCodeHandlerForm.php
on line 161

Edit: I misunderstood the fatal error; it wasn't caused by the extra argument but by changing the value argument $form_state to a reference argument. PHP does allow adding optional arguments to overriding functions, apparently.

it's clearly impossible to add extra arguments to an inherited function signature

Not true - adding extra arguments to a function signature is one of the fundamental reasons that inheritance exists in OO.

You literally just need to add your arguments to the function signature to make this work:

public function buildForm(array $form, FormStateInterface $form_state, $arg1, $arg2) {
    // You have $arg1 and $arg2 available
}

You could do something more fancy and get typed data by using parameter upcasting, otherwise you'll get the args as strings.

Examples here.


Add parameter to the URL based on a field value Is it possible to append a campaign tracking code to the requested URL basing on a specific field value on the linked node? I'm trying to use a path_processor_outbound service, but it doesn't work quite as expected and it works rather randomly.

This is the code I am using.

function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {if(isset($options['entity']) && $options['entity'] instanceof \Drupal\node\NodeInterface ) {
      $node = $options['entity'];

      if($node->bundle() == 'article') {
        $channel = $node->get('field_channel')->getValue();
        $promotions = array(10);
        $channel_value = reset($channel);
        $channel_id = $channel_value['target_id'];

        if(in_array($channel_id, $promotions)) {
          $options['query']['foo'] = 'bar';
        }
      }
    }
    return $path;
  }

I have a feeling this is correct approach for links to nodes generated on site (teasers on front page), but it doesn't append parameters on page request.

I also considered adding parameters to the path alias, but that doesn't seem to be right and JavaScript code would be added too late.

Don't know if it fits for your use case, but I wanted all outgoing links from a specific node type to have the ID appended, e.g. on every product page all outgoing "Call to action" links should appent something like ?from_product_id=1234. My module name was 'wt_ctalinks`

wt_ctalinks.services.yml

services:
  cache_context.wt_ctalinks:
    class: Drupal\wt_ctalinks\CtaLinksCacheContext
    arguments: ['@request_stack']
    tags:
      - { name: cache.context }
  wt_ctalinks.ctalinks_pathmodifier_service:
    class: Drupal\wt_ctalinks\CtaLinksPathModifierService
    arguments: ['@request_stack']
    tags:
      - { name: path_processor_outbound, priority: 3000 }

src/CtaLinksCacheContext.php

<?php

namespace Drupal\wt_ctalinks;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;

class CtaLinksCacheContext implements CacheContextInterface {

  /**
   * @var Symfony\Component\HttpFoundation\RequestStack;
   */
  protected $requestStack;

  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
  * {@inheritdoc}
  */
  public static function getLabel() {
    drupal_set_message('Modify CTA links based on current node type');
  }

  /**
  * {@inheritdoc}
  */
  public function getContext() {
    $nid = 0;
    $request = $this->requestStack->getCurrentRequest();
    $node = $request->attributes->get('node');
    if (is_numeric($node)) {
      $node = Node::load($node);
    }
    if ($node instanceof NodeInterface && $node->bundle() === 'article') {
      $nid = $node->id();
    }
    return $nid;
  }

  /**
  * {@inheritdoc}
  */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

src/CtaLinksPathModifierService.php

<?php

namespace Drupal\wt_ctalinks;
use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\config_pages\Entity\ConfigPages;
use Drupal\node\Entity\Node;

/**
 * Class DefaultService.
 */
class CtaLinksPathModifierService implements OutboundPathProcessorInterface {

  /**
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  protected $bookingPath;
  protected $enquirePath;

  /**
   * Constructs a new DefaultService object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if (empty($request)) {
      $request = $this->requestStack->getCurrentRequest();
    }

    $node = $request->attributes->get('node');

    if (is_numeric($node)) {
      // missing upcasting in revision view, have to load manually there
      $node = Node::load($node);
    }

    if ($node instanceof NodeInterface && $node->getType() === 'article') {
      // your logic here
    }

    if ($bubbleable_metadata) {
      $bubbleable_metadata
        ->addCacheContexts([
          'wt_ctalinks',
        ]);
    }
    return $path;
  }
}


Cookie Compliance and Google Analytics I'm using Drupal 8.6.14 (going to upgrade soon) and I am trying to create a cookie consent page that actually works!

I've used many different modules like EU Cookie Compliance, GDPR Compliance and several others, but all of them fail to block Google Analytics cookies.

I even used a couple of patches on Google Analytics that I found in the community in order to support EU Cookie Compliance module, but all of them fail.

To be exact, EU Cookie Compliance seems to load the cookies as normal, then deleting them as the dialog of consent appears and then loading them all again once I pick any option.

All the other solutions seem not to work at all (I get the cookies any time the page loads). BTW, all the solutions I've found are for <8 versions.

Any idea how I can get this done? Am I missing something?

From the EU Cookie Compliance module's project page on drupal.org:

If you want to conditionally set cookies in your module, there is a
JavaScript function provided that returns TRUE if the user has given
their consent:
Drupal.eu_cookie_compliance.hasAgreed()
For example, if you want to disable Google Analytics, you could do the
following: http://drupal.org/node/1648286#comment-6145800
Another example of how it can be used with Google Analytics is
provided by dagomar in this comment.
Here is another example showing how to set cookies after user clicks
the accept button: http://drupal.org/node/1624876#comment-6111688

I've personally used this to prevent third-party code snippets from loading until after compliance is granted, by making a custom module and including the call to hasAgreed() in my module's JavaScript behaviors.
But as the first example above shows, a custom module is not necessary for Google Analytics in particular. You can simply add the following code to the Advanced Settings->Custom JS in Google Analytics:
if (!Drupal.eu_cookie_compliance.hasAgreed()){
window['ga-disable-UA-xxxx-1'] = true;
}

EDIT (2020-02-23):
It seems that you want to enforce extremely strict GDPR compliance, and prevent the cookies from being loaded at all unless consent has been granted.
You can do this with a custom module, leveraging the same hasAgreed() JavaScript behavior provided by the EU Cookie Compilance module.
First you need to remove the code snippet from your site completely and replace it with a placeholder.
If it's just one script in your HTML head, you might just edit html.html.twig.
If there are multiple scripts you need to prevent from running, it will be more work.
In my case, I replaced dozens of different third-party forms with an empty
 element:

My custom JavaScript behavior looks for all the DOM elements with that class:
document.getElementsByClassName('thirdPartyFormWrapper');

The 4-digit number in the div ID corresponds to the unique third-party form ID for each form.
If consent has not been granted (or if the EU Cookie Compliance module is not installed or enabled, and hasAgreed() is not available) then my custom module uses the 4-digit ID to look up substitute content (saying, e.g., "Please accept cookies to view the Yoyodyne, Inc. Gnomovision Mailing List Subscription Form," or whatever that particular form is.)
If consent has been granted, then my custom module uses the 4-digit ID to inject the JavaScript snippet for each of the third-party forms into the placeholder
.
Once the form snippet is injected, you can figure out how to handle the cookies. If consent is withheld, neither snippets nor cookies will load.
You can also use this technique to handle cookies for extremely strict GDPR compliance, following this pattern:
/**
 * Cookie handling for strict GDPR compliance
 */
  Drupal.behaviors.customCookieConsent = {
    attach: function (context, settings) {
      if (!Drupal.eu_cookie_compliance || !Drupal.eu_cookie_compliance.hasAgreed()) {
        // Bail out if cookie consent not given
        return;
      }
      // If cookie consent is given, set cookie (unless already set)
      if (!$.cookie('customConsentTime')){
        var consentTime = new Date();
        $.cookie('customConsentTime', consentTime.toISOString(), {expires: 3650});
      }
    },
  };

This approach is a bit more work, but it will prevent scripts and cookies from being loaded at all before consent is granted.
Finally, I should note that based on your comments here and on Drupal.org, I think you should do some research on "Drupal Behaviors" for your JavaScript. This will help you to avoid the "Uncaught ReferenceError: Drupal is not defined" message you have been seeing.


Drupal 7 IMCE image paths I develop sites on my server then move them when ready. I just started using IMCE and everything works well other than the image path. For instance:

The path shows /test/sites/default/files/images/test.png however I want /sites/default/files/images/test.png so when I move the site I don't have to redo all the images.

I set the rewrite in the .hataccess file and I set the base url in settings.php. Is there something else I need to set?

If you develop your site in a sub folder, rather than a subdomain, you are going to be in for a bad time. All of your image paths and links are going to be incorrect. You are better of moving to a subdomain instead. If its already too late then use the Pathologic module to clean them up.

  Pathologic is an input filter which can correct paths in links and
  images in your Drupal content in situations which would otherwise
  cause them to “break;” for example, if the URL of the site changes, or
  the content was moved to a different server. Pathologic can also solve
  the problem of missing images and broken links in your site’s RSS
  feeds.


How do I add a date format to custom block output I have two custom block output fields that are date

    function my_three_upcoming_events() {
  $output = '';
  $now_events = views_get_view_result('schedule_list2');
  $upcoming_events = views_get_view_result('clone_of_now');
  $max_events = 3;

  $all_events = array_merge($now_events, $upcoming_events);
/*   print_r ('
');
print_r ($all_events);
exit();
*/  for ($i=0,$z=$max_events;$i<$z;$i++) {

    $node = node_load($all_events[$i]->nid);
    $output .='
' . l($node->title,'/node/'.$node->nid) . '
';
    $output .='
' .($node->body[und][0][value]) . '
';
    $output .='
' .($node->field_venue[und][0][value]) . '
';
    $output .='
' .($node->field_session_start_date[und][0][value]) . '
';
    $output .='
' .($node->field_session_start_date[und][0][value2]) . '
';

  }

}

and they output like this

2014-04-18 15:15:00
2014-04-19 21:15:00

How can I change to one of the php date formats

Thanks for any help on this

You should use date_format (Drupal function).


"add content" suddenly not showing on navigation block anymore Good day,
I'm having a problem of a block not showing its content!
the block is stock and called navigation, which has "add content" in its links.

but just recently, it has not been working on other users except admin.
i checked it setting, and the access control says: "authenticated users" which is good.
but the moment i check it at other users (the non admin), i can only see the navigation block with "chaos Ajax demo" ONLY..

i checked around possible permissions, link settings, but with no luck..nothing seemed strange to me..

here's a screen shot of the navigation block at admin:

and here's 2nd shot at non admin (was working and showing few days back, but then suddenly became like this):

logically speaking, since the navigation block is existing at other users only means that its permissions is allowed for users to see the block.

but why suddenly it stopped showing the links?? im very much concerned about "add content" link, because i need it to add contents (otherwise, i'll have to go through a headache of creating 10s of manual links for each content to add).

let me note that I'm quit new to drupal, that's why I'm not pretty sure what did i mess with here.

any help is very appreciated, Thanks

First a clarification about terminology: make sure to correctly separate access to "blocks" from "navigation links": your non admin users seem to have access to that "block" also (that Ajax link in it proofs that to me). Your real issue/question should be something like "why are some of the menu links missing in that block?".

Seems like you need to resolve that "Access Denied" message first. Even though it's hard to tell (from the screenshots provided), My best guess would be that you need to review/tune some of the settings related to "node" within admin/people/permissions.

So check/confirm that for the users who receive this "Access Denied", they are granted the permission like "View Published Content". If that permission was not granted yet, then do so now and try again to see what happens.

A few more "comments" (moved from the comments below to around here):

The "menu items" that are shown in that block, will be shown (only) to the users who have access to the actual content (node) that the menu items are related to. And apart from that there is the "block visibility", which is typically something you "can" set so that it is only shown (or hidden) on specific pages, or so that it is only shown to users with specific roles.
About "I didn't want every user to other users' published content": looks like there is something you mis-interprete about the "View published content": that permission is ONLY a way to tell Drupal "which roles are allowed to see anything (nodes) that have the "published" checkbox turned on. It seems to me that you MIGHT need to add something like the (great!) "Content_Access" module to implement something similar to what you wrote in one of your last comments.
If it makes sense, you should set the "default" content access for each content type first, so that you only have to change it for those nodes where you want content access to be different from that default. So no need to "go through every content to manage their content access".


Adding a Custom Menu Fields I am new to Drupal and I am trying to create a menu (top navigation links) where a small description would be visible under the main Title.

I am trying to replicate this sites menu.

Is there any module that would allow me to do this? Or is there something I missing that would allow the Description that you type to show up the way I am looking for. Any help with this would be greatly appreciated!!

You can do this with theme_menu_link().

A menu item's description is by default output as a tooltip (ie, in the title attribute).  Here's a thread that shows how to do take advantage of that using hook_menu_link() to achieve more or less the result you want.


How to extend block.block.* schema configuration file Someone know how to exend this schema located in block module in core, to add a new data type in mapping from my custom module?

The point is that I need to add a Boolean field for all the blocks in the block configuration page and store this value (0 or 1) in all the block configuration files, but the problem I have is when I import the configuration for those blocks that does not  import the boolean field.

I guess I'm missing declare a "data type" for this boolean field.

    block.block.*:
      type: config_entity
      label: 'Block'
      mapping:
        id:
          type: string
          label: 'ID'
        theme:
          type: string
          label: 'Theme'
        region:
          type: string
          label: 'Region'
        weight:
          type: integer
          label: 'Weight'
        provider:
          type: string
          label: 'Provider'
        plugin:
          type: string
          label: 'Plugin'
        settings:
          type: block.settings.[%parent.plugin]
        visibility:
          type: sequence
          label: 'Visibility Conditions'
          sequence:
            type: condition.plugin.[id]
            label: 'Visibility Condition'

I want to add this

   mapping:
    hide_for_campaign:
      type: boolean
      label: 'Blocks hidden in campaign page'

The answer is to use the ThirdPartySettingsInterface Interface, using that interface you can add/save custom configuration for config entities, works perfect. Thank you !.

More info here
https://www.heididev.com/how-alter-configuration-entity-data-drupal-8-or-add-additional-data-configuration-entities


Change label in views php I am using the views php module and want a custom label.

The label field doesn't allow php to be entered, how would I go about changing the label?

In the view UI, choose a php field type

and your custom php code can be entered here:


Draggable table: drupal_render, render, both yield an empty string for "#weight" types? I am attempting to implement a draggable table in a Drupal 7 module. Whenever I invoke either render() or drupal_render on my element of type #weight, an empty string is returned. The table does render and I am able to drag the rows, but cannot see the weights. I cannot figure out what I am doing wrong: I've explored some core Drupal components that follow the same pattern (of invoking drupal_render on a #weight type element) and nothing is jumping out at me.

My form begins here:

$table_header = array_map(t, array('Order', 'Item', 'Manage'));
$form['table'] = array(
    '#theme' => 'mymodule_kw_table',
    '#header' => $table_header,
    '#rows' => $my_rows // array(string)
);

hook_theme() is implemented as such:

function mymodule_theme()
{
    return array(
        'mymodule_kw_table' => array(
            'render element' => 'form',
            'function' => 'mymodule_table'
        )
    );
}

Finally, mymodule_table() looks like this:

function mymodule_table($variables)
{
    $table_data = $variables['form'];
    $table_id = uniqid('tb');

    $rows = $table_data['#rows'];

    for ($i=0; $i < count($rows); ++$i) {
        $weight = array(
            '#type' => 'weight',
            '#title' => t('Order'),
            '#default_value' => $i,
            '#delta' => 1,
            '#attributes' => array('class' => array($table_id . '-weight'))
        );

        $rows[$i] = array(
            'data' => array_map(render, array($weight, $rows[$i], 'abcd placeholder')),
            'class' => array('draggable')
        );
    }

    $table = theme('table', array(
        'header' => array_map(t, array('Order', 'Item', 'Manage')),
        'rows' => $rows,
        'attributes' => array('id' => $table_id)
    ));

    $table .= drupal_render_children($table_data);

    drupal_add_tabledrag($table_id, 'order', 'sibling', $table_id . '-weight');

    return $table;
}

Weight objects can be rendered with form_process_weight()

    $weight = array(
        '#type' => 'weight',
        '#title' => t('Order'),
        '#default_value' => $i,
        '#delta' => 1,
        '#attributes' => array('class' => array($table_id . '-weight'))
    );

    $weight = form_process_weight($weight);


How to show cart with number of items in Ubercart? For his cart, my client wants a cart icon with the number of items in it. Not a list of all items. I searched around a little bit but didn't find anything.

As for D8 latest version, it looks like uc_cart_get_contents is not working anymore.  So here is how I managed to do it :

/** @var \Drupal\uc_cart\CartManager $cartManager */
$cartManager = \Drupal::service('uc_cart.manager');
$items = $cartManager->get()->getContents();
$variables['nbr_cart_items'] = count($items);


if string contains substring twig I feel a bit dummy as I can't make it work..

I'm trying to check if a string contains substring in my twig.

{% set url = url('<current>') %}
{{ url }}

{% if 'my-delivery' in url %}
    //print something
{% endif %}

The url is printed outside the if statement but it doesn't enter the if statement and the url contains 'my-delivery'.

Any idea why it doesn't work?

The twig function url() returns a render array, when you render it with the twig filter |render you get a markup object and when you render it again you get a string, which you can check whether it contains a substring:

{% set url = url('<current>') %}
{% if 'test' in url|render|render %}

url contains "test"

{% endif %}


Hide 'previous' on first and 'next' on last image in views slideshow I create slideshow using Views Slideshow module, controls are enabled (previous, next), I enable and 'End slideshow after last slide' in settings.

Now, how I can hide 'previous' text on first image in slide and 'next' text on the last image in slide?

Easiest way out is to use css. Hide the control when you don't need it.The particular element can be found by a simple inspection. Hope it helps.

display:none;

Another alternative is to use the slideshow API to customise the behaviour. You can start here.


Get node based target id from entity reference We have an Article content type which has an Entity Reference field called field_document that is linked to the Media bundle type of Document. In mymodule we need to write a hook that will take the current field_document.id (which maps to Document.mid) and return all the Article pages where field_document.target_id = mid.
Goal

Take the current node id and retrieve the Document entity that is linked to by accessing field_document
Using the field_document value, return other Articles that have the same value for field_document
Perform the query in a hook_preprocess_node() hook.

Question

How can we retrieve all the nodes based on the $mid?

When we tried
We were able to return all Articles. However when we add ->condition('field_document.target_id, $mid), we get zero results even though we know there are Articles where the field_document.target_id = $mid.
function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1);

  $and = $query->andConditionGroup();
  $and->condition('field_document', $linked_document_id, '=');
  $query->condition($and);
  $results = $query->execute();

  // returns zero
  ksm($results);
}

We also tried using $and->condition('field_document.target_id', $linked_document_id, '=');, but that did not return any results either.
Additional steps we tried, but with similar issue.
 function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1);
    ->condition('field_document', $linked_document_id, '=');
  $results = $query->execute();

  // returns zero
  ksm($results);
}

We found the issue, it was both duplicate data issue and syntax errors mentioned by @berramou. The fix to the query was  changing ->condition('status', 1); line to ->condition('status', 1).

We found that the test data included duplicate media entities so when the ->condition('field_document', $linked_document_id, '='); was added, there were no results because the entities we were expecting were not in the table.

Sample test data:

media entity (id=1) name --> foo
media entity (id=2) name --> foo
media entity (id=3) name --> bar
Article->field_document->target_id = 1

I was expecting foo (id=1) to be returned but I was receiving foo (id=2). We have a specific requirement that media entities should be unique so after we merged the duplicate ones, the issue resolved.

function mymodule_preprocess_node($variables) {
  $node = $variables['node'];
  $linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];

  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $node_storage->getQuery()
    ->condition('type', 'article')
    ->condition('status', 1)
    ->condition('field_document', $linked_document_id, '=');
  $results = $query->execute();

  // returns results now
  ksm($results);
}


How do I prevent node enumeration? I am currently developing a Drupal 8 site that will consist of one only central content type with a minimal menu structure. The user is supposed to navigate the site only by using a search/filter form (similar to a search engine) and I would like to disallow all methods for locating content other than using the search form.
The problem is: All content in Drupal is normally accessible by using <site>/node/<somenumber>, which makes it easy to locate all content by simply counting upwards (I think, this process is called node enumeration). I know, I can use the Pathauto module to generate a pattern for URL aliases (say, a random hash). Unfortunately, that won't prevent the original URLs from being accessible: When entered, they will simply be forwarded to the generated aliases.
So, my question is: Is there a way to prevent this node enumeration from being possible? Is it possible to have the node available only under the generated aliases and not forward the original URLs?
All help would be much appreciated.

This is difficult, because it is core functionality.
What you could do to prevent people from checking node/4, node/5 etc is blocking access when a url request has a certain structure. You'd need a custom module with an EventSubscriber.
Here is an example how to intercept such url requests and how to redirect them. In this case it is a taxonomy term view but the underlying thought is the same: https://stefvanlooveren.me/blog/redirect-taxonomy-terms-filtered-view-page
Further, you'd have to check in your html rendering that every reference to a node id is hidden. Quite some work but if it is really necessary its possible.


Getting the value of a checkbox in form api I'm creating a form using Drupal's form API.  This form includes about 50 or so checkboxes that I'm creating using the type 'checkbox'.  The checkboxes are grouped using several fieldset elements.  The checkbox is created from a look using an XML file that decides what checkboxes will appear.

$ageKey = '08';
$course = 'y';

$form['events'][$ageKey][$course] = array(
  '#type' => 'fieldset',
  '#title' => 'Set of checkboxes'
}

foreach($xCourse->event as $event) {
  $eventKey = (int)$event['distance'] .'-' . (int)$event['event'];
  $form['events'][$ageKey][$course][$ageKey . ' ' . $course . ' ' . $eventKey] = array(
    '#type' => 'checkbox',
    '#title' => (int)$event['distance'] . ' ' . $top5->dispStroke((int)$event['stroke']),
    '#default_value' => 1,
  );
}

I'm using hook_submit to process the form

function import_form_submit($form, &$form_state) {
  $checkboxes = $form_state['values'];

  //do stuff here
}

However, I find that the value for all my checkboxes is 0, regardless if the checkbox was unchecked by me or not.  If I remove '#default_value' => 1 from the checkbox definition, none of the checkboxes are checked by default.  The values array also appears to ignore the hierarchy I set up.

How do I get the checked state of the checkbox in my submission code? What am I missing here?

I found the answer.  I added '#tree' => TRUE, to the fieldset and suddenly things are working correctly.  I think because of the eventKeys were repeated so overwriting others. By adding the tree attribute, all the checkboxes were seperated into their respective fieldsets in the $form_state['values'] array.


Entity reference of a menu link gives Restricted access instead of the real data I am trying to create an entity reference of a "menu link", but instead of having the menu link name I got  "- Restricted access -".
It seems to be the same problem with wysiwyg profile.
I'm using the last version of entity reference (7.x-1.1), event the dev version is the build.

I'm using admin with full right on everything.

Any idea why ?

Here is an issue I found on drupal .org: https://drupal.org/node/2153463

There is a patch inside to fix the issue but it doesn't seem like the final patch, so decide if you want to use it. Your alternative is to use an old version of entity reference which doesn't have this bug.


Display Suite Extra Fields not showing in content page Display suite extra fields are shown in the manage display.  Fields such as author, user, AND submitted by, are enabled in the custom regions I have defined using a custom ds layout.  When I go to the full content page it does not show any of the extra ds fields that i enabled.  Does anybody know what the issue can be?

I'm using a custom ds layout

custom_article:
  label: article
  category: My Layouts
  template: templates/custom_article
  css: css/custom-article.css
  regions:
    header:
      label: header
    author:
      label: author
    body:
      label: body

I would try adding a class key, for example:

class: '\Drupal\ds\Plugin\DsLayout'

Also, I think you should update the template line, replace the underscore with a hyphen (and do the same for the actual twig file), for example:

template: templates/custom-article


Error: Private files directory not fully protected I received the following error in my Drupal 8 status report:

PRIVATE FILES DIRECTORY Not fully protected See
https://www.drupal.org/SA-CORE-2013-003 for information about the
recommended .htaccess file which should be added to the private://
directory to help protect against arbitrary code execution.

The obsolete link provided shows no guidance for Drupal 8 or 9, only 7 and prior. I already have what I believe is a strict .htaccess file I'd found elsewhere in Drupal's documentation. How can I fix this error in Drupal 8?

Submit the admin form @/admin/config/media/file-system will also create this .htaccess file if your folders are setup correct.


How can I set a default node owner for anonymous nodes on the node edit form? This question is refining the poorly asked Is there any easy way to set the default author for a node being edited to the current author if it is currently anonymous?

The site I'm working on has a lot of Anonymous nodes because it is a migration from a system that didn't have a proper user system.  Users can claim their articles (they have permission via the override node options module) by going in and editing the node and changing the system author.

I'd like the default value on the edit form for node owner to be the current user for non-admin users who are editing a node that was not owned by anyone previously.  I'm sure it must be imminently doable through some form alter or form preprocess hook, but I don't quite get the drupal form system yet.  Solutions and pointers to good sources of information both welcome.  My ulterior motive in this question is to learn more about how to use hook_form_alter to change the values of fields on the form, and particularly the owner field, so answers related to that are preferred.

You can do this pretty quickly in a custom module by implementing a hook_form_alter().

In this example, I created a module called "anon" (you might want to use something more specific) and in my anon.module, I have the following:

<?php

/**
 * Implements hook_form_alter()
 */
function anon_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "article_node_form" && isset($form['author']['name']['#default_value']) && $form['author']['name']['#default_value'] == "") {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

The above code checks to see if you are on a article_node_form (change this to the content type you are using), if the author of the form is blank (which is representative of an anonymous user) and then sets the author name to the currently logged in user name.

Note that by default a new form will always set the author value to the logged in user, so this would only apply for existing nodes.


Force redirect if a valid taxonomy term is not at the start of the URL? As a follow on from this question I am trying to prepend all URLs on the site with a taxonomy term.

The term itself is handled by a custom module for the most part, however elements of the site such as the calendar modules page view don't allow for me to intervene and theme the link accordingly. If a user goes to the following URL:

site.com/calendar

Then they should be redirected to:

site.com/city/calendar

The city itself would be acquired from a cookie set when they hit the front page of the site, or defaults to 'all-cities'.

My vision for such a system was to check in hook_boot against a predefined array for offending patterns (such as calendar) and if they are found, then it forces a redirect to the same page but prepends the city.

My gut feeling is that this is a bad approach and possibly un-Drupal. Please let me know if there is a standardized method I should be following for such things.

O’ Salvation, Deliver Me From Evil!

I wouldn't recommend using such system because I also have the gut feeling that this would create some major confusion for modules relying on the drupal path system.

I think you should better deal with subdomains like city.site.com.


Add a new configurations block to admin/config I'm trying to add a new configurations block to admin/config (just like "People", "Media" and "System").

I tried copying and modifying the relevant lines from modules/user/user.module but my block doesn't show and directly going to the link admin/config/mysite results in an access denied message.

The sub pages appear directly under the Administration > Configuration menu in the Administration module (but not in the page admin/config.)

Any idea how to fix this?

$items['admin/config/mysite'] = array(
  'title' => 'My Site',
  'description' => 'Configure My Site settings.',
  'position' => 'left',
  'weight' => -20,
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

$items['admin/config/mysite/page1'] = array(
  'title' => 'Sub page 1',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mysite_admin_1'),
  'access arguments' => array('access administration pages'),
);

$items['admin/config/mysite/page2'] = array(
  'title' => 'Sub page 2',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mysite_admin_2'),
  'access arguments' => array('access administration pages'),
);

I have solved my own problem. The reason the links appeared where they did and not under my new block is that I've moved existing items to a new location, which means they were still in the original location in the menu configuration screen. Moving them manually to their correct location solved the problem.


Is there a way to generate dummy content for custom entities? Since the Devel module allows to generate content only for core entities:

  Accelerate development of your site or module by quickly generating nodes, comments, terms, users, and more.

Is there a module or a proper way to generate fake content for custom entities?

I mention that I found Devel contrib module that includes the Devel Contrib Generate module, which allows generating of dummy entities of any entity type, but I've not been able to figure out how to use it with D8.

To create some demo entities programmatically, you can use a while loop in your function.  To create 100 entities:

$i = 1;
while ($i <= 100) {
  $i++;

  // Create an entity here.  See https://www.drupal.org/docs/8/api/entity-api/working-with-the-entity-api#s-create
  // To create random strings (e.g. for fake titles), refer to the comments at https://www.php.net/manual/en/function.rand.php -- In here you will find different ways to create random strings.
  // Generate some Lorem Ipsum text if you like: https://stackoverflow.com/a/20633400/861826

}


Use 2 different font sizes on combobox form elements In a form combobox, is it possible to have each combo box element have 2 different font sizes?

Blue (like the sky)
Yellow (like the sun)
Green (like the mix of the above)

The color names would display using a 16px font.
The text in parentheses would display using a 11px font.

If it's possible in HTML & CSS flavour you are using, it is. There are two ways:

Purely CSS one, described at w3schools and not really belonging to this site as it's Drupal independent.
Class way - to get more flexibility and compatibility, add classes to your <option> tags inside your <select>. You can do this implementing theme_select() in your theme. You would need to replace form_select_options() with your own function providing similar functionality, or parse original one's output to add your classes.


Commerce line item views with fields from content node I have some fields on content node (not on product variation)
like images, brand, and others that i want to show up in cart/order views
on edit view in advance>relationship, you can add product refference and that enables the option to add fields from product variations, but i cant find a way to add fields that are on the content node

In less words: i want to add fileds like image that are on the content type to cart/order views.

Found a good work around:

adding relationship you can obtain fields from product in views.

This isn't easy, because the line item has no direct reference to the node. It does store the node URL in a textfield, but that does not a Views reference make. If you have a store where there's only one product display referencing each product, then you can get away with using a reverse product reference - i.e. starting with the line item, you reference the product, and from the product, you add a reverse reference to the "node referencing the product." Then you should be able to add fields from the product display node.

If you have multiple product displays referencing any given product, this solution might not work (unless of course each node contained the same fields you intend to pull into the View).


How to get database credentials I am integrating code that implements its own extension of PHP's PDO class, in the same way that Drupal's DatabaseConnection does. So this code (which is various data models) needs to use this non-drupal PDO object.

This code needs DSN, username and password to access the default drupal database. I noted that $databases, defined in settings.php is not available: global $databases does not work to give me access to that data.

Is there a way to ask Drupal for this info or extract it from the default connection object?

The following works perfectly for me in devel/php

global $databases;

dpm($databases);

It should return the full array of database information:


What is the scope of the drupal session cookie? I am bootstrapping drupal 7 (using DRUPAL_BOOTSTRAP_FULL) so that I can use drupal's authentication/security features in the rapid development of a web app I'm doing a proof of concept for. (And yes I know it is better to use drush to bootstrap drupal.)

If the PHP file that I am bootstrapping drupal from is in the root drupal directory, then the bootstrapping works -- I know this because inspecting the $user global variable will show that I am logged in.

If the PHP file is not in the root drupal directory (whether a subdirectory of the root drupal directory or a sibling of the root drupal directory), then the bootstrapping works -- I can inspect the $user global variable, but the $user variable says I am an anonymous user rather than the logged in user that I am.

Is my suspicion right that this is related to the scope of the drupal session cookie? If so, what is that scope?

Better late than never?

Yes, if you are creating the cookie with a default path. It will use the current page path. So the cookie will be restricted to any path starting with the defined one (if it's /a/b then the cookie will be available for /a/b, a/b/c etc but not /a alone).

(I had a short period of hair-tearing once where I was accessing a site using it's IP address and unable to understand why the cookies weren't available ... they were hardwired to the domain.)


How to write custom Form API elements for Drupal 7? In context of this question I wanted to ask - how to provide custom controls to use with Form API? Especially ones that needs to be exploded into javascript and at least one additional hidden field to make their GUI work.

I can find manuals for Drupal 6 easily enough, but somehow I can't spot ones for 7. I know I need to start with hook_element_info(), but hook's description for Drupal 7 points to a manual for Drupal 6.

Could anyone provide step-by-step instruction how to make it work?

Searching Google for "hook_element_info tutorial" brings up Create custom Form API elements with hook_element_info() in Drupal 7.

There is also the Examples for Developers project, which is included in the documentation at http://api.drupal.org. The Form API Example module implements hook_element_info() and contains a number of example elements in the form_example_elements.inc file.


Adding comments to pages Is it possible to add a the content type comments to a page? When I create a page and look to see what can be added into a panel comments are not available

Thank you!

You might be confusing things which makes your question hard to answer.

Please note that comments are not a content type, but they are part of nodes, and thus can be appended to any content type. Comment's can't be used inside the Panels module because they are part of a node (one is to import the whole node).

If you meant page rather then panel. Please make sure the comments module is enabled in modules. And then go to the 'basis page' content type and check the 'comment settings' tab (at the bottom) to see if comments are open.


Get all children of a term I  have the following tree structure, I want to get all child terms. I implemented taxonomy_get_children('tid') drupal api function.

1.Gloves
 1.1 Seamless
   1.1.1 Kevlar
    1.1.1.1 Shell
    1.1.1.2 Dots
    1.1.1.3 Coated
 1.2 mechanics
 1.3 cut and sewn
2.Apparels
 2.1 Coveralls
 2.2 Aprons
 2.3 Trousers

When I clicked on Apparels I successsfully get all child terms using but when I clicked on Gloves, it provides me only top level child terms ('seamless', 'mechanics','cut and sewn'), not the deep levels.

Use taxonomy_get_tree instead, it takes vocabulary ID as the first param, and the term ID under which to generate the tree - this should give you all children of a term.

More info here.


How to disable all commerce modules from Commerce Kickstart using Drush? I need to disable all commerce modules from the Commerce Kickstart distribution. I've done this before using the drupal backend admin/modules and have no problem at all but it took me around 4hs because of the modules dependencies.

This time I would like to do it using Drush.

How can I do this?

I tried with drush dis -y commerce but I get a lot of error/warning lines (not sure if it worths to post them here...) and get the site broken.

Note that by disabling all of the Kickstart specific modules (which is practically required to uninstall Commerce due to dependencies) may cause your site to become unusable. If you're using the image rotator or the Kickstart specific content types things could get really crazy. You've been warned. Go slowly.

I know you want to know how to do it in drush, but using the UI will likely be easier given the amount of time it will take to do this:

Uninstall the Kickstart specific modules. These will be all of the modules whose Package is Commerce Kickstart. There should be 18 of these. Disable one or two at a time. You have to do these first.
Once those are done, then you'll need to go through and disable all of the Commerce Contrib modules. These would be modules found under Commerce (Contrib), Commerce (whatever), etc.
Once those are done, then you should be able to disable the Commerce core modules.


How to edit Media module`s display profiles? I can`t find where can i edit media module profiles.
There are no any link in admin section.

They are to be edited on file-types page in Structure:
admin/structure/file-types


Display the URL of where the content is located in my search results I'm using SOLR search/search API on my Drupal 8 site and I've set the view to display the following two fields:

Content datasource: Title (The title & link to the page)
Search: Excerpt (Highlighted text of the searched keywords found on the page)

I would also like to display the URL of the page that the content is located below those two fields. However, there is no URL field to add. I've also tried to get just the URL from the 'Title' field, but can't seem to get it from there either.

Below is an example of what I'm trying to achieve.

Would anyone have any ideas as to how to add that at all?

Search API provides several general fields (e.g. Aggregated field, Rendered HTML output, URI, etc.) which are available to all Datasources.

Edit your index, when on the Fields tab, click Add fields and under the General heading add URI. You will need to re-index your content and the new fields should be available.


HowTo - Image Style's 404 image How could I define an image for those images that are not found (404's). In other words, if image which is displaying with image style is not found, provide an another image?

If someone is interested here is my solution:

function themeName_image_style($variables) {
  // Determine the dimensions of the styled image.

  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
);

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the url for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  // Load default image for 404's
  if(!file_exists($variables['path'])) {
    $variables['path'] = file_create_url('/sites/all/themes/custom/lsa/css/images/404.png');
  }

  return theme('image', $variables);
}

Go to Administration -> Structure -> Content Types, select the name of your content type, then click on Manage Fields.  Find the image field, click edit for that field, then scroll down until you see the Image Field Settings section.  Click the default image button, and select what image you want to show by default.


How to show votes in view results by node id? I installed the modules "rate (voting widget)" and "voting api". These modules work very well.
I use views to get a list of nodes, and I added the voting results. Now I get a row for each vote, not for each node...

Views rows:

Node 1  --  angry: 1  happy: 1
Node 1  --  angry: 1  happy: 1

Node 2  --  angry: 1  happy: 0

Node 3  --  angry: 0  happy: 1

I want to group the results by node id, but this doesn't seem to work. what would be the easiest solution for this problem?

You can use hook_query_alter() in your custom module. Your code should look like this:

function MODULENAME_query_alter(&$query) {
  if(!empty($query->alterMetaData['view']->name) && $query->alterMetaData['view']->name == 'VIEWNAME'){
    $query->groupBy("node.nid");
  }
}


Way to have a theme-settings form input to accept numbers only? I am creating some theme settings and am creating a form to populate them in theme-settings.php. I am using the hook hook_form_system_theme_settings_alter().

I would like to restrict or verify that only numbers can be entered into a field. I've searched online but have not found how to do this. Would anyone know what I ought to add to my code?

Code currently looks like:

$form['mysite_theme']['mysite_contact_phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Contact Number'),
    '#default_value' => $default['mysite_contact_phone'],
    '#description' => t('Enter the main contact number for this site.'),
    '#required' => TRUE,
  );

You should be able to add your own validation handler. After the code you've shown, add this:

$form['#validate'][] = 'my_validation_handler';

Then in your handler, you can add your own validation:

function my_validation_handler($form, &$form_state)
{
  if(!is_numeric($form_state['values']['mysite_contact_phone']))
  {
    form_set_error('mysite_contact_phone', t('Contact number must be numeric'));
  }
}


How do I allow regular non-admin users to view other users' emails? Email is now an included field in core, but the stock email for users seems to be set to private; only users with administrator privileges or the user themselves can see.

I'd like to allow other users to see this basic field, without having to create yet another email field where someone has to copy the information over from the other other simply for the ability for it to be visible.

This should be a fairly easy/common practice, but I can't find anything yet.

How do I allow regular non-admin users to view other users' emails?

One route you can take is to allow users the View user information permission and display this information on the user profile page.

To do so, override user.html.twig in your theme (copy it from core/modules/user/templates/user.html.twig to your theme's template directory) then inject the email into the template via hook_preprocess_user() in your mytheme.theme file:

/**
 * Implements hook_preprocess_user()
 */
function mytheme_preprocess_user(&$variables) {
  $variables['mail'] = $variables['user']->getEmail();
}

In this example, you'll be able to user {{ mail }} to insert the email variable into your user profile template.


End-user Documentation Generation Is there a way to automatically generate end-user documentation (likely in a stubbed or skeletal format) for content types that you have setup?

Perhaps there is a module that does this?

Drupal has an API for documentation and comment standards that allow you embed comments in the code using a special syntax that will automatically generate documentation for the module, including modules that create content types.

This is the system that is used to automatically generate the online API reference  found on http://api.drupal.org and other similar sites.

The API module used to generate these pages parses documentation and code in PHP files, and it expects documentation to be in a format similar to other code/documentation parsing systems such as PHPDoc, JavaDoc, etc. The system was originally based on doxygen, but it has evolved into something that has its own set of tags and Drupal-specific functionality.


How to pass on the user id(block user) after registration I am working on a project where users need to pay to use site.Site have a registration form where user can register and redirected to the payment page.All the resisted users are blocked until they make payment.
The registration process working fine but, when user redirects to payment page there is no method to get resisted user id. How to get registered user id on payment page?

The user registration form is generated by user_register_form(), and like normal Drupal forms, it can be altered via hook_form_alter or hook_form_FORM_ID_alter. When not explicitely set, the submit handler of a form is named form_id_submit(), however, in user_register_form, a submit handler is added to the #submit property of the form - user_register_submit().

In the function user_register_submit, you'll notice the following codes:

...
$form_state['user'] = $account;
$form_state['values']['uid'] = $account->uid;
...

which saves the new user object and ID in $form_state.

To access this after the registration form is submitted, simply add a custom submit handler via hook_form_alter() or hook_form_FORM_ID_alter(). Example:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the user registration form by adding a custom submit handler.
 */
function foo_form_user_register_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] 'foo_user_register_form_submit';
}

/**
 * Custom submit handler for the user registration form.
 */
function foo_user_register_form_submit($form, &$form_state) {
  $account = $form_state['user'];

  $uid = $form_state['values']['uid'];

  // Do something meaningful
}


Class 'Drupal\user\Entity\User' not found when running drush I am trying to run a drush on functional Drupal 7 site, however, the attempt of run drush ends with an error saying: Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php, line 571.

Any idea what may be happening?

Full output:

vagrant@1843vm:/var/www/drupalvm/drupal/web$ drush
PHP Fatal error:  Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php on line 571
[error]  Drush command terminated abnormally due to an unrecoverable error.
Error: Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php, line 571
[error]  Drush was not able to start (bootstrap) Drupal.
Hint: This error can only occur once the database connection has already been successfully initiated, therefore this error generally points to a site configuration issue, and not a problem connecting to the database.

Drush was attempting to connect to:
 drupal-version         :  7.50
 drupal-settings-file   :  sites/default/settings.php
 uri                    :  http://default
 db-driver              :  mysql
 db-hostname            :  localhost
 db-username            :  root
 db-password            :  123
 db-name                :  il
 db-port                :
 install-profile        :  standard
 db-status              :  Connected
 theme                  :  intelligent_life
 admin-theme            :  seven
 php-bin                :  /usr/bin/php
 php-os                 :  Linux
 php-conf               :  /etc/php/5.6/cli/php.ini
 drush-script           :  /usr/local/share/drush/drush.php
 drush-version          :  9.0-dev-g1c91f8b
 drush-temp             :  /tmp
 drush-conf             :
 drush-alias-files      :  /home/vagrant/.drush/drupalvm.aliases.drushrc.php
 root                   :  /var/www/drupalvm/drupal/web
 site                   :  sites/default
 modules                :  sites/all/modules
 themes                 :  sites/all/themes
 files                  :  sites/default/files
 temp                   :  /tmp
 %paths                 :  /var/www/drupalvm/drupal/web
                       sites/default
                       sites/all/modules
                       sites/all/themes
                       sites/default/files
                       /tmp`

I had the same problem, it's related to the Drush version used by the DrupalVM.
You can change the Drush version in the config.yml file.

More info: https://github.com/geerlingguy/drupal-vm/issues/1020


Override autocomplete provided by module to not suggest current user(self) I hope it's pretty clear from my question title itself. I want to override autocomplete provided by module such as privatemessage to not suggest the current user(self) who is trying to send message.
I tried doing some research about it but all I got was about overriding JS file.

I have used automcomplete with my custom form long ago & when I prepared the JSON, I removed current user from the list. But what to do if I have to do the same for some contributed module ?

If you look at the code in Privatemsg module, the autocomplete callback function provides a hook hook_privatemsg_autocomplete_alter(). You can use this hook and unset the current logged in user from the $matches array.

I don't have Privatemsg module installed in any of my current projects, so I cannot test it, but the following code should do it:

function YOURMODULE_privatemsg_autocomplete_alter(&$matches, $names, $fragment) {
  global $user;
  unset($matches[$user->uid]);
}


Custom webform validation handler not getting called using Event subscriber I am trying to implement a custom validation for webform. I need to validate if user entered email is valid or not. For that I have altered the webform using event subscriber and assigned a validation handler. But validation handler is not getting called. The configured webform is ajax enabled. Below is my code.

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;

/**
 * Altering drupal forms with hook_event_dispatcher.
 */
class ContactWebFormFormAlterEventSubScriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      HookEventDispatcherInterface::FORM_ALTER => 'hookFormAlter',
    ];
  }

  /**
   * Altering form array from here.
   */
  public function hookFormAlter($event) {
    if ( strpos( $event->getFormId(), 'webform_submission_contact_us' ) !== false ) {
      $form = $event->getForm();
      $form['#validate'][] = '::mymodule_webform_submission_contact_us_validate';
      $event->setForm($form);
    }
  }

  /**
   * Altering form array from here.
   */
  public function mymodule_webform_submission_contact_us_validate(array &$form, FormStateInterface $form_state) {
    $email = $form_state->getValue('email');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $form_state->setErrorByName('email', $this->t('Email address is invalid'));
    }
  }
}

You should use a custom webform plugin handler for that.

More information here: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element


How to translate page titles? I'm using the awesome Internationalization Module for managing the translations of my multilingual website. The name of each menu item also becomes the page title (the HTML TITLE tags). When switching languages everything works perfectly except the page titles. The page title shows correctly the name of the page, but in the LAST language I translated that menu link into. The last added translation of the menu is Chinese, so the page titles are always Chinese, regardless wheter you are on the Swedish or French version of that page.

Using Drupal 7.18
Using Internationalization module 7.x-1.7, fully enabled.
The multilingual options of the menu are set to 'Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.'

What could I try to fix this?

while translaing page, there is an option at bottom 'provide a menu link'. check this field with title...


What does typical beginning mark in *.tpl.php files mean? I'm looking into template files for theming purposes, and often at the beginning of the file there is a // $Id$ mark.

Could you explain me what it mean, and what the purpose of it is?

It is a placeholder, that is automatically replaced by CVS and then contains information about CVS version, author and so on of the file. For more information, see http://badgertronics.com/writings/cvs/keywords.html.

Since Drupal.org recently switched to Git as the version control system, this tag is now completely irrelevant so it can and should be removed. In fact, it has been removed automatically during the CVS -> Git migration for all modules on drupal.org


How to get the path of a drush command? I'm creating a starter kit for the Panopoly distro that will generate a skeleton distribution using Panopoly as a base distribution.  I'm doing this with a custom drush command.  The code can be seen here.

I'm using a STARTERKIT folder that contains all of the code that will be copied and go through string/token replacements.  The drush command is working well however what I'm unable to figure out is how to programmatically figure out where the STARTERKIT folder is.  Right now I'm relying on the user entering --include=path/to/drush.command option.

Assuming the user copies the whole project to their ~/.drush folder they can run the drush command without the --include attribute but then my command does not know where the STARTERKIT folder is.

Here is where I'm using the --include option to locate the STARTERKIT folder.

You could make a wrapper script panopoly_starter_kit.sh, and determine the path to the script via $0.  Your script would then just run your drush command, supplying the --include variable.  See the drush script for an example of how a bash script can find the directory that the script itself is located.

UPDATE:

Another option would be to use a Drush script instead of a Drush command to do your installation.  You would lose your help output, but you could still process arguments and options.  See drush topic docs-examplescript for details.


EntityFieldQuery with fieldCondition returns nothing I have created a custom entity, called 'point'.

I'm able to get all of the entities in the db, with this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'point')
    ->entityCondition('bundle', 'point');
$result = $query->execute();

But when I add a fieldCondition, to make sure I only get the one single entity I want, I'll get an empty array back.

It looks like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'point')
    ->entityCondition('bundle', 'point')
    ->fieldCondition('field_point_unique_number', 'value', $unique_number, '=');
$result = $query->execute();

Where $unique_number is a textstring. And it's not a typo in the textstring.
In the db the field 'field_point_unique_number' is a varchar, but only contains numbers.

Why does the fieldCondition return nothing?

I hadn't checked it for trailing spaces. So using trim() on $unique_number did the trick. Thanks for leading me the right way Clive!


Perform task on opening the site I'm new to writing modules.

I would like my custom module to perform a task whenever the main page is loaded and no user is logged in, like when a user enters the url to my page, then the page loads and does something. I searched for a while now, but can't find the hook for this

What i tried was this:

function mymod_menu() {
  $items = array();

  $items['/'] = array('page callback' => 'mymod_do_it');

  return $items;
}

But this does not work. At the moment despair is joining me with this.

Any help would be very appreciated.

Thank You!

You might check out the 'Examples for Developers' project page for some relevant examples:
https://www.drupal.org/project/examples

I think you want to use hook_init instead of hook_menu. Try this:

function mymod_init() {
  if (drupal_is_front_page()){
    $items = array();

    $items['/'] = array('page callback' => 'mymod_do_it');

    return $items;
  }
}


How to ajax changing date field on _node_form? On content type called Order have 2 fields - "Category name" (term reference) and "Date" (Date (Unix timestamp)). On node edit form I want to change date to other value (for test purpose it is "hard coded", see code below) on changing "Category name".
Ajax fire on "Category name" and "Date" fieldset "fade" but date value still no change.

Code:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'order_node_form') {
    // Date (Unix timestamp)
    $form['field_date']['#prefix'] = '
';
    $form['field_date']['#suffix'] = '
';

    // Taxonomy reference select list
    $form['field_category_name']['und']['#ajax'] = array(
      'callback' => 'category_name_callback',
      'wrapper' => 'field-date-replace',
      'method' => 'replace',
      'effect' => 'fade',
    );

    if (!empty($form_state['field_category_name']['und'][0]['tid'])) {
      $form['field_date']['und'][0]['#default_value']['value'] = strtotime('12/12/2013 00:00:00');
    }

    // Test - work if uncommented
    //$form['field_date']['und'][0]['#default_value']['value'] = strtotime('10/10/2013 00:00:00');
  }
}

function category_name_callback(&$form, &$form_state) {
  // don't work too
  //return $form['field_date'];

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#field-date-replace", render($form['field_date'])),
    ),
  );
}

I found a solution but not why, if someone knows and says I will mark as the correct answer.
Phone type behaves similarly to the decision to date and it is the same.

First of all this was hard to debug. For this I add in ajax callback the line

ajax_command_prepend("#field-date-replace", theme_status_messages(dpm($form_state)), 'status'),

And now all code

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'order_node_form') {
    // Date (Unix timestamp)
    $form['field_date']['#prefix'] = '
';
    $form['field_date']['#suffix'] = '
';

    // simple text line input
    $form['field_some_text']['#prefix'] = '
';
    $form['field_some_text']['#suffix'] = '
';

    // Phone number module field
    $form['field_phone']['#prefix'] = '
';
    $form['field_phone']['#suffix'] = '
';

    // Taxonomy reference select list
    $form['field_category_name']['und']['#ajax'] = array(
      'callback' => 'category_name_callback_func',
      'wrapper' => 'field-some-text-replace',
      'method' => 'replace',
      'effect' => 'fade',
    );

    if (!empty($form_state['values']['field_category_name']['und'][0]['tid'])) {
      $form['field_some_text']['und'][0]['value']['#value'] = 'after change';
    }
    else {
      $form['field_some_text']['und'][0]['value']['#value'] = 'before change';
    }

  }
}

/**
 * AJAX callback for 'field_category_name' form
 */
function category_name_callback_func($form, $form_state) {

  if (!empty($form_state['values']['field_category_name']['und'][0]['tid'])) {
    $form['field_phone']['und'][0]['number']['#value'] = '999999';
    $form['field_phone']['und'][0]['country_codes']['#value'] = 'gb';

    $form['field_date']['und'][0]['value']['date']['#value'] = '01/01/2014';
  }
  else {
    $form['field_phone']['und'][0]['number']['#value'] = '';
    $form['field_phone']['und'][0]['country_codes']['#value'] = '';
  }

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#field-date-replace", render($form['field_date'])),
      ajax_command_replace("#field-some-text-replace", render($form['field_some_text'])),
      ajax_command_replace("#field-phone-replace", render($form['field_phone'])),

      // remove comment (//) on next line for debuging
      //ajax_command_prepend("#field-date-replace", theme_status_messages(dpm($form_state)), 'status'),
    ),
  );
}

The difference between all the examples I've seen, and this decision is that the values change is made in "ajax callback" but not in hook_form_alter.


When creating a module, where do I set cookies? Drupal 7 newb here.

I am creating a simple module. Basically, this has an admin config form with a message text area. On the front end, that message appears or not depending on the state of a cookie.

My question is: where (in what function) should you set the cookie?

My code is:

/**
 * Implements hook_block_info().
 */
function message_block_info() {
  return [
    'message_block' => [
      'info' => t('Message'),
      'cache' => DRUPAL_CACHE_GLOBAL,
    ],
  ];
}

/**
 * Implements hook_theme().
 */
function message_theme() {
  return [
    'message_block' => [
      'template' => 'templates/message-block',
      'variables' => [
        'config' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_block_view().
 */
function message_block_view($delta = '') {
  if ($delta !== 'message_block') {
    return;
  }

  $config = message_default_settings();
  if (empty($config['alert_message']) || $config['alert_show'] === 0) {
    return;
  }

  $block['content'] = array(
    '#theme' => 'message_block',
    '#config' => array(
      'alert_show' => $config['alert_show'],
      'alert_message' => filter_xss($config['alert_message']),
      'alert_link' => filter_xss($config['alert_link']),
    ),
  );

  return $block;
}

Here i set the cookie as user login and logged out.

/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-logged-in', '2', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-logged-in']);
}

You can try it will able to create new cookie anywhere i.e Create cookie into  hook_init()
https://www.drupal.org/forum/support/theme-development/2009-05-26/setting-custom-cookies#comment-2901778


Is there a way module to tell if you're logged into Dev, Stage, or Production Our deployment model has

Dev
Stage
Production
Failover (mysql replication and load balancer)

Our problem is that the server has failed over, we want to alert content editors that they're on the failover, or moreso, we'd like to ensure they're editing in the production areas and not on a development box.

Is there a way to distinguish the environment, after a user logs in? Is there a module by which color codes the admin bar depending on the server's host name?

Try Environment Indicator, it does exactly what you want.

  This module will help you to keep sane while working on your different
  environments by adding a configurable color bar to each one of your
  environments.

It also integrates nicely with Admin Menu.


Apply Image styles for migrated images I've done a drupal migration from drupal 6 to drupal 8.
While all files are migrated well, image styles are not applying on migrated images.

Image styles are applied to the newly added images.

I think I should have force drupal to generate image styles for migrated images, but I don't know how.

any help one that is appreciated.

PS. I read some information about Flushing image styles in drupal 7 but I couldn't find a proper way to use it in drupal 8 as a custom module.

To solve the problem I used the code below to force Drupal to create the image styles for my nodes:

if ($entity->hasField('field_image') && $entity->get('field_image')->getValue() != null) {
  $image = \Drupal::service('image.factory')->get($entity->get('field_image')->entity->getFileUri());
  if ($image->isValid()) {
    $styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();
    $image_uri = $entity->get('field_image')->entity->getFileUri();
    foreach ($styles as $style) {
      $destination = $style->buildUri($image_uri);
      $style->createDerivative($image_uri, $destination);
    }
  }
}

Here is the description, for each node ($entity variable) , first it checks if the node type has a field with machine name "field_image" and if this field has a value, then it checks if fileUri is a valid image, then if all conditions met, the code iterates on all image styles available and build that style for given image manually.

This code can be used as a cron job function, so on every cron job image styles of given nodes are created.


How to get list of templates for the active theme? I am creating UI that will allow users to edit the active theme's template files(something like Wordpress does). For this I need to get the list of all templates from the system and to know which templates are already overridden by the front-end theme.

The list of templates can be retrieved via \Drupal::service('theme.registry')->get(). The problem is that this will return templates of the currently used theme therefore this will not return templates that are overridden by the front-end theme(since this is done on the back-end which has different theme).

The class \Drupal\Core\Theme\Registry has option to specify the theme in it's constructor but there is no option to set this via the service. Calling the class directly would require me to take care of DI and it's not what I'd want to do anyway(not very Drupal-way approach).

In the init() method there is logic that would rebuild the registry if there is no global theme key set or the theme name is different from theme information but I don' want to fiddle with global variables.

So what would be the proper way to do this?

This is a working prototype, although I will be rewritting it a bit later.

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Form\ThemeTemplateForm.
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Theme\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Component\Utility\String;

/**
 * Form for editing template files for current theme.
 */
class ThemeTemplateForm extends FormBase {

  /**
   * The cache backend to use for the complete theme registry data.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The lock backend that should be used.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

  /**
   * The module handler to use to load modules.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme registry service.
   *
   * @var \Drupal\Core\Theme\Registry
   */
  protected $registry;

  /**
   * The template that is being edited/created.
   *
   * @var string
   */
  protected $template;

  /**
   * The front-end theme that we'll be editing templates for.
   *
   * @var string
   */
  protected $theme;

  /**
   * Creates ThemeTemplateForm object.
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend interface to use for the complete theme registry data.
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to use to load modules.
   */
  public function __construct(CacheBackendInterface $cache, LockBackendInterface $lock, ModuleHandlerInterface $module_handler) {
    $this->cache = $cache;
    $this->lock = $lock;
    $this->moduleHandler = $module_handler;
    $this->theme = $this->config('system.theme')->get('default');
    $this->registry = new Registry($this->cache, $this->lock, $this->moduleHandler, $this->theme);

    $template = $this->getRequest()->query->get('template');
    if (!empty($template) && $this->templateIsAllowed($template)) {
      // Always use machine name of the template
      $this->template = str_replace('-', '_', $template);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cache.default'),
      $container->get('lock'),
      $container->get('module_handler')
    );
  }

  /**
   * Returns path to selected theme.
   *
   * @return string
   *   Path relative to Drupal root.
   */
  public function themePath() {
    return drupal_get_path('theme', $this->theme);
  }

  /**
   * Returns the list of template files.
   */
  public function templateList() {
    $list = array_filter($this->registry->get(), function($info) {
      return isset($info['template']);
    });
    // Allow modules to alter the list
    \Drupal::moduleHandler()->alter('editable_template_list', $list);
    ksort($list);
    return $list;
  }

  /**
   * Returns list of overridden templates by the front-end theme.
   */
  public function overriddenTemplateList() {
    $list = array_filter($this->templateList(), function($info) {
      // The system will return templates that have preprocess functions
      // implemented by the theme so we need to remove them from the list
      // since they aren't really overridden.
      $theme_path = $this->themePath();
      return $info['theme path'] == $theme_path && (isset($info['path']) && stripos($info['path'], $theme_path) === 0);
    });
    return $list;
  }

  /**
   * See if provided template is allowed.
   *
   * @param string $template
   *   Template name.
   *
   * @return bool
   *   TRUE if template is allowed, FALSE otherwise.
   */
  public function templateIsAllowed($template) {
    $list = $this->templateList();
    $list[$template] = array();
    \Drupal::moduleHandler()->alter('editable_template_list', $list);
    // If no module removed the template the template is allowed
    return isset($list[$template]);
  }

  /**
   * Returns information if the provided template is overridden by the theme.
   *
   * @param string $template
   *   The template name.
   *
   * @return bool
   *   Returns TRUE if the template is overridden, FALSE otherwise.
   */
  public function templateIsOverridden($template) {
    $overridden = $this->overriddenTemplateList();
    return isset($overridden[$template]);
  }

  /**
   * Returns the template information.
   *
   * @param string $template
   *   The template name.
   *
   * @return array
   *   Returns the template information array. Empty array is returned
   *   when template was not found.
   */
  public function templateInfo($template) {
    $templates = $this->templateList();
    if (isset($templates[$template])) {
      return $templates[$template];
    } else {
      $base_hook = $this->registry->getBaseHook($template);
      return $base_hook ? $template[$base_hook] : array();
    }
  }

  /**
   * Returns the source path of the template file.
   *
   * @param string $template
   *   Template name.
   *
   * @return string
   *   Path to the source template file relative to Drupal root.
   */
  public function getTemplateSourcePath($template) {
    $info = $this->templateInfo($template);
    return $info['template'] . '.html.twig';
  }

  /**
   * Returns the path of the template in the theme.
   * If the template does not exist(is not overridden yet)
   * the 'templates' directory within the theme directory will
   * be used as destination for the new template. Otherwise
   * 'path' will be used since themes don't have to explicitly put
   * their templates into the 'templates'directory.
   *
   * @param string $template
   *   Template name.
   *
   * @return string
   *   The path to the template file within the theme directory
   *   relative to Drupal root.
   */
  public function getTemplateThemePath($template) {
    $info = $this->templateInfo($template);
    if (isset($info['path']) && stripos($info['path'], $this->themePath()) === 0) {
      return $info['path'] . '/' . str_replace('_', '-', $template) . '.html.twig';
    } else{
      return $this->themePath() . '/templates/' . str_replace('_', '-', $template) . '.html.twig';
    }
  }

  /**
   * See if provided path is allowed for writing/overriding
   * a template file.
   *
   * @param string $path
   *   Path to the template relative to Drupal root.
   *
   * @return bool
   *   TRUE if template can be created/overridden, FALSE otherwise.
   */
  public function pathIsAllowed($path) {
    // Access is allowed only to theme's directory AND this
    // always has to be located within the 'sites' directory.
    return stripos($path, $this->themePath()) === 0 && stripos($path, 'sites/') === 0;
  }

  /**
   * Returns content of requested template.
   * If the template is not implemented by the theme
   * the content of the original template will be returned.
   *
   * @param string $template
   *   Template name.
   * @return string|false
   *   Returns the code of the template or FALSE if template could not be loaded.
   */
  public function getTemplateCode($template) {
    $info = $this->templateInfo($template);
    if (empty($info)) {
      return FALSE;
    }
    $path = isset($info['path']) ? $info['path'] . '/' . $template : $info['template'];
    $path .= '.html.twig';
    return @file_get_contents('.' . base_path() . '/' . $path);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'theme_template_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state) {
    $templates = $this->templateList();
    $overridden = $this->overriddenTemplateList();

    if ($this->template) {
      $form['#title'] = $this->t('Template: @template', array('@template' => str_replace('_', '-', $this->template)));
    } else {
      $form['#title'] = $this->t('Create new template');
    }

    $form['left'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'template-edit-left'
      )
    );

    $form['left']['edit'] = array(
      '#type' => 'textarea',
      '#rows' => 35,
      '#default_value' => $this->template ? $this->getTemplateCode($this->template) : NULL,
      '#required' => TRUE
    );

    $form['left']['name_wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => $this->t('Template name'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE
    );
    $form['left']['name_wrapper']['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Template name'),
      '#required' => !$this->template,
      '#field_prefix' => $this->template ? String::checkPlain(str_replace('_', '-', $this->template)) . '--' : NULL
    );

    $form['left']['actions'] = array(
      '#type' => 'actions',
      'save' => array(
        '#type' => 'submit',
        '#name' => 'save',
        '#value' => $this->t('Save')
      ),
      'delete' => array(
        '#type' => 'submit',
        '#name' => 'delete',
        '#value' => $this->t('Delete'),
        '#access' => $this->template && $this->templateIsOverridden($this->template)
      )
    );

    $form['right'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'template-edit-right'
      ),
      'templates' => array(
        '#theme' => 'item_list',
        '#items' => array()
      )
    );
    foreach ($overridden AS $template => $info) {
      $form['right']['templates']['#items'][$template] = array(
        '#type' => 'link',
        '#title' => str_replace('_', '-', $template),
        '#route_name' => 'mymodule.settings.theme.template',
        '#options' => array(
          'query' => array(
            'template' => str_replace('_', '-', $template)
          )
        ),
        '#attributes' => array(
          'class' => array('overridden')
        )
      );
    }
    foreach ($templates AS $template => $info) {
      if (isset($form['right']['templates']['#items'][$template])) {
        continue;
      }
      $form['right']['templates']['#items'][$template] = array(
        '#type' => 'link',
        '#title' => str_replace('_', '-', $template),
        '#route_name' => 'mymodule.settings.theme.template',
        '#options' => array(
          'query' => array(
            'template' => str_replace('_', '-', $template)
          )
        )
      );
    }

    if ($this->template && isset($form['right']['templates']['#items'][$this->template])) {
      $form['right']['templates']['#items'][$this->template]['#attributes']['class'][] = 'active';
    }

    $form['#attached'] = array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.themetemplateform.css.less'
      ),
      'library' => array(
        'mymodule/codemirror.twig'
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.themetemplateform.js'
      )
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
    // If there is no template, the 'name' is required so we'll always end up with a value
    // for the name.
    $template = $this->template ? $this->template : '';
    if ((string) $form_state['values']['name'] !== '') {
      $template = (string) $template === '' ? $form_state['values']['name'] : $template . '__' . $form_state['values']['name'];
    }
    $template = str_replace('-', '_', $template);
    if (!$this->templateIsAllowed($template)) {
      $this->setFormError('name', $form_state, $this->t("Template name is not allowed."));
    } elseif (!$this->pathIsAllowed($this->getTemplateThemePath($template))) {
      $this->setFormError('name', $form_state, $this->t("Template cannot be changed."));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
    // If there is no template, the 'name' is required so we'll always end up with a value
    // for the name.
    $template = $this->template ? $this->template : '';
    if ((string) $form_state['values']['name'] !== '') {
      $template = (string) $template === '' ? $form_state['values']['name'] : $template . '__' . $form_state['values']['name'];
    }
    $template = str_replace('-', '_', $template);

    $tplpath = $this->getTemplateThemePath($template);

    switch ($form_state['triggering_element']['#name']) {
      case 'save':
        $write = @file_put_contents('.' . base_path() . $tplpath, $form_state['values']['edit']);
        if ($write === FALSE) {
          $this->setFormError('edit', $form_state, $this->t("Couldn't write data into file. Please try again or contact help desk."));
        } else {
          $form_state['redirect_route'] = array(
            'route_name' => 'mymodule.settings.theme.template',
            'options' => array(
              'query' => array(
                'template' => str_replace('_', '-', $template)
              )
            )
          );
          mymodule_success_message();
        }
        break;

      case 'delete':
        $delete = @unlink('.' . base_path() . $tplpath);
        if ($delete) {
          $form_state['redirect_route'] = array(
            'route_name' => 'mymodule.settings.theme.template'
          );
          mymodule_success_message();
        } else {
          $this->setFormError('edit', $form_state, $this->t("Couldn't delete template. File does not exist or is not accessible."));
        }
        break;
    }

    // Always rebuild cache
    Cache::invalidateTags(array('theme_registry' => TRUE));
  }

}


How to provide option to select geographic part for content I'm working on Drupal6 travel website and stuck with how to provide option to users to select the right geographic part of the world that they are going to write story about that place.

Should I provide AJAX drop down for example:
1 - Countries  (So when user select country)
 then
2 - Cities/States (Related to the selected country)

If there is something else for that ?

Any help would be appreciated :)

Zafar

Try the Location module. It will help  you to attach location info with nodes. More details from the module's project page:

  The Location module allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content. The Location module allows admins to collect addresses, geocode them (translate addresses to lattitude/longitude), and associate locations with Drupal nodes and users. Location data is automatically used to generate GeoRSS within your existing RSS feeds.


contextual filter for a block view with relationship I defined two content types : Book, Quote. A quote has a Book field, an entity reference to the book it is extracted from.

I want to build a block view to be displayed on each Book node page : all the quotes extracted from that book. In other words, all the quotes whose Book field value matches the NID of the current Book node.

So I defined

• a relationship field_book : Content (Content using field_property_book) ;

• a contextual filter : (field_book : Content) Content : Book set

to use Relationship = field_book : Content
When the filter value is NOT available :
Provide a default value = Content ID from the URL
(I also tried Raw value from URL + element number 2 : node/NID)

The view block displays no results. Obviously, I missed something about configuring a contextual filter for a block view ! Any ideas ? Help to a newbie with relationship greatly appreciated :-) Thanks.

I figured it out: the contextual filter should NOT use the relationship, as the Book field is in the Quote content type!

Finally, this worked: contextual filter (field_book : Content) Content : Book set

• Relationship = Do not use any relationship

• When the filter value is NOT available : Provide a default value = Content ID from the URL


how to make $page['content'] stop replacing HTML In my page (basic page content type) I have the following code in the body field

Heading

In my custom themes page.tpl.php I have

<?php print render($page['content']); ?>

However the rendered content replaces the h3 with a p and stripes my class for some reason and I need it to render the code that I saved.

header

However, if I use the following then it will print correctly:

<?php print field_get_items('node', $node, 'body')[0]['value']; ?>

If I use that then when I navigate to any of the default pages, mainly the admin login I get an error as $node is not defined. I added a conditional to check that $node was defined to prevent the error. After that the error wasn't displayed but since $node was supposed to contain the content, no content is displayed.

What am I doing wrong here? I just need my page to print out the body without deciding it should edit my code for me and I don't understand why $page['content'] is butchering my code.

Try going to admin/config/content/formats/html where 'html' is your WYSIWYG profile and check your filter processing order.

Mine:

Insert view filter
Convert Media tags to markup
CKEditor Link Filter
Convert URLs into links
Correct faulty and chopped off HTML
Limit allowed HTML tags

If I put 'Limit allowed HTML tags' at the top I get similar issues to what you are describing.

EDIT: The order did not actually cause the issue for me. I had just forgotten to add <h3> to the allowed list.


Howto drag & drop field images in editor Is there any possibility/ module to multiupload e.g. 3 three images and drag/insert them into the text field (Body) to the position I want the Images?
After this it should open colorbox gallery when I click on this images in the content.

I painted my problem:

http://i.stack.imgur.com/wVWrK.jpg

regards,
l

Insert is a utility that makes inserting images and links to
  files into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

2) Vimeo Screencast Colorbox for Drupal 7, part 2: Inline images with the Insert module


How to upgrade module table scheme for entity I've written a module that uses entities functionality. It has the following table scheme in .install file:

$schema['transaction'] = array(
    //fields
    'fields' => array(
        'id' => array(
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE),
        'name' => array(
            'type' => 'varchar',
            'length' => 50,
            'not null' => TRUE,
            ),
        'random_id' => array(
            'type' => 'varchar',
            'length' => 11,
            'not null' => TRUE,
            ),
        ),
    //additional properties
    'primary key' => array('id'),
    'unique keys' => array(
        'random_id' => array('random_id'),
        ),
    );

Entity description:

function transaction_entity_info() {
  //song entity
  $entity_info['transaction'] = array(
    'label' => t('Transaction'),
    'label callback' => 'transaction_label_callback',
    'base table' => 'transaction',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'id',
    ),
    'uri callback' => 'transaction_class_uri',
    'static cache' => TRUE,
    'admin ui' => array(
      'path' => 'admin/content/transaction',
      'controller class' => 'transactionUIController',
      'file' => 'includes/transaction.admin.inc',
    ),
    'module' => 'transaction',
    'access callback' => 'transaction_access_callback',
    'bundles' => array(
      'transaction' => array(
        'label' => 'Transaction',
        'admin' => array(
          'path' => 'admin/structure/transaction/manage',
          'access arguments' => array('administer transaction'),
        ),
      ),
    ),
    'entity class' => 'Transaction',
    'controller class' => 'transactionController',
    'views controller class' => 'EntityDefaultViewsController',
  );

  return $entity_info;
}

Now I need to add a new property into the table:

    'output' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),

I can use fields, and add it through the admin panel, but I want to learn, how to upgrade the tables directly.

How can tell Drupal to reload the table scheme for this module, add attribute into the table and use it when loading the entity?

@Clive is correct (in the comments). You'll just want to add the new definition to the schema hook and then create an update script in the .install file (hook_update_N) to add in that definition for sites/installations that have already created your new entity.


Get page title in webform I have a webform block on a page and i am looking for a way to get the webpage title in one of my fields. I have been looking for a while now and have not found a solution to my issue. One of the things that i found was using [current-page:title] but i cant get it to work i keep getting [current-page:title] to return in the field.

I found it off of this post: https://drupal.org/node/1782042, but i am afriad that i am using it the wrong way from what they explain and i may not understand what they are doing.

I have tried:

[current-page:title] and got [current-page:title] to return

%get[current-page:title] and got %get[current-page:title] to return

Does anyone know where i am going wrong or possibly have a solution to returning the title of the page in the webform field? I am pretty new to drupal development and any help would be much appreciated. Thank you!

---EDIT---

The reason why %title is not an option is because it will only grab the title of the block. I need the current title of the page that the block is on. Any ideas?

I was able to do this by upgrading to the webform 4.0 beta version. and used [node:title].