Avoid control-B is "eaten" I am a heavy EMACS user. On the Mac I get EMACS keybindings in most text fields, and on most websites. However, if I am on a drupal website editing an HTML field, control-b toggles bold. Command-B should toggle bold; control-b should move me back a character.

Is it possible to fix this, on either my client or on the Drupal server?

This has to do with the CKeditor's javascript library rather than drupal. There are several sites and questions around on how to do this, for example this. I haven't tried this, but my guess is that you need to modify the config.js file that lives in your /sites/all/library/ckeditor folder of your drupal installation.


Create taxonomy terms on the fly As far as I know, the way to create a taxonomy term is having to go into the taxonomy module and creating on there, and THEN assigning the term to the node.
Is there a way to create taxonomy terms on the fly? When the node is created, if the taxonomy term doesn't exist, it should be created too.

Use the Hierarchical Select module:

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!

Another way is selecting Autocomplete term widget (tagging) as field widget, when creating your term reference field

As another option, there is the Simple hierarchical select module.


How can I point to a site in a not common directory path? Normally when adding a new Drupal site I just put the sites root folder in /var/www/ and then edit the hosts file for that address and then edit the httpd.conf file to point to that site.

The situation here is the Drupal site I am working on came from a git repo where other people work on it as well. The site came like this - /sitename/web/sites/default so when I put that in my /var/www directory it isn't the same as a usual setup which is - /sitename/sites/default, multipleSite1, multipleSite2, ...

So the /web directory is throwing things off I think. It messes with the simple way I point to a site with http.d conf and the way Drupal looks inside that directory for the settings.php file.

Simple example of httpd.conf that normally works fine

<VirtualHost *:80>
     DocumentRoot /var/www/testsite
     ServerName testsite
</VirtualHost>

Any ideas? I'm sure it's a real simple solution.

-apache2 on ubuntu10.04

If I have an unusual directory structure I tend to use symlinks to get the folders into the correct place on the system.

If your site is running a standard drupal install you could install that to /var/www as normal

and create a link to your directory

ls -s /path/to/my/default/dir /var/www/default


Skip user edit page on first login using fboauth I am using the latest dev version on FBOAuth module on my site. I am using Popup for facebook login.

When the user logs in for the first time using facebook currently the user is being redirected to the account edit page. Is there a way I can skip this test, so that user will be back to the page where he came from. Later on he can go to account edit page and set the password if he wants to. Else he continue using the facebook login only.

Once the account is already connected, I am not facing this issue as the user is rightly directed to the page he came from. The issue is only with the first login using facebook.

Please let me know if there is some setting that I can enable.

You can redirect the page using rules modules and drupal_goto function


drupal_queues for drupal 6 So this all starts when I hit my php memory limit, I know I can increase my php memory limit... but in order to get the process that I needed running I had to up my limit to 1026M... and I dont think that this is the right way to go.

My process needs to run using cron, so I first looked to batch processing... its very usefull and works well, except when implemented with cron.

I know see that the right path is to use the d7 backport of drupal_queues.

I would put up some code, but what I am really trying to understand is the logic behind setting up and processing a queue using drupal_queues and cron.

So far this is what I got:

I set up hook_queue_info:

function mymodule_cron_queue_info() {
  $queue['mymodule_queue'] = array(
      'worker callback' => '_mymodule_queue_worker',
      );
  return $queue;
}

I setup hook_queue_worker($item)

function _mymodule_queue_worker($item) {
  $acc_id = $item['acc_id'];
  //Collect list of relevant campaign ID's
  $campaignNIDs = mymodule_get_campaignNIDs($acc_id);
  dpm($campaignNIDs);
  foreach($campaignNIDs as $key => $value) {
       $CampaignNID = $value;
       mymodule_collect_contact_actions($acc_id, $CampaignNID);
  }
}

And then I worked in the hook_cron

function mymodule_cron(){
  //Adding drupal_queue into the cron
  $items = mymodule_get_all_accounts();
  //This is the list of items that we need to itterate through
  //This will be the different ESP accounts
  $queue = drupal_queue_get('mymodule_queue'); //grab the queue
  $queue->createQueue(); //initiate the queue
  foreach ($items as $item) {
    $queue->createItem($item); //each item passed as param to worker
  }

  drupal_queue_cron_run();

So far this works and allows me to call each account separately in the queue. but now I have processes(functions) that need to be run per account. Ho would I add these processes as a "Sub-queue" to the queue that is currently being processed.

Do I need to do this or is what I have so far satisfactory?

Any light on this subject would be really appreciated as the documentation on this subject is somewhat lacking

There's no concept of a "sub-queue", it's just queues, items in the queue, and workers of a queue (on items). Without knowing more about your use case I'd say you should may want to have a queue per account. Or create a queue item containing the account its for and working that way. So, you can either have many queues with some items in each or one queue with a whole bunch of items.


How to create a hook? How can I create my own hook (similar to the ones Drupal core creates) for other Drupal modules to utilize?

You don't actually create hooks. You use helper functions such as module_invoke_all(), module_invoke() or drupal_alter() to invoke all functions matching the expected name pattern. The invoked functions are usually found with  module_implements().

Even if it is not needed for the hooks to work, the best practice is to document them in MODULE.api.php by creating empty stubs hook_NAME functions with documentation comments.


Created a sitemap using the modules views and views data I just created a sitemap using the modules views and views data export. How do I add

tag in the header.

thank you

You'll need to edit the views-data-export-xml-header.tpl.php that corresponds to the view your wanting to edit. To find this out, click on Advanced, Theme, and then Information. You're looking for a line like this:

  Alternative style: views-data-export-xml-header.tpl.php, views-data-export-xml-header--test.tpl.php, views-data-export-xml-header--views-data-export.tpl.php, views-data-export-xml-header--test--views-data-export.tpl.php, views-data-export-xml-header--default.tpl.php, views-data-export-xml-header--default.tpl.php, views-data-export-xml-header--views-data-export-1.tpl.php, views-data-export-xml-header--test--views-data-export-1.tpl.php

Pick a filename and make the changes. Note that if you're looking to wrap the results in additional tags, you'll need to override both the header and the footer files.

You'd change:

// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>

To also include any other information:

// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>
<header-data>
</header-data>


How do I create hierarchical taxonomy terms on import nodes? I use drupal 7 and the feeds module.

I have an excel file that contain 10 fields,So I want to import these 10 fields to specified content type as node and  for 3 fields of those create hierarchical taxonomy terms on importing file.
For example My excel file have 10 columns.

  column 1 (cars name)

  BMW
  Chery
  MVM

  column 2 (cars model)

  BMW 110
  Chery tigo 5
  MVM 110s

  column 3 (color)

  red
  black
  silver

  column 4

  ...
  ... . . . .

I want to import this file and after importing have 3 hierarchically taxonomy like following that assigned to nodes of content type.
Taxonomy terms is not added by me to content type yet and I want to create taxonomys and terms automatically and assign automatically to nodes.

I have created 3 taxonomy vocabulary in my drupal site (but not added any terms to those):
1- Car name (taxonomy vocabulary 1)
2- Car model (taxonomy vocabulary 2)
3- Car color (taxonomy vocabulary 3)

I want to have taxonomy terms such as:
-car name :
  -BMV
       - BMV 110
           - red
  - Chery
       - tgo5
          - black

Please Help me for importing some fields of my file as taxonomy terms and sub terms .

I Can't type english verywell.sorry
thank you

First make 3 taxonomy feeds importers for each of the tree taxonomy vocabularies separately

Import the terms from the same source file you got - you need only to specify Term Name and matching the right columm under Mapping for "Taxonomy term processor"

In case you want to import taxonomy with the hierarchy, use Taxonomy CSV import/export to put the taxonomy terms.
Sample import file with terms&hierarchy should look like this:

BMW;BMW 5;

BMW;BMW 7;

Audi;R8;

Audi;A1;

After you run these  imports, make the final node importer.
Change the settings to node processor. Remember under Mapping for Node processor when you map taxonomy terms to have "Search taxonomy terms by: Term name" checked on these three columns


Filter the products by selecting the checkbox I am developing an e commerce website. I want to display the product catalog on the left sidebar as check-boxes. When the user will select the products, the page should get loaded with those products. I am new to drupal. I know that I will have to use Taxonomy. Please let me know what else i have to use to achieve this? And how all these are linked?

Thanks in advance!

If what you are looking is filtering and not just displaying the products according to their taxonomy terms, then maybe you are looking for the facet api module with apachesolr


Text field inside  tags falls below it I've created a custom twig template in which I'm placing a text field inside a  tag like so:

{{ content.field_sample_text }}

It renders the content of that field just fine but when I inspect it, it seems to create a new div below the  tag and places its contents in that div like so:

  Content of the field

There's an extra p tag at the end as well which is also confusing. How can I ensure that my text field renders inside the original p tag as intended so that I can style it properly?

If you are using Stable like theme you can see that the field is wrapped around a div tag.
You can rewrite field.html.twig with your theme suggestions and edit the markup.


How to query all content type and add as checkbox for custom form? Need help on how to create a custom form that is only available for admins that will query all content types and display the options as a checkbox.

The goal is to only add certain libraries to particular content types selectively through an admin form. How would i query all content types and display them as checkboxes?

What we tried:

mymodule.module

function mymodue_preprocess_node(&$variables) {
  $node = $variables['node'];
  $config = \Drupal::config('mymodule.settings');
  $enabled_content_types = !empty($config->get('enabled_content_types')) ? $config->get('enabled_content_types') : FALSE;

  // This is where we need help.
  if(in_array($enabled_content_type, $node->bundle()) {
    // perform some logic.
  }
}

mymoduleForm.php

<?php

namespace Drupal\mymodule\Form;

class mymoduleForm extends ConfigFormBase {
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'mymodule.settings',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $types = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->loadMultiple();

    foreach($types as $type) {
      $content_types[$type->id()] = $type->label();
    }

    // Need help setting this up so that the options are content types.
    $form['enabled_content_types'] = [
      '#type' => 'checkbox',
      '#title' => 'Enabled Content Types',
      '#description' => 'Run preprocess for all enabled content types only',
      '#options' => $content_types,
    ],
  }
}

This was inspired from @leymannx comments.

I changed the '#type' to checkboxes.

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
 $types = \Drupal::entityTypeManager()
   ->getStorage('node_type')
   ->loadMultiple();

 foreach($types as $type) {
   $content_types[$type->id()] = $type->label();
 }

 // Need help setting this up so that the options are content types.
 $form['enabled_content_types'] = [
   '#type' => 'checkboxes',
   '#title' => 'Enabled Content Types',
   '#description' => 'Run preprocess for all enabled content types only',
   '#options' => $content_types,
 ],
}


hook_field_prepare_view not called If I understand correctly, hook_field_prepare_view should be called each time, when some field value is displayed.
But when I visit some node page, that contains some fields, my hook_field_prepare_view is not called. I have simple hook implementation as follows:

function mymodule_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
watchdog('mymodule', 'field');
}

I have no record 'field' in log messages, so I think my function is not called. I flushed caches several times.
Could anybody help, where can be problem?

As documentation says:

  This hook is invoked before the field values are handed to formatters for display

It will not be called when content is served from cache - as values are not handed anywhere, it's just output taken from cache table (or other cache bin) and sent to display.


How can I prevent a form from being displayed in the privatemsg module? I am trying to remove the "Block a user" fieldset, username text and input field, and "Block user" button from the "Blocked users" page as shown below.

The code I'm trying to change is in the pm_block_user module:

/**
 * Formbuilder function to build a simple form to block users.
 */
function pm_block_user_list() {
  global $user;
  $form['new'] = array(
    '#type'   => 'fieldset',
    '#title'  => t('Block a user'),
  );
  $form['new']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#autocomplete_path' => 'messages/user/autocomplete',
    '#description'        => t('Separate multiple names with commas.'),
    '#required'          => TRUE,
  );
  $form['new']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Block user'),
    '#validate' => array('pm_block_user_block_validate'),
    '#submit' => array('pm_block_user_block_submit'),
  );

  $header = array(
    array(
      'data' => t('Username'),
      'field' => 'u.name',
      'sort'  => 'asc',
      ),
    array(
      'data' => t('Operations'),
      ),
  );

  $select = db_select('pm_block_user', 'pmb')->extend('PagerDefault')->extend('TableSort')
    ->fields('pmb', array('author'))
    ->condition('pmb.recipient', $user->uid)
    ->limit(20)
    ->orderByHeader($header);

  // Only show existing users, therefore join users.
  $select->innerJoin('users', 'u', 'u.uid = pmb.author');

  $rows = array();
  foreach ($select->execute() as $row) {
    $rows[] = array(
      theme('username', array('account' => user_load($row->author))),
      l(t('unblock'), 'messages/block/' . $row->author, array('query' => drupal_get_destination())),
    );
  }
  $form['#header'] = $header;
  $form['#rows'] = $rows;
  return $form;
}

Here is the code I tried in my template.php based on these instructions for removing unwanted elements from forms:

function MYMODULE_pm_block_user_list($form) {
  unset($form['new']['#title']);
  unset($form['new']['#type']);
  return drupal_render($form);
}

However, this code hides the "Username/Tom/Operations/unblock" section, not the "Block a user" section which I am trying to hide.

The following code does it for me:

function MYMODULE_form_pm_block_user_list_alter(&$form, &$form_state, $form_id) {
  unset($form['new']);
}

This should help if you didn't know about it.

hook_form_FORM_ID_alter();

Also there's the more generic hook_form_alter().


Add user note in CiviCRM on behalf membership page I have a CiviCRM contribution page form that is :

on behalf of an organisation (required)
used for becoming a member

I need to add the possibility for the member to add a comment on the subscription form.

I tried 2 ways that seems not to work because of current limitations :

adding a custom field for contribution in the profile - doesn't work because of https://issues.civicrm.org/jira/browse/CRM-15787
adding the note field in the profile - doesn't work because the note displayed in the receipt is not always the one added by the user.

I need a quick way to fix this while those bugs are resolved.
My guess is maybe to remove the note from the receipt to avoid problems but how could i do that ?

Any better way of doing this is welcome.
webform is excluded because i am using paypal with redirection for now.

I would do this by using a CiviCRM integrated webform (using the webform CiviCRM integration module) and the CiviCRM contribution page. Use the webform to collect some of the information, including your comments field, and then on submission of that form take the user to the contribution page where they can initiate the transaction. Its less than ideal, but it works.

Work is going on to enable payment processors like Paypal website payments standard to work with webform_civicrm, but it's not ready yet, so I use this approach whilst awaiting that feature to be launched.


changed theme -> Logged out -> No log in field shown :( I cant find the log-in or registration fields on my wellcome page after i changed my theme and loged out myself.

How can i make the log in field visible again?

thank you for help.

You can go to the following path:
http://www.yoursite.com/?q=user/login


How do I do a regex query in reverse in entity query? I have a config entity with a row of regex strings, and I want to query which one of them matches a provided string; this stackoverflow question (https://stackoverflow.com/questions/12044628/searching-mysql-database-by-a-regex-match-in-reverse) describes how this could be done in mysql. What's the best way to do this using entity query?

Okay, is seems like this is in fact impossible to do right now with config entities.

If you look at \Drupal\Core\Config\Entity\Query\Condition, and into the function match, it shows what operators are available for config entity queries. REGEXP isn't even an option. Nor is there anyway to query a value against a field, instead of a field against a value.

The only way to really do this seems to be to load all of the config entity records into memory, then do the comparison with php.


How to export (send) image from website to Instagram? I'm working on a social network website based on Drupal7, This social network is based on photos and users may upload photos and they are accessible in their profile. I need to equip the site to contact to the Instagram profile of users and they can send images from my website to their profile in Instagram. I checked the Instagram Block and Instagram Feeds and Drupalgram modules, but from I understand these modules only import images from Instagram, non of them export images to Instgram. How do I can send Images from my website to Instagram?

You can use module InstaPost for posting nodes to Instagram. Some details about it (from its project page):

  This module allows users to post nodes automatically to the online
  mobile photo-sharing, video-sharing, and social networking service
  Instagram.

Disclosure: I'm the maintainer of this module.


Show blocks based on parent URL context We are looking for a way to show banners on pages based on their URL parent. There are multiple banners in use, and each page should display a banner based on its parent page. We want to build this into the theme, if at all possible.

So, for the Programs section, the Programs banner should display. However, within Programs there are named Programs with their own banners, such as "Great Program" and "Program For Winners" which each have their own sub-pages. When on those sub-pages, we want only the banner for the specific program to show.

/programs - Show Programs banner (top-level parent)

/programs/all - Show Programs banner

/programs/great-program - Show Great Program banner (second-level parent)

/programs/great-program/about-great-program - Show Great Program banner

Note: I'm using D7, and probably using blocks, maybe Views. Open to all suggestions.

If you'd implement those banners via blocks, then you might be able to get it to work using the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the various URLs corresponding to each of those banners.

If you're not familiar with how to do that with Rules, then have a look at my answer to the question "How to make the permissions of a module more granular?" (and pay attention to the regex-expression included in the sample rule I included there).


How to add a menu under Webform Results? In Drupal 7, I know we can use Views to add sub menu or menu tab on "My Workbench". The form result I have in "mydomain.com/node/99/webform-results" contained Submissions, Analysis, Table, Download, and Clear sub-menus. How can I add another sub menu next to "Submission"? I have tried to use the same method from Workbench, but it does not seem to work.

My new sub-menu setting in Views

Type: page
path: /node/99/webform-results/details
menu: Menu Tab: Navigation

Try to select Default menu tab instead of Menu tab.


Database Abstraction Layer and 'LOAD DATA INFILE' Statements I realize that using the database abstraction layer comes with a few caveats such as not being able to run queries that are not available in one way or another across all versions of the databases supported by Drupal7. However, I need to load data from a CSV file into the database from a user uploaded CSV file via a form built with the form API. So in the hook_submit function, I am going to do just that. Obviously I can write my own MySQL dependent implementation, however, I was hoping there was an abstracted "Drupal way" to accomplish the same task. I have not been able to find any such method.

Typically here is how I would do this after sanitizing the data, as an example:

LOAD DATA INFILE 'components.csv'
INTO TABLE components
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(componentId,componentName,componentDescription,componentAverageCost);

However, obviously this is a MySQL dependent query and even further it is dependent upon MySQL version 5 and later if my memory serves me correctly.

Your question is a little vague. I assume this isn't for a Content Type you created or an Entity in D7 ?!

As you pointed out this is DBMS specific. The drupal db api basically adheres to an ANSI SQL '97 (i think) specification. So you can do basic queries, updates, etc using the Drupal API. When you start talking about DBMS specific stuff you're outta luck.

The drupal API sits atop the PHP PDO library. This is an abstraction on top of many DBMSs as well -- you can do anything dbms specific with a bare PDO_Connection object ... called a stored procedure, or do your nifty INFILE usage above.

So you'd probably have to make your custom MYMODULE_form_submit() and do your custom query there from the raw pdo db connection. You can call Database::getConnection() in Drupal 7 to get the default db connection directly. Here is similar concept in calling a MySQL stored procedure from D7 asked here before on stackexchange.

Lastly, this isn't really drupal api related because you not seeking to call node_save() with your CSV data ... node_save() lives in the universe of the drupal API and has a succesion of function calls around it in the Drupal-verse, you're clearing asking for MySQL-verse stuff :)


PHP code to check for required fiels I'm using the Rules module in my Drupal site to do the following:

when an existing user logs in
check if there are required fields of the user account that have no value yet
redirect to the user page and show a message

This is necessary, because we have added required fields to the user account. My problem is with the second step. I can add a check for every required field, but would like to use a more generic approach.

What I'm looking for is PHP code to check if the current logged in user has required fields that are empty.

I am a developer but in .NET and have no PHP knowledge, though I'm willing to learn and I'm confident I'll pick up quickly.

Here is how its done:

First create a new rule then,

**Events**
-User has logged in

**Condition**
-Data Value is empty

you have to enter the value u want to check, something like
site:current-user:field-skills
make sure to change field-skills to the field name you want to check.

**Actions**
-Show a message on the site
"enter the message you want"
-page redirect
"enter uri to redirect to"

here is an export of the rule:

{ "rules_check_required_fields" : {
"LABEL" : "Check required fields",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
  { "data_is_empty" : { "data" : [ "site:current-user:field-skills" ] } }
],
"DO" : [
  { "drupal_message" : { "message" : "Field skills is empty", "type" : "warning" } },
  { "redirect" : { "url" : "\u003Cfront\u003E" } }
]

}
}


Modify apache solr search sort options? Is there the ability through contrib module or hooks to modify how the apache solr sort block sorts queries?

Currently, it seems it supports these queries out of the box:

Relevancy
Title
Author
Date

What i would like to have is to remove Author, Add a field to sort title from a-z and z-a. Is that possible?

You can find all info with examples here: http://drupal.org/node/715276

<?php
function MYMODULE_apachesolr_query_prepare(DrupalSolrQueryInterface &$query, &$caller) {
  $query->addParam('fl', 'some_field_image');
  $query->addParam('fl', 'some_field_date');
  //Remove sorts
  $query->remove_available_sort('sort_label');
  $query->remove_available_sort('bundle');
  $query->remove_available_sort('sort_name');
  //Rename sorts
  $query->remove_available_sort('score');
  $query->set_available_sort('score', array('title' => t('Relevance'), 'default' => 'desc'));
  $query->remove_available_sort('ds_created');
  $query->set_available_sort('ds_created', array('title' => t('Latest'), 'default' => 'desc'));
 }
?>


Easiest way to add popup dialog with snippet of html/text using a wysiwyg editor? My client isn't too technical and cannot code, but she wants a popup dialog when the user clicks on a link to show a snippet of html or text.

What solutions are there for the end user to be able to add and edit text popups like this using only a wysiwyg editor without having to code in stuff?

Here is a recipe for that:

CKEditor Link: Used for linking to other content in your Drupal. In this case, I would create another Content-Type, e.g. Popup Snippet or sth similar. This is an optional component, depending on your exact requirements.
Colorbox Node: Used for presenting node content in a popup, stripped of the surrounding regions and other theme elements. It also provides an easy way to turn links into popups, by providing a 'magic' class, colorbox-node. This is the main component, and the main idea, allowing the user to 'popify' links by adding a class name to the link's properties in CKEditor.

Below are some screenshot of the result on a D7.

Linking to content

Setting the colorbox-node class

End-result

Good luck!


How to create a block of links shared by a user? I am using oembed to convert url to embedded content. I have enabled the oembed input filter in a text format. Now I want to create a block using views to only show the posts which have these links. How to do that?

Note: I want to use it on a custom form. Is there something which can detect embedded content in a view. By this I will be able to create a separate view/block containing the embedded content.

Just wanted to make sure you've tried this simple approach. Create a check-box field for the all posts (whatever content-type it is) you were referring to with options embedded or non-embedded and create a view with a filter to only display embedded content.

Edit: Have a checkbox for the content-type (responsible for posts) which asks anyone creating posts if they are using the oembed text filter, give a description to check "embedded content" if they are.
Then create a view and pull all the posts by setting the filter- "CheckboxName (isOneOf) Embedded content".


How do the $node modifications in hook_node_presave persist? I was looking at hook_node_presave() and I tested it out and it works as described. The thing I'm puzzled about is that it doesn't take the $node parameter by reference, nor does it return anything from the function, however when I modify $node in this hook, the changes get saved. I'm really confused. Can anyone shed some light and make sense of this? How do I implement something like this?

Objects are (mostly) passed by reference in PHP. The $node variable is a stdClass object so any changes you make will be reflected on the original object in memory.

You don't need to do anything special to implement this yourself, just accept an object as an argument to a function as usual and let PHP take care of the rest.


How to exclude forms from processing by Hide Submit module? According to module description this is possible.

However I didn't find how to do it and I did not able to exclude form by any way, e.g:

http://drupalcode.org/project/hide_submit.git/commit/8aab1ab

The 2.x branch introduced hook_hide_submit_alter() which can be implemented to exclude certain forms based on the current path:

function MYMODULE_hide_submit_alter($hide_submit_settings) {

  // IMPORTANT NOTE: given the way module_invoke_all and array_merge work you
  // should not modify and return the original array. Instead create a new one
  // and add only the keys you care about. If two modules implement this hook
  // and try to modify the same values then the default will be used instead.
  $altered_settings = array();

  // Disable the module for my special form page.
  if (arg(0) == 'my-special-form') {
    $altered_settings['hide_submit']['hide_submit_status'] = FALSE;
  }

  return $altered_settings;
}

There doesn't look to be a way to turn the functionality off for a specific form, just by path. Might be worth a feature request on the module issue queue if that's something you'd like to see.


Setting Simple Sitemap Values Programmatically not reflected in form I'm trying to set some Simple Sitemap settings programmatically. I'm using the following to set whether or not a specific node is indexed:

\Drupal::service('simple_sitemap.generator')->setEntityInstanceSettings('node', $node->get('nid')->value, ['index' => FALSE]);

This works fine and I was able to see the results reflected in my sitemap. However, this is only reflected in the "Simple Sitemap" form of that node if the value is set to TRUE. If FALSE neither radio button is selected.

This is confusing to others who are editing the site. How can I get this reflected in the form?

I figured this out, but in case anyone else runs into this. The documentation in the readme.md file shows the following format the settings:

setBundleSettings('node', 'page', ['index' => TRUE, 'priority' = 0.5])

Instead of using TRUE/FALSE I changed the index setting to 0/1 and this was successfully reflected in the form as expected.

\Drupal::service('simple_sitemap.generator')->setEntityInstanceSettings('node', $node->get('nid')->value, ['index' => 0]);


What is causing Unknown field error in EntityFieldQuery API? I am attempting to use the entity-field-query API to see if any node of referee content type has custom field that equals x. I've looked at dozens of code examples and references. (Included below)

If it is relevant I am executing this code as a custom PHP action in Drupal rules.

My problem is when the code is executed I get the below error:

EntityFieldQueryException: Unknown field: field_referee_id in EntityFieldQuery->addFieldCon
dition() (line 817 of /home/scienceorg/public_html/includes/entity.inc).

(The field does exist on the referee content type.)

My code:

<?php
error_reporting(E_ALL);

$query = new EntityFieldQuery();
    $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'referee')
    ->fieldCondition('field_referee_id', 'value', '1', '=');
    $result = $query->execute();
?>

Further information: If I remove the field condition line from the above code it works perfectly. So the problems seems to be around finding the field_referee_id.

Code references and examples

EntityFieldQuery condition

https://www.drupal.org/node/1343708

Alternative answer:
If you don't know what is causing the above problem I will accept alternative methods of achieving the same outcome as the correct answer.

The code above seems right only problem here might be the machine name of the field is not same as the one given in
->fieldCondition('field_referee_id', 'value', '1', '=');
or the field might be multivalued field, for multivalued field in place of '=' 'IN' should be used.


Create a page to edit all fields from a custom content type I have a custom content type that has a custom field called "stock."

I would like to have a single page that shows me all "stock" values in a list, and allows me to change the value. Is this possible?

Create a view filtered on your content type and include a "NODE: EDIT LINK" in the FIELDS along with all the rest.  You can then click on that to edit the node. Anything fancier requires digging into views tpls and custom node edit code.


How can I allow users to duplicate a select field while creating a page from a custom content type? I have one select field (filled with taxonomy terms) in a custom content type. I can't figure out how to allow users to duplicate that select field (select "apples" and then add the select field again -- 2 instances of it now -- and select "oranges") when creating a page with the custom content type.

EDIT: is there perhaps a module that would do this? I've looked at similar kinds of modules like Webform, but none of them seem to be quite what I'm looking for.

If you use CCk, you can just edit your field setting in it's global settings and select illimited value number :

And you get a button "Add another" :

here I just used a text field for the example but it can be a select or anything else


Exception handling in drupal : How one can deal with warnings in Drupal? How one can deal with warnings in Drupal? If the code is getting executed smoothly, then what's the purpose of these warnings? Is there any way to deal with drupal "warnings", "notices".

one example here is:
I have written hook_uninstall

function hook_uninstall(){
   if (field_info_field('hide_field')) {
        field_cache_clear();
        field_delete_instance('hide_field');
        field_delete_field('hide_field');
    }
}

and this code is throwing warning:

Warning: Illegal string offset 'field_name' in field_delete_instance() (line 772 of modules/field/field.crud.inc).

Warning: Illegal string offset 'entity_type' in field_delete_instance() (line 773 of modules/field/field.crud.inc).

Warning: Illegal string offset 'bundle' in field_delete_instance() (line 774 of /modules/field/field.crud.inc).

Warning: Illegal string offset 'field_name' in field_delete_instance() (line 781 of modules/field/field.crud.inc).

Warning: Illegal string offset 'field_name' in image_field_delete_instance() (line 480 of /modules/image/image.module).

and there is no halt in the execution of the code. I'm very much curious about how drupal deals with exceptions, warnings, notices.

What does these warnings mean?

And can we contribute our module to drupal community if warnings or notices exits in module?

Can anyone share their piece of knowledge here?

The purpose of warnings are to warn you that something is wrong with the code you've executed. They are provided by PHP, not by Drupal (though Drupal can trigger them if required). Notices are similar, but considered less urgent. Warning/notices are not fatal, so don't halt the scripts' execution.

The way to "deal with" them is to simply fix the code, which might mean fixing your code, reporting a bug to a core/contrib issue queue, digging through a request to make sure that the value of variables being passed around are what they're expected/required to be, or something else.

Some people might tell you just to disable warnings/notices so that they're not bothering you visually, but as in all walks of life, hiding a problem instead of fixing it is a bad idea.

There isn't a catch-all answer to fixing every possible type of warning. You need to debug the site, find out exactly what and where the problem is, and apply your skills as a developer to fix them.

I don't know what the policy is for contributing modules that containing warnings/notices. I would hope that they are, at least in an initial review, rejected if they cause such things, but that might not be a practical expectation.

Regarding how Drupal deals with them: the answer is that it doesn't, really. You can switch on and off the display of error messages through the admin UI, but Drupal can't, and doesn't, have any interest in fixing these errors, or helping you any further to narrow down what's causing them. It's just a PHP app at the end of the day.

Incidentally, Drupal does implement its own PHP error handler (_drupal_error_handler_real()), so that it can log errors and exceptions in the watchdog, and/or to the screen.


Why do I get "Page not found" with my code? I just created a new module but I can't manage to access it.

Here is the home.info.yml

name: Home
description: Ownzones Homepage
type: module
core: 8.x

Here is home.routing.yml

home.oztest:
  path: '/oztest'
  defaults:
    _content: '\Drupal\home\Controller\HomeController::oztest'
    _title: 'Ownzones'
  requirements:
    _permission: 'access content'

And here is the HomeController:

namespace Drupal\home\Controller;

use Drupal\Core\Controller\ControllerBase;

class HomeController extends ControllerBase {
  public function oztest() {
    $element = array(
      '#markup' => 'Hello, world',
    );

    return $element;
  }
}

I don't see what I'm doing wrong, and when I try to access /oztest I get a message saying The requested page could not be found.

_content is no longer used, wherever you found that is outdated. Use _controller instead.


Rules scheduler and views- how to show normal users the schedule? I am using Rules Scheduler and Flag to handle troublesome users by issuing a one-week ban.  I flag the user with a temporary ban flag, and then the user sees a special block that says "You have been temporarily banned for being a jerk."  I have a rule that automatically schedules the user to be unflagged one week later.
However, I want to show users how much time they have remaining.  My first thought was to create a block/content pane in Views, so I made a view of type Rules scheduler, but when I went to add the UID as a Contextual Filter, I realized that Rules scheduler views only provide these options:

Null
Component name

Is there some other way I can show the user how much time they have until an arbitrary Rules Scheduler action will be evaluated?
What I tried
Based on this question, I added a filter for user-provided identifier, set the value to a garbage value (punishme), and added views_pre_view() as follows:
function MYMODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'punishment_show_details') {
    if ($user->uid) {
      $newvalue = 'punish/' . $user->uid;
      $view->display[$view->current_display]->handler->options['filters']['rules_scheduler']['value'] = 'punish/' . $user->uid;
    }
  }
}

However, this doesn't work; for some reason, when I dpm() the view, the value for filters is empty.

Why not add a user profile field that stores the ban removal date? Then you could use the "Time ago" formatter with the "Time hence" setting and then just set or unset it using the rule (and it's associated de-ban rule). You can show that field using Views and/or on the user's profile page. Or panels. Or custom code... etc.


How often i should re-build and re-submit xml sitemap for news website? I have an website that get news from RSS Feeds. I build every day 2-3k articles and now i have almost 160k links.

So, how often i should re-submit the xml sitemap; (currently i do this job every hour)

Depending on your server configuration you can setup your site to run cron more often.

You can also use Rules module, To write a rule for resubmitting site map  which can be trigger after certain time or on new content published.

It is also important to mention that search engines takes time to index - no matter whether through external links, internal links or sitemaps.

So don't think submitting site map more often will help.


How to save the "user agent" in the Drupal logs? when going through the log files it would be really helpful to know if an error was caused by a real user or by a bot.

Is there a way to save the "user agent" string (browser name) to the drupal log?

Using hook_watchdog, you can manipulate all, or some of your log messages. You can find the user agent string in the super-global $_SERVER['HTTP_USER_AGENT']. This way you could for example prepend all "notices" with the user-agent, and all errors with both user-agent and remote IP.


Setting messages from classes in Drupal How do we set messages now in 8.x? Do we still use drupal_set_message? Not a fan of mixing procedural calls within classes if it can be avoided.

Prior to 8.5.x, drupal_set_message is the way.
For >=8.5.0-alpha1, there's a new messenger service, with a note (and example which I won't bother copying):

The procedural functions drupal_set_message() and drupal_get_messages() have been deprecated and replaced with a dedicated Messenger service.
You should now inject this service as a dependency for your own services and controllers:


Drupal commerce auto login during checkout process I have created a e-commerce site, in that when anonymous user purchase a product during checkout process it should automatically created a account and assign order to the user. For existing user it should it should log in and assign order to him. Is there any module to do this or else how can achieve this.

I have tried https://www.drupal.org/project/commerce_checkout_complete_registration it works fine for new user. When I enter existing user email site goes to Maintenance mode.

Commerce Checkout Login includes this functionality.

If you just want a rule action to automatically log a user in, then use simongeorge's wonderful sandbox. It provides a rule action that allows you to do just that.


Loop through all entities with rules I have a content type (called Issue dates with fields called field_issue_date (date type) and field_issue_type (term_reference)) and by using Rules module 7.x-2.9 I want to check if the taxonomy field has been set to "Double", If so I want to list and set the next Issue Dates content type to be unpublished e.g

"Magazine Issue Date 2017-04-07 (Double)"

"Magazine Issue Date 2017-04-14" this should now be set as unpublished

"Magazine Issue Date 2017-04-21" this should be/remain published

Note: If Rules isn't the way to go, what would be a better way to unpublish a piece of content

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_issue_type" } },
      { "list_contains" : { "list" : [ "node:field-issue-type" ], "item" : "4" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_issue_type] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_issue_type", which is the machine name of the term reference field I want to check for.
List contains item "node:field-issue-type" and with Taxonomy term identifier value "4" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_issue_type] just got created or updated." (with [node:field_issue_type] the actual term with term id = 4).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions. Especially because of your extra comment "field_issue_type is a multiple value" (only "List contains item" is the Rules Condition that will do the trick ...).

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Within the Rules Conditions, adapt the "term id" (= "4") to fit your case.
Replace the Rules Action by what you want to happen as per the "set the next Issue Dates content type to be unpublished" in your question, which should really be a different (followup?) question.

PS: This answer applies to D7.


ThemeNegotiator not working for admin pages I'm trying to use the ThemeNegotiator to change the theme of the add and edit pages of one content type. I've followed the following very extensive posts/blogs.

Don't use admin theme for adding editing specific content type

Dynamic theme switching in Drupal 8

Soft launching your new drupal theme

Choose your theme dynamically Drupal 8

I have a user that is allowed to see the Admin theme seven, but for one content type documenten I want him to see the front-end theme svds. I'm able to get this to work for front-end pages but not for admin pages. What I think is that the applies part doesn't match on the add and edit pages. So it doesn't know it's on a documenten content type. Does anyone has an idea on how to solve this?

Module structure:

theme_switcher
--src
----Theme
------SwitcherNegotiator.php
--theme_switcher.info.yml
--theme_switcher.services.yml

theme_switcher.info.yml:

name: Theme Switcher
type: module
description: 'Switch theme for specific Content Type'
package: SVDS
core: 8.x

theme_switcher.services.yml:

services:
    theme.negotiator.theme_switcher:
        class: Drupal\theme_switcher\Theme\SwitcherNegotiator
        tags:
          - { name: theme_negotiator, priority: -50 }

SwitcherNegotiator.php:

<?php
/**
 * @file
 * Contains \Drupal\theme_switcher\Theme\SwitcherNegotiator
 */

namespace Drupal\theme_switcher\Theme;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;

class SwitcherNegotiator implements ThemeNegotiatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function applies(RouteMatchInterface $route_match)
    {
        // Use this theme on a certain route.
        $node = $route_match->getParameter('node');
        if (!is_null($node) && $node instanceof \Drupal\node\Entity\Node) {
            return $node->getType() == 'documenten';
        }

        // apply default theme
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function determineActiveTheme(RouteMatchInterface $route_match)
    {
        // Here you return the actual theme name.
        return 'svds';
    }
}

The admin theme negotiator is tagged with a priority of -40:

user.services.yml

  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

So you have to use at least -39, since the first negotiator returning a theme name wins and on an admin page this core service will return the admin theme.


Undefined variable error in node.tpl.php I'm using the Basic theme, and I get the following error when I refresh my site.

  Notice: Undefined variable: unpublished in include() (line 18 of /Users/me/Projects/mysite/httdocs/sites/all/themes/mytheme/templates/node.tpl.php).

The line that is caused the notice is the following one.

    <?php if ($unpublished): ?>

<?php print t('Unpublished'); ?>

    <?php endif; ?>

<?php endif; ?>

I don't understand this error. How can I fix it?

Try if ($node->status == 0) instead of if ($unpublished).

This may be happening because the variable is not set correctly in a hook_preprocess_node() implementation of the theme; you may also want to check the template.php file in your theme for these hooks.


Flexslider - on touch I am using Flexslider module in drupal 7 .  when i checked my website on mobile.  i am not use slider by touch

Is there is any setting for flexslider.

Thanks

You need to enable touch for that. Follow this path for flexslider setting $base_url/admin/config/media/flexslider/list/default/edit.

You will see screen such as
You need to check Touch in Navigation and Control Settings & save.

Don't forget to clear cache :)


How can I avoid broken filenames in cached content? I'm using Feeds to import data from Site A to Site B. Feeds runs every 15 minutes to check for new content, via cron / job_scheduler. I have caching turned on, with minimum lifetime and expiration both set to 15 minutes, with the hope that content will be rebuilt for anonymous users every 15 minutes.

The problem I'm having is that if Feeds updates a node and brings over a new image (or the same image; Feeds renames the same image every time the parent node updates) then the image on the rendered node is broken, as the original image doesn't exist anymore. e.g. example.com/files/image.jpg is deleted and replaced with image_0.jpg, while the cached page still has image.jpg in its source. Is there a good way to combat this, outside of having Feeds replace the existing file?

You might attach a cache_clear_all() at the end of your import task.

So every time Feeds updates your content, your cache will be reset.

Your cache will be handled right when it's needed. It's not safe in my opinion to rely on "coincidence" between import time and cache lifetime.


creating and theming register form in drupal 7 There are many links in websites that talk about this question, but I'm really bewildered how to do it, I've tested many solutions but I failed.

this is my code to add register form into a page

<?php
    if(user_is_anonymous()) {
    $form = drupal_get_form('user_register_form');
    print drupal_render($form);
    }
?>

it is all I know of register form !
it prints all the fields of registered users. I also added other fields like mobile, phone and ... from admin/config/people/accounts/fields.

what is the most straightforward solution to theme the form? text fields and ... ?

You can try this one

To implement hook_form_alter() in a module and set the form's #theme property:

    function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
      $form['#theme'] = 'user_register';
    }

and add this code to template.php

    function mytheme_theme($existing, $type, $theme, $path){
      return array(
        'user_register' => array(
          'render element' => 'form',
          'template' => 'templates/user-register',
        ),
      );
    }

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

Also, create a user-register.tpl.php in

  sites/all/modules/YOUR_module/templates/user-register.tpl.php

to add the 'markup' for the desired output and

<?php echo $rendered; ?>

to print the form.

For more information, follow this https://www.drupal.org/node/1211520

Hope, it works.


Want to allow a form on another domain to submit registration to a drupal form I know this is probably a bad idea/imposible, but have to ask.  Is there a way to allow a form on domain "example.com" to submit to the user registration form on "example2.com/user/register".

I mean, it has to be possible, because if you don't turn on spam filters you'll get a bazillion fake accounts from automated bots. I'd play around with posting the values from your first site's form using drupal_http_request, something like:
drupal_http_request($second_site_url, array('method' => 'POST', 'data' => $querystring_from_form_values))


How to show a page create with the view module in the administrative overlay? I've created a view with the view module which is a kind of administative page and i'd like to show that page using the administrative overlay, how can i do that?

Showing a view in the overlay just requires you to implement hook_admin_paths_alter().

function mymodule_admin_paths_alter(&$paths) {
  // Treat all user pages as administrative.
  $paths['the path of your view'] = TRUE;
}

Keep in mind this:

In the path you can also use asterisks (e.g. node/*/edit), useful in the case the view is using contextual filters
If the overlay is not accessible from the user, the page will be shown using the administrative theme, which could also be the default theme used by Drupal, if the site doesn't set a the administrative theme to be another one


How do I modify menu links depending on context? I'm trying to create a menu for a department & group-based company such as:

Presentation (/<department>/<group>/presentation)
Projects (/<department>/<group>/projects)
Personnel (/<department>/<group>/personnel)

Instead of having one static menu per <department>/<group>, what should be a proper approach to create just one dynamic menu which automagically updates its links to <department>/<group>?

So finally Menu Token is the way to go. Once installed, created my menu entries and set them up using tokens this way:

Please notice the relative link token together with the one-level-up part before last part of path:  /[current-page:url:relative]/../presentation. This preserves the relative static path before the last dynamic part as in this case I wanted to make the dynamic menu relative to each <department>/<group> path. Also remember to check Use tokens and select Method for Node: Context for Node.

Hope it helps.


Proper way of removing/hiding unwanted elements? There are many times where in drupal I'm styling a theme and if I don't need some element I cannot remove in settings I just hide it with css(display:none, or similar).
Is it considered a bad practice to do this and should I always use hooks or some over methods?

It depends what you are hiding.

If it is something like a page or block title or labels or other semantic type markup, you should hide it using the element-invisible class, which effectively hides it but without using display: none. This way screen readers can still see the text, which helps give visually impaired users context for the subsequent content, which is required for accessibility reasons.

If you are hiding actual content, like fields, or whole blocks, or menus etc. you should not be doing it in the CSS. It is best to do it on the back end.

The time when this is most important is hiding for access control. Never use css to hide data or fields that a users should not be allowed to see. Because that data is still available to the user, it just isn't visible by default. So that would be a security issue.

For forms you can use hook_form_alter(), hook_form_BASE_FORM_ID_alter() or hook_form_FORM_ID_alter().

For other areas, there are many possibilities depending on what you are themeing and what you are intending to do. Some examples, are hook_node_view_alter() for node pages, hook_user_view_alter() for user pages, other alter hooks, template preprocessors, theme functions and template file overrides.

For more information on drupal hooks see http://api.drupal.org
For more information on overriding theme functions and template files see http://drupal.org/theme-guide/6-7


How to add a modal which then opens a ctools modal? I am trying to set up a modal that opens a ctools modal from inside it. IOW the user sees the first modal, clicks on a button inside that modal and it opens a second modal on top of the first modal. Then when the second modal's work is done, it closes and user can still see the first modal.

I understand that ctools is limited to one modal at a time according to this DO issue. My second modal is a ctools modal. I tried to set up a jQuery modal and a bootstrap modal as the first modal, but closing the second ctools modal always closes my first modal.

Any pointers as to where I can find a workable solution to this?

Any pointers as to where I can find a workable solution to this?

If you know jQuery and CSS you can create your own custom modal. Modal one has div id of modal-1 and for two modal-2.

use the z-index css property, and make sure modal 2 is higher than 1, so it displays on top:

#modal-2 { z-index: 10; }
#modal-1 { z-index: 5; }

Use CSS to center the div, so it appears in the middle of the page, like this. Probably better to use fixed position rather than absolute, up to you.

Then with jQuery use the .click() function

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings)

      $( "#some-show-button" ).click(function() {
        $('#modal-1').fadeIn();
      });

      $( "#some-x-button", "#some-submit-button").click(function() {
        $('#modal-1').fadeOut();
      });

      $("#some-other-show-button").click(function() {
        $('#modal-2').fadeIn();
      });

      $( "#some-other-x-button", "#some-other-submit-button").click(function() {
        $('#modal-2').fadeOut();
      });

    }
  };
}(jQuery));


How to make a block only appear for a certain content type? I have a content type and what I want to do is show a block on the right hand side only if the user is viewing that content type using a custom module. Any general pointers as to where I should start looking?

This can be done in a few ways.

If your content type always has a unique URL (such as /news) you can set the block to only show when on a page matching that URL.

Or this can be managed in a variety of ways using different plugins that allow for the manipulation of displaying content types and their corresponding views/blocks.

Are you currently using any plugins like that or have any themes installed?


Should I go for Drupal7 or Drupal8? I am currently developing my website. It is in initial stage. I got pretty good hand on Drupal7. But as Drupal8 is going to release in few days should I shift to drupal8 from now itself as my development is in very initial stage Or should I stick to Drupal7?

Drupal 8 is a better platform , it has a better structure , more features in core , it is based on symphony2 and so the module development is different from what you knew in drupal 7. template engine also is changed to twig so again you have to change your point of view about how used to theme before .

Another thing must be mentioned before making your decision is that there are too many module for drupal 7 and you can find a module for almost any job but cause drupal 8 is new , many modules are not still developed for this version.

All in all I should suggest you that it is a good idea to migrate to drupal 8 but if you have a deadline for your project this may not be a good decision to start it with drupal 8 ,cause it will take some times to be adopted.


Drop-down pager for search results? How do I go about adding a drop down to alter the amount of search results at search-results.tpl.php that will change pagination?

I would prefer not to use Views because I have completed a lot of styling and template changes to search-result.tpl.php.

Hi in Drupal 7 you can directly have the options in the views

if you are using drupal 6 you should use somthing like hook "hook_views_pre_build (&$view)"


Create a View with Previous Next and Return to Parent options ok so I've currently sorted this out using raw PHP and mySQL queries but it feels like a hack and I'd like to Drupalafy it if possible. not sure if it would be quicker or not, but would certainly be easier to manage in the long run.
I have a list of node thumbs on a front page, ordered into Tax based groups. Click any of these and you are taken to that nodes page and you can next/previous though all the other nodes in that Tax group. there is also a link to take you back out to the front page (of which there could be many, as this is based on a higher level tax term).
I'll try and show an example.
Tax top 1.
  tax sub 1
  tax sub 2
Tax top 2
  tax sub 3
  tax sub 4

nodes 1,2,3 are in Tax sub 1
nodes 7,8,9 are in Tax sub 2
nodes 4,5,6 are in Tax sub 3

Main page 1 shows nodes 1,2,3 under heading Tax Sub 1, and 7,8,9 under Tax Sub 2,
main page 2 shows nodes 4,5,6 only under heading Tax Sub 3.
Click though to a node say 5, and you will have a
Next take you to node 6
Previous to node 4
Home/back to Main page 2.

hope that makes senese. you can see it in action on this site.
www.martynazoltaszek.com
So my question is can I do this using I guess Views? I've tried but cannot elicit the control I want completely.
edit: the nodes can be in any sort order so I guess I require the nid to be carried though to the view of a single node, and from that work out what would be next previous.

These are rough suggestions, have you tried custom pagers and eventually views slideshow for the previous/next links ?

For the back link, you can call your views with an URL parameter and build a footer link using this parameter (somewhat do the "destination" parameter).


Character limit on body Summary field I am trying to make the summary field on the body field have a limit of 40 words.
I have searched on the net so far, and I haven't found any solution.

Do you have any idea on the best approach for this?
The website is live and already has content with summaries, so I can't use a new field to do this.
am working with drupal 7

The answers on this question might help you.

You override maxlength in a hook_form_alter().

function hook_form_[content-type]_node_form_alter(&$form, &$form_state, $form_id) {
    $form['summary']['#maxlength'] = 40;
}

The above is not tested but should get you started. You can inspect the $form object with dpm() if you have Devel installed to check the exact name and place in the $form array of the summary field.


Display two products as two radio buttons with a single Add to Cart Form I am having trouble deciding how to tackle this problem.  I have two products (indeed, one could be made as an attribute of another, which may help) which are basically two ticket options, only one of which can be purchased by a customer.  Therefore I would like to display them as two radio buttons with a single add to cart button (which I would then configure with Rules to send them straight to checkout).

Right now I have this:

Again, I would like to basically have two buttons, only one of which can be selected, with a single Add to Cart form.

Any ideas?

Drupal commerce was designed to do exactly this without going through lots of hoops, but it might be a bit tricky to get into.

Instead of making one an argument of another I'd create one product display with two different attached products, for which you can set an attribute field and a price. You can do so by having a node content type to act as a 'product display'. To do so you require inline_entity_form and commerce_product_reference (part of the commerce package).

On the product-type add a field the distinguish 'premium' product and make sure to hit the 'Enable this field to function as an attribute' checkbox.
Add a product reference field to a (new) content type you call 'product display' (or if you plan on selling more different kinds of products you can use a more specific name line 'event ticket' or something).
For the field widget choose 'inline entity form (multiple)'.
Create a node of the 'product'-type and add the two different products and their properties; for the 'premium' product make sure to change the price and the attibute field we created earlier.
Save the node.

If all went well you should end up with a selection box on the 'product display' node, allowing the users to select which version of the product they want to buy.

If you find this too vague, there is a detailed explanation (with pictures) on it here: Product Attributes & Variations. It does not use inline entity form so the 'attach products' involves a drop down on the images, whereas inline entity form will allow you to create and edit the entities directly on the node.


EU Cookie Compliance module not working got a problem with the EU Cookie Compliance module. I installed it and it only worked when you were logged in (my site uses SSL).  Then I realized I hadn't set the permissions so that the cookies message is displayed to Anonymous users.  Now the message doesn't appear to anyone, logged in or not.  I've made sure the cookie is deleted from the browser, but still no luck.  Any ideas please?

The site is http://idea.nottingham.ac.uk.

No message displayed for anyone since I added Display permissions for anonymous users. Before, it wasn't displaying message for 'guests', only logged in users.

Interestingly, it does work (for both guests and logged-in users) on my Bitnami development copy of the website where SSL is switched off.

I used something else in the end as I couldn't get the module to work, so used cookieassistant.com in the end. As for the speed, thanks for that, I think it's down to good hosting to be honest. – pixelshrink


Import Drupal Database, Excluding Database Connection Parameters Another developer and I have the same Drupal theme installed.  The other developer is the one doing the development work and I'm simply trying to import his updates into my theme so I have the latest and greatest and can see how the work is progressing.  I am able to IMPORT his EXPORTED database, however, his MySQL database connection parameters are different in that he's not using a password, and my MySQL database connection parameter INCLUDES a password.

The way I am importing his export, is simply by using PhpMyAdmin, I first DROP all the website's Tables, and then simply IMPORT his EXPORT.

QUESTION IS: Which tables should I NOT Drop, and when he does his EXPORT, which Tables should he NOT Export... so I receive everything I need to get all the updates into my database, but don't have a problem with database connectivity?

I've actually never heard of database settings being stored in the database. Are you sure you aren't updating your site's settings.php-file as well?

Do you have different database prefixes?

Could it be related to some stale cache?


How can I place the article date before the title? I'm using the Basic theme and want to show the article date before the title. The problem is, that {{ date }} is only available in node.html.twig, whereas the title is created in page-tite.html.twig.

How can I place the article date before the title?

You can do this by implementing template_preprocess_page_title() hook in your Theme (THEME_NAME.theme). Check example below:

/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function [THEME_NAME]_preprocess_page_title(&$variables) {
  // Check if page is node page, and is instance of Node.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && ($node instanceof \Drupal\node\NodeInterface)) {
    // Get created time of Node and convert to human readable, and append Node title.
    $variables['title'] = '' . date("d m Y", $node->created->getValue()[0]['value']) . " " . $node->getTitle();
  }
}

Similar question is answered by @Linus's here.


$form table displays no table data I just made a $form['table']. It shows enough rows (the count of the total rows in database) only it doesn't show the results. I tried using #value, #title, #markup but nothing works

Screenshot of result:

My code:

function push_notifications_stats_form($form, &$form_state) {
$form = array();
$id = $_GET['id'];

$query = db_query('SELECT * FROM push_notifications_messages WHERE msg_appID = :app_id', array(':app_id' => $id));
$qCount = db_query('SELECT * FROM push_notifications_messages WHERE msg_appID = :app_id', array(':app_id' => $id))->rowCount();

$form['table'] = array(
    '#theme' => 'table',
    '#header' => array(t('Message'), t('Device'), t('Date')),
    '#rows' => array(),
    );

foreach($query as $result) {
  for($i = 1; $i <= $qCount; $i++) {
    $form['table']["#rows"]["r$i"] = array(
        "'c1'" => array(
            '#type' => 'textfield',
            '#value' => t('hoi'),
          ),
        'c2' => array(
            '#type' => 'textfield',
            '#title' => t('device')
          ),
        'c3' => array(
            '#type' => 'textfield',
            '#title' => t('device'),
          ),
      );
  }
}

$form['id'] = array(
'#type' => 'item',
'#title' => 'Application ID',
'#description' => t('The application ID you are viewing: @appId', array('@appId' => $id)),
);

return $form;

}

When I check the $form with dsm it does show the results.. And also when I use my browsers element inspector it does show the values. Only it puts them inside the first  tag. while it should be between the  tags

<td #type="textfield" #value="hoi" #data="hoi"></td>

I think you are mis-using #header and #rows properties of the Form API and getting them confused for variables passed to the theme_table function that is being called with the form['#theme'] => 'table'.

This question is similar and might be what you're looking for: How to insert a theme table form inside an existing form?

Perhaps you want to use the tableselect element?


Programmatically change the available options in a views exposed filter I have an existing view in which I want to change the available options in a view exposed filter. I can't manipulate the form because the modifications are dependant on other views data, so I thought I could use a view hook:

function my_mdoule_views_pre_view($view, $display_id, $args) {
  // This doesn't work unfortunately
  if ($display_id === 'gallery_media_select_modal') {

    $filters = $view->display_handler->getOption('filters');

    $filters['bundle']['operator'] = 'IN';
    $filters['bundle']['value'] = ['image' => 'image'];

    $view->display_handler->overrideOption('filters', $filters);
  }

}

This setting is basically the same that you can do in the UI, but like I said I need to do it dynamically.

I can see that this is in fact set correctly (and still set in later view hooks) but it's never picked up by the code that is responsible for building the exposed select.

I've found many similar questions, but conclusively they've only been answered for Drupal 7, e.g. https://groups.drupal.org/node/82219

I think you are very nearly on the right track, and I don't think you necessarily need a hook. I was able to perform essentially the same task with the following code in a class method.

// Get reference to your view.
$storage = \Drupal::entityTypeManager()->getStorage('view');
$view = $storage->load($view_id);

// Be sure to get a specific display.
$view->getExecutable()->setDisplay($display_id);
$display = $view->getExecutable()->getDisplay();

// Retrieve filters. If the combine fields filter is present,
// edit it then assign back using `overrideOption`.
$options = $display->getOption('filters');
if (isset($options['combine'])) {
  $options['combine']['fields'][$field_name] = $field_name;
  $display->overrideOption('filters', $options);
}

// This is the critical missing step.
$view->save();

I hope this helps.


Setting role based access control Since we launched we have added many new job roles and wish to set all new wiki pages so everyone can access. At present we are having to manually tick each role.

Is this possible?

Tick "Authenticated User" and the rest will automatically become ticked


How to call up the argument passed to the View? I have a view that reads the argument from panel url.

How can I call up the passed argument inside the "no result case" with html code?

Thanks!

I don't think it's possible with HTML, but 'No result case' allows you to use PHP, so arg(x) should work, x being the zero based position of your argument in the URL.


How to automatically select the organic group audience when adding content? How can I setup a link on a group page to add content that automatically selects the group audience as the referred group?

For instance:

I'm a member of the group "Puppy Kittens" and I'm logged in to that group page (node/12) and I have links on that page to "Add Post". The link "Add Post" opens up and allows me to add a post for my group without me having to select my group.

OG group extras

  Extra functions, blocks, and views for Organic Groups 7.2. In
  particular, this module adds views and blocks needed by sites that are
  not using Panels.

This only works on OG 7.2 but not on OG 7.1. If you are using OG 7.1, you can use panels and add a create group content panel to the node page.


Allowing downpayment Is the a way to allow downpayment for customer-preoders.
I can create a content type that allows customers to place orders(pre-order) but I wish they could commit a certain fee, like 30% of the original price.
Is there a way to achieve this?

There are plenty of modules are available for managing inventory and orders. Like Ubercart, Commerce.

But according to your requirement it seems that you want a partial payment system.

The default modules available in drupal community will not be able to provide you such kind of feature.

My Suggestion is to create it completely using your custom module and manage the complete order and partial payment process system.

Hope this will help you.


My implementation of template_preprocess_block() isn't working My block has id=block-block-10, now i want to add a more link after the title.
This is my code in my theme's template.php.

function mytheme_preprocess_block(&$variables) {
  if($variables['block_id'] == 10){
    $variables['block']->subject='
test>
more';
  }
}

There is no more text on the block's title. What's wrong with my code?

The $variables['block_id'] variable is based on the number of blocks in a region (see template_preprocess_block(). If you want this for a specific block, despite what region it is in, you should be checking $variables['block']->delta == 10 instead.


Stopping 404 pages when adding get variable to the URL I have a Drupal 8 website with a URL like http://mywebsite.com/my-content-url/my-content-url. What I have done is adding a variable to the URL, making it like http://mywebsite.com/my-content-url/my-content-url/myvariable.

How do I get Drupal 8 to stop seeing /myvariable as a part of the URL and giving me a 404 error?

You need a menu callback that accepts the variable. For more info, take a look at the Drupal docs.

Another way to do this is to pass your variable as a query parameter like http://mywebsite.com/my-content-url/my-content-url?var=myvariable. You can then use code to parse that parameter from the URL. You can get those parameters by using something like \Drupal::request()->query->all();


Access nid in field template How do I access the nid of the current node in a field.html.twig template?

I found myself a solution for this. Maybe not the perfect way to go, but it worked very well for my needs:

in .theme-file:

function MYTHEME_preprocess_field(&$variables, $hook) {
   $variables['nodenid'] = \Drupal::routeMatch()->getRawParameter('node');
}

and in .twig:

{{ nodenid }}

of course you might want to filter the preprocess hook to only add this variable to a specific field.


How to programmatically add a field to a view depending on another field and reorder fields then I broke a site yesterday using views global php, even if it was working in the preview, so I'm a bit nervious about that php in database and I'm trying to implement the same thing with Views API.

Depending on the key value of a hidden field in the current display, I need to put a custom text. Something like (global php version) :

if( isset($data) && isset($data->field_field_statut_depart) ) {

  switch(  $data->field_field_statut_depart[0]['raw']['value'] ) {

    case 1:
      $text = 'ABC';
      break;
    case 2:
      $text = 'DEF';
      break;
    //and so on

  }
  print $text;
}

I'm trying to build it with hook_views_pre_view(&$view, &$display_id, &$args) but I can't find the required field_statut_depart value in  dpm($view).

Maybe it's not the right hook ?

EDIT : after applying solution described in the answers below (views_post_execute hook) and 12 hours running, I'm facing a strange behaviour : the changes made by  views_post_execute hook are not stable : after clearing caches, they are visible for a while but raw data (without my function applied) is displayed then ! I'm afraid it's still not the right place to do that. Any help is welcome.

You may want to try the views_post_execute hook.

Otherwise there is a reduced list of hooks used for views rendering at the bottom of the Views Hooks API page.

It is a little hidden but I have used it many times and you may find a solution to your issue there.


Views rewrite output including the wrapper divs? I have 3 fields in a view and I want to rewrite the output in a fourth field.
like this

[field1][field2][field3][field4]

But I want to have a wrapper div around each field like in the field settings.
The problem is I could do something like this:

[field1]

[field2]

[field3]

[field4]

But with this even if the field is empty the divs with the css classes will stay alive.
I dont want that. If the field is empty dont display it with the
.

If I just display the field, there are no wrappers at all.

I found the answer myself. I use the modul views_fieldsets.


Override Taxonomy Pages without entire page override I need to override Taxonomy page (page--taxonomy--term.tpl.php) and wondering if it's possible to just override the content section of the page instead of the whole page.

I don't want to print all other regions again as I will to update different page tpls if I update some other part of the page template.

Cheers

You can use Panels module to create custom layout.

Or :

You can override taxonomy-term.tpl.php in your theme directory as following :

taxonomy-term--[vocabulary-machine-name|tid].tpl.php

I would suggest panel rather than overriding template files.


Migrate into Multi-value Checkbox from CSV Update: Turns out typos suck. But added an answer to this as well, in case anyone ever stumbles upon this...

I'm running into a bit of an issue using Migrate API. I thought I had a fairly simple use-case, but am unable to actually find an example for this particular instance.

I have a CSV I'm importing, utilizing the migrate_source_csv module. My migration was working just fine, but now I need to add a field_dealer_type field. This field is a multivalue checkbox. In the CSV, it's represented in a single dealer_type column, separated by commas (I've also tried other delimiters with no success).

A couple example rows of my CSV would look like:

id,name,city,dealer_type
1,Sample Location,Cool City,"trucks,motorcycles"
2,Another Location,Second City,trucks

The CSV is well-formatted, wrapping the dealer_type column in quotes when necessary.

However, I'm not able to get these to import properly into my nodes. I've verified the values through the CSV are valid options in the field definition as well (trucks, motorcycles).

I've started with the explode plugin, as other examples use that as well, but I know I'm missing a follow-up processing. I've seen example using Taxonomy and entity_generate, but that doesn't fit my use-case. I also have the migrate_plus module installed, for clarity.

langcode: en
status: true
dependencies: {  }
id: dealers_csv
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: default
label: 'Import Dealers'
source:
  plugin: csv
  path: sites/default/files/dealer_locations.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: 'Unique Id'
    -
      name: 'Dealer Name'
    -
      city: City
    -
      dealer_type: 'Dealer Type'
process:
  title: name
  type:
    plugin: default_value
    default_value: dealer_location
  field_dealer_name: name
  field_dealer_city: city
  field_dealer_type:
    plugin: explode
    limit: 2
    delimeter: ','
    source: dealer_type
destination:
  plugin: 'entity:node'

Turns out typos can send you down a completely misguided rabbit hole!

Within the explode plugin, the property should be delimiter, not delimeter (incorrect spelling).

After that switch, things are working great.
Yay.


Implement Push Notification in my iOS App with a Drupal backend I building an iOS App whose content is being brought from a Drupal site. It is being built in ionic/AngularJS.

I intend to implement "Push Notification" functionality in my app that whatever notification a user sends through my Drupal site is received on my app.

There is a particular module Push Notification, made specifically for this and has integration with Services, but I can't seem to figure out how I'll show the Push Notification on my app when it's sent from my Drupal site. Probably some small example?

Any help would be highly appreciated.

Three module you need to require to accomplish notification one is rules second is services and push notification modules.

On cofiguration of push notifications you need to configure APNS certificate for IOS by put on private folder and set path to configuration.

By services module you need call register and deregister push token services.

By rule module you can set action of send push notification to particular token.


How to unzip or uncompress a file .epub on Drupal? I've created a content type that upload files .epub on database. Now for some reason (to use epub on a mobile app) I need to get the file .epub uncompressed.

It's like in my content type I upload a .zip file but when drupal store it it's stored unzipped.

Did someone knows a Drupal API function or a method that uncompress or unzip a .epub files?

Note that when I upload an .epub file or .jpg image or any other type of extensions, in the table file_managed I always get filemime : "application/octet-stream"? is it normal ?

PHP already has a built in class to process zip files. You can combine that with a hook_node_presave invocation in a custom module to process the field containing your ePub file and extract it to a directory in your file system.

/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  if(isset($node->field_MYFIELD[LANGUAGE_NONE][0]['fid'])) {
    $file = file_load($node->field_sss[LANGUAGE_NONE][0]['fid']);
    $file_path = drupal_realpath($file->uri);
    $file_name = pathinfo($file_path, PATHINFO_FILENAME);
    $zip = new ZipArchive;
    if ($zip->open($file_path)) {
      $zip->extractTo(drupal_realpath("public://MYMODULE_customdir/$file_name"));
      $zip->close();
    }
  }
}


How can I change a user's password? How can I change a user's password from the command line using Drush?

In Drush 9, the command is drush user:password USERNAME "SOMEPASSWORD"; its aliases are user-password and upwd.

In Drush 8 (and earlier) the command is drush user-password USERNAME --password="SOMEPASSWORD"; its alias is upwd.


Display node title in view comment type I have created a view (using views 2) with type = comment (displaying comments).
Now i can display comment author, comment post date fields, but i can't create a node title field which belongs to comment.

Tried using views customfield, but $data variable isn't allowed here, only $comment variable. Please throw me in a right directions, thanks.

Try setting up a new Relationship within the View.

Add a new relationship to "The node the comment is a reply to."
Check box that "requires this relationship"
You should now be able to add a new field for the node title


format_date not working as expected I'm using Drupal 7.38 and I'm trying to print the creation date of a node in 3 separate divs, to be able to format it appart, so I created the following on the node.tpl.php:

<?php print $date; ?>

<?php print format_date($node->created, 'custom' , 'M'); ?>

<?php print format_date($node->created, 'custom' , 't'); ?>

<?php print format_date($node->created, 'custom' , 'Y'); ?>

But, when I go to the result page I've got this:

MAR, 07/28/2015 - 16:20

JUL

31

2015

So, why is the day showing the incorrect date???

Thanks.

You should use d for the day of the month. Using t php displays the number of days for the given month. Reference: http://php.net/manual/en/function.date.php


SQLSTATE[HY000]: General error: 1366 I'm using Feed Importer to import data from a csv file, and I got this error

SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xA0 a TN...' for column 'message' at row 1

All values are in english characters, and I really don't know how to solve this problem

Help please. thanks

What is the origin of your CSV file? Are you sure that it is properly encoded using UTF-8? This error is coming from an issue with the database handler trying to process non-UTF8 characters (see: http://drupal.org/node/1140194).

The particular character it is having problems according to your error above is the "&nsbp;" character or 0xC2 and 0xA0, you'' want to convert your file to UTF-8 or alternatively if you have control over what ever is generating your export, strip it out using php following the advice here


Where are permissions stored in DB? I'm looking at the DB but can't find where the permissions are stored.

On the Admin page the permissions can be saved at /admin/user/permissions

But where this data is saved in the DB?

Permissions are stored in the permission table.

The table stores a comma-separated list of permissions that are enabled for each role, by role ID, which links back to the role table.

The users_roles table makes the final link between users and the roles assigned to them.


How can I combine a product attribute with a subset of another one in Drupal Commerce? Assume I have 2 product attributes (using the Drupal Commerce module):

Background color (white, black, green, blue, yellow).
Surface (glossy or matte).

And assume that surface "glossy" can be only selected in combination with background color "white" or "black".

How should I configure this conbination of attributes?

Required steps

Step 1

Create 2 taxonomies:

Background color, with terms white, black, green, blue, yellow
Surface, with terms glossy or matte.

Step 2

For each prod type, add field "Background color", which is a field "term referenace" (and refer to the Background color taxonomy).

Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).

Then add a similar term reference field "Surface".

Step 3

Use store / products / add product to add individual products, with a specific SKU, and for which you pick the right values for each of both taxonomies.

So for "Matte surface", you should create 5 individual products (one for each background color). But for "Glossy surface", you only create 2 individual products (1 with a white background color, and 1 with a black background color)

Video tutorials

For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13). Before doing so, you may want to first view these related videos:

Drupal Commerce - Pruduct Types (9:11).
Drupal Commerce - Pruduct Displays (11:36).

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.

Commerce Backoffice

Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about
Correct way for Attributes in Commerce


Add only one input filter to a textarea using form api I have created a custom form, in which I have one textarea field with a wysiwyg.
Here is the code

$form['text'] = array(
    '#type' => 'text_format',
    '#default_value' => variable_get('text'),
    '#title' => t('text'),
    '#format' => NULL,
  );
  return system_settings_form($form);

So it returns me a textarea field with a format dropdown. Which I don't required. I need only to use the filtered_html and the format dropdown should not appear.

There are several  way to  achieve this, you can use the Hide Formats module:

  Hide Formats allows you to collapse the "text format" or "input
  format" dropdowns to clean up the UI.

or Better Formats module:

  Better formats is a module to add more flexibility to Drupal's core input format system. Features 8.x & 7.x (needs more testing for a stable release)

  Set allowed text formats per field.
  Set default order of text formats per field.
  Hide format tips per role. Hide more format tips link per role.
  Hide format selection per role per entity.
  Currently only works on Field API fields on fieldable entities implementing core style text processing. The good thing is that is
  most things in core and contrib.

Or, use the FormAPI to disable it with something like:

// hook_form_alter function
function CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
    // We want this on a specific node type
    if ($form_id == 'NODE_TYPE_node_form') {
        $form['#after_build'][] = 'CUSTOM_MODULE_NODE_TYPE_node_form_after_build';
    }
}

// afterbuild function
function CUSTOM_MODULE_NODE_TYPE_node_form_after_build($form) {
    // We want this on a specific field
    $form['YOUR_FIELD']['und']['0']['format']['#access'] = FALSE;
    return $form;
}

Also you can try this (I didn't test it but it may work):

$form['text'] = array(
    '#type' => 'text_format',
    '#default_value' => variable_get('text'),
    '#title' => t('text'),
    '#format' => "full_html",
    'format'=>array('#access'=> false),
  );


Event subscriber to invalidate a cache I am invalidating a cache tag in KernelEvents::REQUEST event:

public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = ['onRequest', 100];
  return $events;
}

public function onRequest(GetResponseEvent $event) {
  if ($this->request->cookies->has('myValue')) {
    $this->cacheTagsInvalidator->invalidateTags(['my_tag']);
  }
}

When I refresh the page the tag is invalidated but the changes are showing on the next refresh, to which event/hook/etc. do I need to subscribe me to see my changes in single refresh ?

Edit 1:
I have 'Internal Page Cache' module installed. If I uninstall it, the code above works fine.

Edit 2: Added the if condition.

I did it implementing a middleware:

mymodule/mymodule.services.yml:

mymodule.http_middleware:
  class: Drupal\mymodule\StackMiddleware\BeforePageCache
  arguments:
    - '@cache_tags.invalidator'
  tags:
    - { name: http_middleware, priority: 280, responder: true }

mymodule/src/StackMiddleware/BeforePageCache.php

...
/**
 * {@inheritdoc}
 */
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
  if ($request->cookies->has('myValue')) {
    $this->cacheTagsInvalidator->invalidateTags(['my_tag']);
  }

  return $this->httpKernel->handle($request, $type, $catch);
}
...


How can I retrieve the value of variable I have defined in a config form from a Twig template? I have a module in Drupal 8 to build a configuration form where I can set the value of a variable. But I don't know how to retrieve the value of that variable from the twig template.

In Drupal 7 I just needed variable_get() to get the value. What is the equivalent code that I should use in Drupal 8?

The values saved as configuration items can be accessed using code similar to the following one.
$slogan = \Drupal::config('system.site')->get('slogan');

Since you are asking for a template file, that code should be split in two parts. My example is for the node.html.twig template file, but you can use the same kind of code for other template files too.

In the preprocess function of your template file (e.g. mytheme_preprocess_node(&$variables)) you get the value of the configuration item
$variables['slogan'] = \Drupal::config('system.site')->get('slogan');

In the template file (e.g. node.html.twig), you access that variable
{{ slogan }}

Be sure not to use a variable ($variables['slogan'], in my example) that is not already used from the template file, or its preprocess functions.


How to get a field value in form validate i have a custom form validate function. what is the correct/reliable way to get the field value and why? below two lines get the same value from a Select List.

a) $form['field_a']['und']['#value']

b) $form_state['values']['field_a']['und'][0]['value']

Refering to form API Drupal 7 for #value

$form['field_a']['und']['#value']

  Used by: button, hidden, image_button, submit, token, value

  Description: Used to set values that cannot be edited by the user.

For $form_state['values']['field_a']['und'][0]['value']

  $form_state is one of the arguments passed to a form submission
  handler, or a form validation handler; its main usage is to retrieve
  the values entered from the user in the form see the content of
  $form_state['values'])

So you should use $form_state['values']['field_a']['und'][0]['value']


Is it possible to stop a webform form during submission? The webform module is being used for a form that takes a payment. The data is validated as much as it can and then in a submit handler it is finally sent to the payment processor.

The result can be a failure (wrong card number, or no funds etc.), which should result in the form being re-presented giving the user the opportunity to check their fat fingers didn't type in the wrong card details, try another card etc.

In a vanilla Drupal form I could do a $form_state['redirect'] = FALSE; and it would return the form as-is, but this does not work when working within webform because it deals with that itself.

So this is a weird one because it's basically validation done in a submit handler. This is because we need to make sure everything's valid before submitting it to the third party, but there are clearly two ways to frame this question:

As the title says, is it possible for a submit handler to tell webform to stay on this page and not consider it complete?

or
If I move the submission code into a validation handler, how can I ensure my validation handler happens after all the others, and then check that there aren't any other validation errors before I proceed with the payment submission?

First is I'm not sure if it's best practice to do validations in the submit handler because as you've said, you need to validate first. So I can only answer your second question.
To make your validation run after every validation present for that form, you need to add it in the end of the #validate attribute. Example is like:
$form['submit']['#validate'][] = 'your_last_needed_validation_func';
To check if there are validation errors before your validation function, you can use the form_get_errors function.


Procedure For Cloning Commerce Collection Taxonomy View Page? We are creating a store with Commerce Kickstart2. We need to duplicate the functionality of the Collection taxonomy. Essentially, we need -exactly- what the collection field does, but we need another one to organise products in a different way.

I've created a new Taxonomy term called 'Specialty'. I've successfully added that field to the Products. They can be searched and displayed and if I type in

/specialty/whatever-term

...I get a basic taxonomy term page of the correct products.

What I want to do is clone the View called 'collection-products' to a new view 'specialty-products' which does -exactly- the same thing, but for the new vocabulary 'Specialty'. I took a wild stab at it:

I copied/renamed the PHP file for the view into my theme folder

views-view--specialty-products--page.tpl.php

Edited that php replacing 'specialty' for all the vars 'collection'.
I cloned the collection-products view and replaced the 'collection' field with 'specialty' where necessary.

So (naturally) this does nothing.

Can someone provide guideance on where I went wrong or how to proceed from here?

I think you need a view based on your products filtered to your taxonomy term. You should be able to do this with the views UI more easily than the way you're attempting to programatically.

I think you're misunderstand the theme folder altogether and how drupal presents the page that is rendered in the browser. The theme folder has mark up, images, and CSS that defines how your whole site is displayed, the views are generated, not stored as discrete files in your theme folder.

If you're on the kickstart demo store. Go to Product Categories, delete the defaults, add your own 'categories', and that should change the demo store to reflect your own set up. You should play with a default drupal set up to get familiar