Remove disabled modules from Database i just recently learned that i must unistall the module before delete it from modules folder ( "I thought that the deleting is the unistall" ), so can you please give a solution to delete the disabled modules from database ?
and is that make a problem?

Yes, you can get errors when you delete the module files without disabling it first. It's best to completely uninstall the module, which allows the module to clean up after itself (eg. delete configuration from the database). After that, you can safely delete the files.

If you already deleted the files, the easiest way to get rid of bits and pieces left in the database, is to restore the files (download the module again and put the files back where they were), follow the uninstall process, and delete the files. Make sure you download the exact same version of the module you had installed earlier.

So how do you know which module version you had? Ideally you are already using a version control system (such as Git) to manage your code, so you can always look back in the history to find out which module version you were using. If you don't have version control, you can try to find the version number in the database as described in this answer. As a last resort, try to remember when you installed or last updated the module and look in the module's releases list to find a version close to that date.


Variable in base path I need to change the BasePath in drupal 8 of all views and all node in such a way that it contains a variable (which will manage as country)
Like this:

site.locl/{lang}/{variable}
site.locl/en/testvar/node/100
site.locl/en/testvar/myview

Search for path inbound and outbound processing, that's what the alias and language prefix systems use for example. Both are tagged services, see PathProcessorAlias and the corresponding service definition path_processor_alis.

In Inbound, you cut off the part you want and store it somewhere in a service or so, where you can access it again where you need it. And in outbound, you add it again. As you seem to require both language and country, you will need to make sure the priorities are correct in relation to the language prefix handling.

Keep in mind that this will not give you any possibility to have different interface or content translations as there isn't really a way to store it. If you need that, you more likely need to use a language per language/country and figure out how to do fallbacks correctly.

There is also a module available that helps with this: https://www.drupal.org/project/purl. It apparently has an 8.x dev version, but I have no idea about the state of it.


Referenced entity with multiple values making duplicate rows in views I checked 'distinct' in my view configuration in Query settings under the 'advanced' fieldset.

So say when I have have three entities connected to one node, there would be three rows in my view of the same node of course one for each entity.

Fields settings

Content: Hour ('event')
Content: Title ('event')
Content: Body ('event')
(Content entity referenced from field_event_performer) Content: Title
(Content entity referenced from field_event_performer) Content: Body
(Content entity referenced from field_event_performer) Content: Foto
Content: Title  ('event')
(Content entity referenced from field_event_performer) Content: Performer

Some fields I've given a class in order to hide them using jQuery and show them in a modal frame when clicked on. That's why fields are shown double. First I thought the problem was be because of the weird field settings. But the nodes that show only one time have the same field settings, only do they have more performers referenced.

I have 4 filter criteria in total:

Content: Published (Yes)
Content: Type (= Event)
Content: Evenement type (= Presentatie) | Settings  (taxonomy)
Content: Locatie (= Kraakhuis)   | (taxonomy)

Having done searches I noticed that everyone who had this problem, only needed 1 field from the referenced entity and could use the aggregation funtion as found under advanced. This works quite fine here as well if I only needed 1 field.

But in my case, when output into a modal frame, one entire row should look like this:

Node123 title
Node123 body
referenced entity 1 title
referenced entity 1 body
referenced entity 1 picture
referenced entity 2 title
referenced entity 2 body
referenced entity 2 picture
referenced entity 3 title
referenced entity 3 body
referenced entity 3 picture

What helped is going custom code. Instead of relying on the fields that would have come out of the Views query, I grabbed the nid of my referenced field of my 'event' content type and loaded the rest of the fields via node_load();. All of this happening in a tpl file views-view-fields--viewnale--block.tpl.php

I used the row object and made a loop that went over the multiple valued referenced entity.

    <?php foreach($row->field_field_evenement_performer_1 as $key => $whatever): ?>
    <?php $performer = node_load($row->field_field_evenement_performer_1[$key]['raw']['target_id']);

    $title = $performer->title;
    $picture = $performer->field_performer_foto['und'][0]['uri'];
    $bio = $performer->body['und'][0]['value'];

    print '

' . $title . '

';
    print '

';
    print '
' . $bio . '
'; ?>

<?php endforeach ?>


How to build drupal-twitter bot like the one on drupal.org I'm really impressed by this bot:  drupal8changes which gets changes from http://drupal.org/list-changes/drupal and posts it on to Twitter. I think it might be something like, when a new node is created of D8Changes content-type, then post it on to twitter. Isn't it awesome? I want to know how that could be implemented? Not just limited to twitter, but for Facebook, Google+ etc.

You can achieve this by using Twitter & Oauth module. You will have to create a twitter app & use Consumer key, Consumer secret to connect to your twitter account.

You will have to choose a content type for tweet & yeah don't forget to enabled import option on twitter account.


How to set cache meta data on drupalSettings? I use drupalSettings to send config data to javascript. But when I edit my config, the javascript object is not modified, I have to clear all cache to get the update.
The cache metadata in http headers show me that the page is linked to my 'config:my_module.settings' tag but the inline drupalSettings declaration is left unchanged.

What's the way to add cache metadata to:

$attachments['#attached']['drupalSettings']['example']['foo']
//or in hook_preprocess_hook ()
$variables['#attached']['drupalSettings']['example']['foo']

Or is there a function that could rebuild drupalSettings ?

When you add attachments you can add cache data as well:

$attachments['#cache']['tags'][] = 'config:my_module.settings';

BTW #attached and #cache are the only data you are allowed to add in hook_page_attachments() or hook_page_attachments_alter().


Filter taxonomy terms in autocomplete list by boolean field on vocabulary's terms? I need to implement a boolean field for a vocabulary that determines whether terms within a vocabulary appear in autocomplete results for a taxonomy term reference field's autocomplete widget. The function taxonomy_autocomplete(...) has the query that I want to modify. But how can I modify the query or override the results of the autocomplete json callback?

I know how to add the boolean field to the vocabulary but not how to filter autocomplete results. The idea is to let users enter new terms but not have their new terms appear in autocomplete results unless approved by an admin.

Here is how I've added a new term custom widget:

/**
 * Implements hook_field_widget_info().
 */
function deepestlevel_taxonomy_widget_field_widget_info() {

  return array(
    'textfield' => array(
      'label' => t('deepestlevel_taxonomy_widget - Only deepest level'),
      'field types' => array('taxonomy_term_reference'),
      'settings' => array(
        'size' => 60,
        'autocomplete_path' => 'deepestlevel_taxonomy_widget/autocomplete',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function deepestlevel_taxonomy_widget_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $tags = array();
  foreach ($items as $item) {
    $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  }

  $element += array(
    '#type' => 'textfield',
    '#default_value' => taxonomy_implode_tags($tags),
    '#autocomplete_path' => 'deepestlevel_taxonomy_widget/autocomplete'. '/' . $field['field_name'],
    // '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
  );

  return $element;
}

/**
 * Implements hook_menu().
 */
function deepestlevel_taxonomy_widget_menu() {
  $items['deepestlevel_taxonomy_widget/autocomplete'] = array(
    'title' => 'Autocomplete taxonomy deepest level',
    'page callback' => 'deepestlevel_taxonomy_widget',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

// THIS IS THE OVERRIDE CALLBACK copied from core taxonomy.pages.inc
// function taxonomy_autocomplete($field_name, $tags_typed = '') {
function deepestlevel_taxonomy_widget($field_name, $tags_typed = '') {

// NEW CODE HERE

}


Styling two views using the same template file? I have two views that are pretty similar so I want them to use the same template file. However, in views I can only select templates that have a name unique to that view meaning two views can't use the same template. How can I accomplish this?

If your views are same or similar then manage both of views as one using multiple views displays. For each display settings and configuration can be overridden. Template can be shared among displays of a single view.

The other a little bit bad way, can be to create a single template file and then include that template to your views templates.


How to force account creation before commerce checkout is complete? I currently have a one-page checkout that works great for anonymous users. After payment is complete, an account is created with the 'Create a new account for an anonymous order' checkout rule.

Now I need to add a subscription product to the site, and plan to use Commerce License and Commerce License Billing to sell a role. To handle recurring payments, I plan to use Commerce Card on File.

This introduces a problem because Card on File requires an authenticated user in order to save cards. See https://www.drupal.org/node/1553468

How can I create a user account before checkout finishes so that Card on File can properly save cards?

Ideally, there would be a custom checkout page that forces account registration as a first step in checkout, but only for users purchasing subscription products.

I don't allow visitors to register on the site at the moment (except via Commerce Checkout), and I'd rather not change that.

I suggest the following steps :

create a custom checkout pane (see  checkout_pane_example.module ) and embed the user register form in that pane:

/**
 * Implements hook_commerce_checkout_pane_info().
 */
function vts_register_commerce_checkout_pane_info() {
  $panes['register'] = array(
    'title' => t('Create an account'),
    'base' => 'vts_register_pane',
    'name' => t('NAME'),
    'page' => 'checkout',
    'weight' => -5,
  );
  return $panes;
}
/*
 * Add user_register_form to register pane
 */
function vts_register_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  $pane_form = drupal_get_form('user_register_form');
  return $pane_form;
}
/*
 * Alter checkout form register pane
 */
function vts_register_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  unset($form['register']['actions']);
}
/**
 * checkout form submission callback.
 */
function vts_register_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  $new_user = array(
    //dsm to find the correct $form_state['input'] for username here, because I have an altered user register form...
    'name' => $form_state['input']['field_name_first']['und'][0]['value'].'_'.$form_state['input']['field_name_last']['und'][0]['value'],
    'pass' => user_password(),
    'mail' => $form_state['input']['mail'],
    'init' => $form_state['values']['mail'],
    'status' => 1,
    'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
  );
  if($GLOBALS['user']->uid == '0') {
    $user = user_save('', $new_user);
    //ASSIGN the current order to created user
    $order->uid = $user->uid;
    commerce_order_save($order);
    $GLOBALS['user'] = $user;
  }
  //check that you got a new user and the order was assigned to him
  dsm($user, 'user');
  dsm($order, 'order');
}
/**
 * Validation callback.
 */
function vts_register_pane_checkout_form_validate($form, &$form_state, $checkout_pane, $order) {
  //validation stuff
  return TRUE;
}
/**
 * Ouputs Review checkout pane.
 */
function vts_register_pane_review($form, $form_state, $checkout_pane, $order) {
  // add some info to review pane
  return;
}

Go to admin/commerce/config/checkout and set it as disabled
Install Commerce Rules Extra, it adds the features you need :

  Rules conditions : Total product of type quantity comparison

  Rules actions : Change pane properties : Change visibility, page, weight of a pane

Create a rule :

Event: Process checkout pane.
Conditions : user is anonymous ; subscription product quantity > 0.
Action : Change pane properties : enabled: true; move to checkout.


Where does the profile name on the Status Report come from? When I click on Reports > Status report, the Install profile field says Snrub (snrub-"1.1) (with exactly one double quote). Where is this value defined?

When the status report is rendered, profile info is retrieved from drupal_get_profile() (by referencing the install_profile var) as well as system_get_info() to retrieve all the metadata properties (by referencing the system data table)


The previous published revision should be available for the visitors while the current revision is in needs review state I am using Workbench Moderation module for moderation on nodes. I notice that it creates revision of the nodes.

I have a node which is in live/publish state therefore it is available for the site visitors. Then when an editor edit that node, I programmatically put that node in needs review state and create a new revision for that node.

After that the site visitors are not able to access that node until its state change to publish.

I want that the new revision should be needs review state and the previous publish revision of the node should be available to site visitors.

The code which I am using for setting the state of the node is as following.

$node->status = 0;
$node->revision = 1;
node_save($node);
workbench_moderation_moderate($node, 'needs_review');

I solved it.

Before the revisioning I loaded the original node first. Then first save the new revision and then save the original node.

My code now looks like this.

$original_node = node_load($nid);
$node = node_load($nid);
$node->revision = 1;
$node->workbench_moderation_state_new = 'needs_review';
node_save($node);
node_save($original_node);


When user.private_tempstore gets deleted I've read about the

  \Drupal::service('user.private_tempstore')->get('mymodule_name');

and found similar to storing data in $_SESSION.

I am using user.private_tempstore in my module to store some data related to the user for a current session but when I logout and login again to the system found the value still persist in that variable. It is supposed to delete on logout.

To store data

  $userSession = \Drupal::service('user.private_tempstore')->get('user_profile');
  $userSession->set('user_profile', TRUE);

To get data

  $userSession = \Drupal::service('user.private_tempstore')->get('user_profile');
  $user_profile = $userSession->get('user_profile');

Is my understanding wrong?

Private tempstore data isn't deleted when you log out, it is usually deleted after a predefined, fixed amount of time.

If you want data that is deleted on logout, then either store in the session or store it somewhere with a random key that you put into a session (Useful when it is data that is no commonly needed on every request and/or larger than just a simple scalar value)


How do I get rid of the "Review payment" form after PayPal Express checkout? Can I somehow disable "Review payment" site after paying with "Express Checkout" method on PayPal?

Why is it even needed? Why do we assume that our customers who pay via PayPal "Express Checkout" do have a company? (There is the field "Company".)

Here's a screenshot:

I got the answer and the solution on Ubercart's forum.

Quoting the user longwave:

  "In Drupal 6/Ubercart 2 go to
  /admin/store/settings/payment/edit/gateways and expand PayPal Website
  Payments Pro then Express Checkout.
  In Drupal 7/Ubercart 3 go to
  /admin/store/settings/payment/method/paypal_ec and look towards the
  bottom of the page."

I'm using D6.
Then I mentioned that I see the following message on that page:

  "You must enable the Credit Card module to use PayPal Website Payments
  Pro."

... and that I didn't want to enable Credit card module while I don't need it. He said I have to, if I would like to reach "Review payment" settings:

  "The settings are hidden here, this is a known bug. Enable the credit
  card module; you don't have to use it - or you should be able to
  disable it again after changing the Express Checkout settings."

That's true, everything related to "Review payment" form could be set there!
I made a screenshot for others who are also struggling with this problem:

Problem solved. No more unnecessary questions before purchasing. :)


How to loop through fields from the Field Collection? Here below is the code loading data present in the field collection.
$field_collection = entity_load('field_collection_item', $ids = FALSE);

In each field collection, there are many fields, i would like to loop through each fields
is there a way to do it? Any help?

I'm current "fighting" width this module, too. I don't know if it is the correct/easiest way, but it works (for me).

First you have to load the ids of the field collection fields of the node:

$fc_fields = field_get_items('node', $node, 'field_image_teaser');

// Extract the field collection item ids
$ids = array();
foreach ($fc_fields as $fc_field) {
    $ids[] = $fc_field['value'];
}

I found the code above at Accessing a field collection (a related question).

To iterate over all fields you can use the following code:

//Get the entities
$collections = field_collection_item_load_multiple($ids);

//Loop over the array - if you have more than one entity
for ($i = 1; $i <= sizeof($collections); $i++) {
    $collection = $collections [$i];

    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
        //Look for fields - there are some other class vars, too.
        if (strpos ($key, 'field') !== false) {
            //Search for textfields
            if (isset($value['und']) && is_array($value ['und']) && isset($value['und'][0]['value'])) {
                print "Field ".$key." ".$value['und'][0]['value'];
            }
        }
    }
}


Need example : D7 + XPath parser to import (mediawiki) XML - xpath parser settings? I've installed XPath/Feeds/D7, but I don't know how to configure XPath parser settings.

Maybe someone can help me to set it right.

I just want to inject <title> and <text xml:space="preserve"> to my node.

I need help to configure my XPath Parser settings : admin/structure/feeds/edit/my_import/settings/FeedsXPathParserXML

I've the following XML structure :

<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang="fr">
  <siteinfo>
    <sitename>Site Name</sitename>
    <base>http://domain.net/index.php/StartPage</base>
    <generator>MediaWiki 1.15.5-1~bpo50+1</generator>
    <case>first-letter</case>
    <namespaces>
      <namespace key="-2">Media</namespace>
      <namespace key="-1">Special</namespace>
      <namespace key="0" />
      <namespace key="1">Chat</namespace>
      <namespace key="2">user</namespace>
      <namespace key="3">Chat user</namespace>
      <namespace key="4">domain.net</namespace>
      <namespace key="5">Chat domain.net</namespace>
      <namespace key="6">files</namespace>
      <namespace key="7">Chat files</namespace>
      <namespace key="8">MediaWiki</namespace>
      <namespace key="9">Chat MediaWiki</namespace>
      <namespace key="10">Model</namespace>
      <namespace key="11">Chat model</namespace>
      <namespace key="12">help</namespace>
      <namespace key="13">Chat help</namespace>
      <namespace key="14">category</namespace>
      <namespace key="15">Chat category</namespace>
    </namespaces>
  </siteinfo>
  <page>
    <title>Drush</title>
    <id>579</id>
    <revision>
      <id>1637</id>
      <timestamp>2012-05-25T14:51:51Z</timestamp>
      <contributor>
        <username>admin</username>
        <id>1</id>
      </contributor>
      <comment>/* Install Drupal with Drush */</comment>
      <text xml:space="preserve">Drush is a command line utility.

=Install Drupal with Drush=
To install drupal with drush :
 drush site-install standard --db-url=mysql://username:pass@localhost/databasename

[[category:Drupal]]</text>
    </revision>
  </page>
  <page>
    <title>Memcache</title>
    <id>586</id>
    <revision>
      <id>1287</id>
      <timestamp>2012-02-12T17:43:32Z</timestamp>
      <contributor>
        <username>admin</username>
        <id>1</id>
      </contributor>
      <comment>Do it under Debian</comment>
      <text xml:space="preserve">=Install=
==Debian==
===Memcache Server===
To install :
 aptitude install memcached

Read and change ''/etc/memcached.conf''.
===PHP5 / PECL===
Install memcache PECL :
 php5-memcache
or
 pecl install memcache

Restart Apache.

===Drupal===
* InstallMemcache module in Drupal.
* Change ''settings.php'' :
&lt;source lang=&quot;php&quot;&gt;
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'site_prefix';
&lt;/source&gt;

Read : http://drupal.org/node/1131458

[[category:Linux]]

[[category:Drupal]]</text>
    </revision>
  </page>
</mediawiki>

Optional task : How can I convert "=" to <h1>, "==" to <h2>, space before start of line to <pre>, [[category:xyz]] to Tags, etc ... ?

Context should be : //Mediawiki/page,  Title field should be title and Text should be revision/text.


Simple row saving through link with Drupal 7 I have a simple requirement but I am not sure how to fulfill it. On my Drupal site, I need a link which when I click creates a row in a table in DB through AJAX.

That's about it.

The main goal of mine is to create a "My List" for any user. The user can go to any node and press "Save it" and it can then save it to the "List". User can later go to "My List" and see all the "saved" nodes which he saved.

Hence Basically, it's a Save for later for the nodes.

I hope there is some module for it. I couldn't find hence I thought I can create it myself, hence the question.

Many Thanks

take a look at the Favourites module:

  Favorites provides a tiny block that allows users to easily bookmark
  any content of the site.

or the Flag module:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.


Node form with fields loaded from another node or other entity I am stuck on this problem, I was making a 'field' to be available on many content types, but this field has itself many fields, so i decided making an entity to have those fields seperate. I choose an entity because i don't these information to be accessible in the searchs etc, and I don't need revisions. Now on the node form submission i would like to have both the fields of the node and the fields of the entity showing up on the same form, as if this entity was a field.  How can i do that ?

If I use form_alter: ok i understood how to add widgets to the form, but then that means i have to re-write all the validation code etc from all fields ? Is it possible to load fields so that they will keep all their properties? (validation, submission etc)
Would it be possible to create a field module that would load other fields from a node/entity type on each hook ?
Any other solution ?

Idealy i would to find or make an 'entity-reference' module that does that job! (load field from one in the other when creating, editing, loading a node) !!

any help welcom, thanks !

dylan

Isn't module Inline Entity Form exactly what you are looking for? Here is a quote about it (from the module's project page):

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.


Term reference is not available as a contextual filter for a View. Why not? I have a commerce product of type Album. On this content type is a taxonomy term reference. This term is from the vocabulary 'Our Artist'. In other words, every album gets tagged w/ the artist name that comes from the 'Our Artists' vocabulary.

I'm trying to create a view that groups together all of an artist albums. I want to use this taxonomy term as a contextual filter. But it is not showing up as an option in the contextual filters list. Can someone explain why?

As mentioned in Niall's comment, you will want to add the taxonomy relationship. In a view that I created recently, I used the Content: Taxonomy terms on node relationship. Once I added it, Content: Has taxonomy term became an available option under Filter criteria.

That is only one way of doing it. There are a few different taxonomy relationships which serve unique purposes. I'd experiment with them to see what fits your needs.


Search API: getAutocompleteSuggestions in D8? How can I use the function getAutocompleteSuggestions() in Drupal 8?
In Drupal 7 you could do something like this:

$query->getIndex()->server()->getAutocompleteSuggestions($query, $this->getSearch(), $incomplete_key, $user_input);

Thank you for your help!

I've solved it with Solarium

//...
use Solarium\Client;
//...

// $value is the search value from the textfield.
if (!empty($value)) {
    $searchAPIconfig = \Drupal::config('search_api.server.server');
    $searchAPIconfigData = $searchAPIconfig->getRawData();

    $config = array(
    'endpoint' => array(
      'localhost' => array(
        'host' => $searchAPIconfigData['backend_config']['host'],
        'port' => $searchAPIconfigData['backend_config']['port'],
        'path' => $searchAPIconfigData['backend_config']['path'],
      ),
    ),
    );

    $client = new Client($config);

    if ($client !== NULL) {
        $query = $client->createSuggester();
        $query->setQuery($value);
        $query->setDictionary('mySuggester');
        $query->setOnlyMorePopular(TRUE);
        $query->setCount(10);
        $query->setCollate(TRUE);

        $resultset = $client->suggester($query)->getData();
        $results = $resultset['suggest']['mySuggester'][$value]['suggestions'];
        $suggestions = array();
        foreach ($results as $key => $termResult) {
          $suggestions[] = $termResult['term'];
        }

        //...
    }
}


How to replace node_form() with my custom form callback? In my module, I want to override the call to node_form() for a specific node type called superpage, because I want this specific node form to allow for a confirmation step before saving.

In drupal_retrieve_form(), every node form is built by the function node_form(), which adds everything you'd expect from a node form.

I want to add an extra step to my form: First, the node form should be rendered normally; then, when the user clicks Save, I am using a custom submit handler to set $form_state['rebuild'], and to set a custom flag, signaling the need for confirmation. Now I want to rebuild the form not through node_form(); instead I want to display a confirm_form().

This means that the process starts over in drupal_retrieve_form(), which simply calls node_form() again, because the node module implements hook_forms() and defines that callback for all node forms.

I would like to replace the form callback for my custom content type, so that it returns a normal node form if confirmation is not needed, or a confirmation form if needed.

Implementing hook_forms() in my module didn't help.

/**
 * Implements hook_forms().
 */
function superpages_forms($form_id, $args) {
  $forms = array();
  if ($form_id == 'superpage_node_form') {
    // Adding this callback crashes drupal_retrieve_form().
    $forms[$form_id]['callback'] = 'superpages_wrapped_node_form';
  }
  return $forms;
}

function superpages_wrapped_node_form($form, &$form_state, $node) {
  // Build for special case: a confirmation form.
  if (!empty($form_state['values']['confirm_is_needed'])) {
    $confirm = t('You should be careful with this. Are you sure?');
    $confirm_form = confirm_form(array(), $confirm, 'node/' . $node->nid);
    return $confirm_form;
  } else {
  // Build a normal node form.
    return node_form($form, $form_state, $node);
  }
}

Variant 1. You can use hook_menu_alter and you can set your callback

/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/superpage']['page callback'] = 'MYMODULE_superpage_form';
}

Variant 2. You can use hook_form_FORM_ID_alter  and override/edit the form

/**
 * Implements hook_form_FORM_ID_alter()
 */
function MYMODULE_form_superpage_node_form_alter(&$form, &$form_state, $form_id){
  // your code
}


Exposing a single field to users to create new nodes from a page I am researching if Drupal is the right choice for my project and so far it seems like it fits, except for one issue. I want to give my users ability to create new nodes from a page, let's say it could be something like creating a Facebook status and would reside at /statuses.

Then these nodes could be visible to other users from the same /statuses page. I don't want my users to deal with publishing and path and all those other options that are available via general Create New Node form - I just want to expose one field that they can fill out on /statuses, hit Submit and then have Drupal do the rest.

Is Drupal suitable for such tasks and what would be the most Drupal way to do it?

I am fairly new to Drupal but have tons of experience with other CMSs and frameworks.

Edit

I am not looking to create specific feed Facebook/Twitter functionality - it was just an example. The functionality that I am going to create will include much more than that. Feeds were just an example - sorry if I gave the impression that it's what I want to make.

The question is what would be the most Drupal-way to expose a single form field that will allow users to create a new node from a page.

Edit

Here's a mockup of the form and page that I want to make. So what would be the best way to proceed?

So you want to create something like simplistic Twitter/Facebook wall? Check following modules:
Microblog

Users can publish microblog updates, follow and be followed by other users, and reply to other users' microblog updates.
Module also provides "public timeline" page as well as followers and following pages, and a block of "recent microblog updates."

Drupal 6 & 7: https://drupal.org/project/microblog
Statuses (Social Microblog)

Provides status updates / microblogs like Facebook's Wall / News Feed, Twitter's Timeline, and Yammer's Feed. Users can update their own status or write messages to other users, nodes, Organic Groups, taxonomy terms, or other entity types. @mentions and #hashtags are supported, as well as comments on status updates, viewing conversations between users, the ability to "like"/"reply" to/RT a message, automatic updates without page refreshing, and integration with over 20 modules.

For Drupal 6: https://drupal.org/project/facebook_status
For Drupal 7: https://drupal.org/project/statuses


Unable to store value of an property or entity key in ConfigEntityType form I have a propay_account_number in config entity type which I am unable to save using the below code.
What is incorrect and how can I fix it to make it work ?

src\Entity\PropayAccount.php

namespace Drupal\propay_api\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;

/**
 * Defines the Propay Account entity.
 *
 * @ConfigEntityType(
 *   id = "propay_api_account_number",
 *   label = @Translation("Propay"),
 *   handlers = {
 *     "list_builder" = "Drupal\propay_api\PropayAccountListBuilder",
 *     "form" = {
 *       "add" = "Drupal\propay_api\Form\PropayAccountCreateForm",
 *       "edit" = "Drupal\propay_api\Form\PropayAccountRenewForm",
 *       "delete" = "Drupal\propay_api\Form\PropayAccountDeleteForm",
 *     }
 *   },
 *   config_prefix = "account_number",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "propay_account_number" = "propay_account_number"
 *   },
 *   config_export = {
 *     "id",
 *     "label"
 *   },
 *   links = {
 *     "edit-form" = "/admin/config/development/propay-api/account-number/{propay_api_account_number}",
 *     "delete-form" = "/admin/config/development/propay-api/account-number/{propay_api_account_number}/delete",
 *     "enable" = "/admin/config/development/propay-api/account-number/{propay_api_account_number}/enable",
 *     "disable" = "/admin/config/development/propay-api/account-number/{propay_api_account_number}/disable",
 *   }

 * )
 */

class PropayAccount extends ConfigEntityBase {

    /**
     * The Propay ID.
     *
     * @var string
     */
    protected $id;

    /**
     * The Propay Label.
     *
     * @var string
     */
    protected $label;

    /**
     * The Propay Account Number.
     *
     * @var string
     */
    protected $propay_account_number;

    public function id() {
        return $this->id;
    }

    public function label(){
        return $this->label;
    }

    public function getAccountNumber() {
      return $this->propay_account_number;
    }

}

config\schema\propay_api.schema.yml

propay_api.account_number.*:
  type: config_entity
  label: 'Propay Account Number'
  mapping:
    id:
      type: string
      label: 'ID'
    label:
      type: label
      label: 'Label'
    propay_account_number:
      type: string
      label: 'Propay Account Number'

src\Form\PropayAccountCreateForm.php

    <?php

    /**
     * @file
     * Contains \Drupal\propay_api\Form\PropayAccountCreateForm.
     */

    namespace Drupal\propay_api\Form;

    use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;

class PropayAccountCreateForm extends EntityForm
{

    public function form(array $form, FormStateInterface $form_state)
    {
        $form = parent::form($form, $form_state);

        $entity = $this->entity;
        $form['id'] = [
            '#type' => 'textfield',
            '#title' => $this->t('ID'),
            '#required' => TRUE,
            '#default_value' => ($entity->id()) ?? '',
        ];

        $form['label'] = [
            '#type' => 'textfield',
            '#title' => $this->t('LABEL'),
            '#required' => TRUE,
            '#default_value' => ($entity->label()) ?? '',
        ];

        $form['propay_account_number'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Propay Account Number'),
            '#required' => TRUE,
            '#default_value' => ($entity->getAccountNumber()) ?? '',
        ];

        return $form;
    }

    public function save($form, FormStateInterface $form_state)
    {
        $entity = $this->entity;
        $entity->set('propay_account_number', $form_state->getValue('propay_account_number'));
        $entity->save();
    }
//event tried formSubmit() but it did not help save the values in propay_account_number

}

Try this one for saving config.

$config = Drupal::service('config.factory')->getEditable('my_module.settings');
$config->set('my_module.dsu_single_indexing_server',json_encode(array_unique($values)))->save();


Linking Content Types to Pages I have multiple content types like news, publications, etc and I will like to link them to pages on my site. So when a user posts a news item on a specific page, it only shows up on that page only. Also I will want users to be able to edit content on only pages they have been assigned to. Eg. A user will only be allowed to add news to pages they have rights to.
I was considering using groups for this, but I know more suggestions will be helpful.

Many thanks
Isacc

You can create different views and filter the content types.


Drush aliases and Permission denied (publickey,password) problem Im trying to use Drush Aliases but getting Permission denied (publickey,password) error. I can login to server using publickey without password but Drush can not.
I've read the solution mentioned here and made the change but no success. Is there anything I'm missing here?

A possible cause is that you are not specifying your remote user in the drush alias file.

For example, if the ssh command that works to allow you to login is:

ssh myuser@example.com

Then an alias might look like this:

$aliases['dev'] = array(
  'uri' => 'http://www.example.com',
  'root' => '/var/www/vhosts/example.com/docroot/',
  'remote-host' => 'example.com',
  'remote-user' => 'myuser'
);


Why does legend not appear when the first bar value is zero? I have created a chart using Forena reports. I have added the legend by using the property frx:legend_entries="legend" from the frx file.
But when value of the first bar chart is zero or null, legend is not visible.

I am attaching the pictures below.

I would check the results you'd get by using either of these special settings in the SVG Graph library:

Use the (boolean) force_associate option.
Set the axis_min_v option to something like -1.

If none of these options help, you might have discovered "some issue" (bug?) in the SVG Graph library.

A possible work around might also be that you can think of a way to replace the "zero or null" with "NULL".


Admin Menu Extra Items and Errors Not quite sure how to explain this, but I will go through what I did, and when the errors started happening.

I have enabled the default taxonomy view in Views, changed it to fields, and added a grouped filter.

After saving, I see the error "Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 .../html/includes/bootstrap.inc)." AND suddenly the admin menu has loads of new items in it?

I read up on it, but cant see any fixes, so try disabling and re-enabling the taxonomy view, and also admin menu.

Now the error message has gone, everything works fine, but I am left with all of these extra menu items in the admin menu.

I have logged in as other lower level users, and their admin menus are fine, yet as the super user (with all permissions) I have about 20 or 30 menu items added to the menu before the usual entries.

I have no idea where to start looking with this. The error above seems to happen when a module passes an array through check_plain(), so it usually a module error rather than core. But in this case, it seems to be the taxonomy view that has triggered it, unless its a coincidence.

Can anyone offer guidance?

EDIT: Also tried flushing cache. And worst comes to worse can revert to a backup 5 days ago, but will lose a fair bit of content, so want to avoid this.

EDIT: Looking phpmyadmin, I can see that all of these new menu items have indeed been added to the menu_links table, but do not appear in the structure > menus > management list.

Reverting the taxonomy view back to its original state, and then rebuilding the changes again made the errors disappear from watchdog, but the management menu and admin menu were still completely messed up.

To fix this, I installed Devel module, and the ran a SQL query to delete all menu rows added by system.

mysql> delete from menu_links where module='system';

I then navigated to /devel/menu/reset

This successfully re-built the management menu, and everything went back to normal.

Note: I also used backup and migrate to quickly clone the website onto a local server and test the changes before making the changes on the production environment.


How can I email all registered users? A lot of similar questions show up in Google, but I can't find a solution for Drupal 7.

You could use the Mass Contact module.

  The Mass Contact module allows anyone with permission to send a single message to multiple users of a site, using its roles functionality.


Create dynamic block instances In Drupal 7, if we need to define multiple instances of blocks from a database table, we use a foreach loop to return the array key, and then we we get all the multiple instances of our block using hook_block_info().

function mymodule_block_info() {
    $blocks = array();
    $add = db_select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta', 'title', 'content_type'))
                  ->condition('n.form_type', 'Add', '=')
                  ->execute();
    foreach ($add as $row) {
        $blocks[$row->delta] = array(
      'info' => t('@name (Add Form Block) Type: @type', array('@name' => $row->title, '@type' => $row->content_type)),
      'cache' => DRUPAL_NO_CACHE,
        );
    }

    $edit = db_select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta', 'title', 'content_type', 'nid'))
                  ->condition('n.form_type', 'Edit', '=')
                  ->execute();
    foreach ($edit as $row) {
        $blocks[$row->delta] = array(
      'info' => t('@name (Edit Form Block) Nid: @nid', array('@name' => $row->title, '@nid' => $row->nid)),
      'cache' => DRUPAL_NO_CACHE,
        );
    }

    return $blocks;
}

In Drupal 8, I suppose hook_block_info() is replaced by plugin derivatives.
Though I found a way here where they display nodes by using the entity manager, I have still to understand what I need to do when I am using my custom database table, and not an entity.

What is the equivalent code in Drupal 8 for hook_block_info()?

Create a file ex : YourBlock.php in   Drupal\mymodule\Plugin\Derivative\YourBlock.php

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class YourBlock extends DeriverBase
{
    public function getDerivativeDefinitions($base_plugin_definition)
    {
        $results = \Drupal::database()->select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta','title', 'content_type'))
                  ->condition('n.form_type', 'Add', '=')
                  ->execute();
        foreach ($results as $result) {
            $this->derivatives[$result->delta] = $base_plugin_definition;
            $this->derivatives[$result->delta]['admin_label'] = t('Title: @name content type: @ctype ', array('@name' => $result->title, '@ctype' => $result->content_type));
        }

        return $this->derivatives;
    }
}

  Also add the necessary annotation to display all the dynamic block instances in

Drupal\mymodule\Plugin\Block\YourBlock.php

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Display all instances for 'YourBlock' block plugin.
 *
 * @Block(
 *   id = "mymodule_block",
 *   admin_label = @Translation("Your block"),
 *   deriver = "Drupal\mymodule\Plugin\Derivative\YourBlock"
 * )
 */

Rebuild the cache as well


How can I get public files path in javascript files? I want to display files present in the public folder(sites/default/files). So in the module file when I click on a link it will call to js function, How can I get all file names which are present in the public folder in js file.

It depends where you are storing all your files, to use the base url of your site you need to do this:

$base_url."/sites/default/files/xxx.jpg"

If your files are inside some theme:

$base_url."/".drupal_get_path('theme', 'name_theme')."/images/xxx.png

If you are using files with public://, use this:

$uri = $your_file_name; // Example "public://xxx"
$path= file_create_url($uri);

I hope it works in your case


How to add a option in wysiwyg editor so that blocks can be selected as images? Using the Wysiwyg module, we are able to add an image. Is there any way so that I am able to view my blocks in it as well as assign those blocks in any place inside a page?

Seems you will need to write your own plugin. There are dozens of manuals, like Creating a CKEditor Plugin with a Custom Dialog Window - this one seems to be good for you, as you might want to have dialog window to allow user select a block.

You will need tips from this Drupal.org thread to

get list of blocks you will feed to the editor
make block data avaliable in node.tpl.php via preprocess function
render the block in a node, probably using custom created, block enabled text filter.

Don't forget to consider security issues when deciding who should be able to add what.

Last but not least, publish your module on Drupal.org for future developers.


Using Revision with Views I'm creating a page to list any content that needs moderation, which in my case includes new content and pending revisions.

I have the pending revisions down, by setting

Fields

Content: Nid
Content revision: Title (Title)
Content revision: Updated date (Last Revised)
Content revision: Vid

Filter Criteria

Content revision: State (= Pending)
Content: Revision moderation (=Moderated)
Content: Published (YES)

Now how do I add in content that hasn't been published that requires moderation, BUT don't pull prior content that has been set to unpublished?

I've tried opening up the filter for Content:published and selecting the ANY option and excluding it from display. However, When you unpublish content, the revision for it asks for moderator attention as if it was a new revision waiting to be published. So it grabs ALL unpublished content as opposed to only the new content waiting to be published.

For your revisions, I assume you're using the revisioning module.

Why not just remove the Content: Published filter entirely?  Any node with a pending revision should be moderated.

On my site, when I unpublish a node, unpublishing it alone does not cause it to have a pending revision.  In other words, if the most recent version of a node is published, unpublishing that node does not create a pending revision.

However, if you unpublish a node with a pending revision, that node will still have a pending revision after it is unpublished.  There is no way to use views alone to distinguish between a node with a pending revision that was "set" to unpublished and one that isn't published yet.

To implement such a workflow, I would suggest using the flag and rules modules.  Roughly, the steps I would take would be:

Create a global flag called "Intentionally unpublished."
Create a rule that automatically flags nodes when they are unpublished.
Add the flag as a relationship to your view and filter based on the existence of the flag.


Best way to delete all variables when uninstalling module I'm writing a module that writes several variables (three, four variables for every content type, and other).

Which method should I use to delete them on hook_uninstall?

Is it safe to perform a query, searching "mymodule_*" variables?

Or should I loop for content types and search variabels, so call many times variable_del?

Variables are cached, so deleting manually is fine so long as you invalidate that cache, e.g.

db_delete('variable')
  ->condition('name', 'mymodule_%', 'LIKE')
  ->execute();

cache_clear_all('variables', 'cache_bootstrap');


Alter Services JSON Response I have created a view to render all taxonomy terms and displayed it through a service. I have also created an endpoint in the service module to hit the url through firefox add-on RESTer to test the JSON response. Now I want to alter the JSON response to add more key and value programatically. I am sharing all my resources which I have used but nothing changed

This is my JSON response so far:
[
        {
            "Name": "General discussion",
            "tid": "1",
            "description": ""
        },
        {
            "Name": "Miscellaneous - Hangout forums",
            "tid": "2",
            "description": ""
        },
        {
            "Name": "Debt Management and Debt Consolidation",
            "tid": "3",
            "description": ""
        },
        {
            "Name": "Archive",
            "tid": "6",
            "description": ""
        }

But I want my JSON like this:
[
        {
            "Name": "General discussion",
            "tid": "1",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        },
        {
            "Name": "Miscellaneous - Hangout forums",
            "tid": "2",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        },
        {
            "Name": "Debt Management and Debt Consolidation",
            "tid": "3",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        },
        {
            "Name": "Archive",
            "tid": "6",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        }
]

I had used hook_views_pre_render to alter the JSON but couldn't get it:
function MY_MODULE_views_pre_render(&$view) {
    if($view->name == 'MY_VIEW_NAME') {
        $results = &$view->result;
        foreach($results as $key=>$value) {
            $value->MY_CUSTOM_KEY= "MY CUSTOM VALUE";
        }
    }
}

Try
foreach($results as $key => &$value) {
    $value->MY_CUSTOM_KEY= "MY CUSTOM VALUE";
}


Create webform on node insert? How do you create a webform on a node insert?

I create an event content type and want to automatically add a webform with 3 fields (lastname, firstname, e-mail) on node insert of the event. I do not want the client to add the webform each time he creates an event node. I want a webform per node.

Under /admin/config/content/webform you can enable your event content type for webforms, and the form will be created as part of the node creation process.

Edit: Misunderstood!

Webforms are one-off forms. If I now understand correctly, you want to re-use a standard form on each event page (only one form created).

To do this, create a webform with the required fields, and while editing the form, go to the webform tab > Form Settings. Under Advanced Settings at the bottom select 'Available as Block'.

You can then use the Block settings to display the form on every Event page as required.


Google analytic module - demographic track does not work I am building a drupal 7 site, and using the Google analytics module.

I installed it, and made the needed adjusments on my Google analytic account.

But, when I am on the Demographics tab on Google analytics, I can't see any data regarding the "overview", "Age" and "Gender".
Note: "Track DoubleClick data" was always enabled.

In addition, I get the following message:

Some data in this report may have been removed when a threshold was applied

Learn more

How can I solve this issue?

You will have to enable Track DoubleClick data under the Search and Advertising tab in the GA module settings.  You should also make sure your privacy policy is up to date with the correct info found here.


How do I set descriptions to each checkbox option Is there a way to set descriptions to each checkbox option? What I would like is for Option #1 to display and then directly below it a description for it, then Option #2 along with its description.
I have:

 $form['field_options'] = array(
                    '#type' => 'checkboxes',
                    '#options' => array(
                        0 => t('Option #1'),
                        1 => t('Option #2')),
                    '#title' => t('Select Options'),
                    '#description' => t('Entering a description here will display below the last item in the array'),
                    '#default_value' => array(0)
            );

Also, for some reason $form_state['values']['field_options'] in function hook_node_submit() shows

Array
(
    [0] => 0
    [1] => 0
)

shouldnt it show what the states of the checkboxes are like this?:

Array
(
    [0] => 1
    [1] => 0
)

Thanks

The #title will be displayed as a description next to the checkbox, description below it if you use single checkboxes in a for-loop.

You need to change it a bit:

$options = array('Option 1' => t('Description1'), 'Option2' => t('Description 2');
$i = 1;
foreach ($options as $title => $description) {
    $form['field_options']['option_' . $i]= array(
      '#type' => 'checkbox',
      '#title' => $title,
      '#description' => $description,
      '#default_value' => 0,
    );
  $i++;
}

Set the value with #default_value = 0; (not an array).

About the 0 value in the array: From drupal.org Form API about checkboxes:
Description: Format a set of checkboxes. #options is an associative array, where the key is the #return_value of the checkbox and the value is displayed. The #options array cannot have a 0 key, as it would not be possible to discern checked and unchecked states.


Disable read more link I tried to remove "read more" link from the "basic page" content type.
In Structure -> Content types -> Basic page -> manage display I checked "full content" and unchecked everything else and this didn't help.
Where am I doing mistake?

I found in another question the possibility to edit the template file, but I would rather do it in the settings.

thank you

There is no setting for that.

You can either do it with a preprocess function as explained in Remove the 'read more' and 'Add new comment' links on the home page or you can implement hook_node_view_alter(). Both is possible in a module or in a theme.

The read more link in is added in node_build_content(), and you should be able to remove just that link like this:

function yourmodule_node_view_alter(&$build) {
  if ($build['#node']->type == 'page') {
    unset($build['links']['node']['node-readmore']);
  }
}


Why are spaces in the file path rendered with %2520 instead of %20? I have a custom content entity (service) with a 'file' field defined by:
$fields['file'] = BaseFieldDefinition::create('file')
  ->setLabel(t('File'))
  ->setSettings([
    'file_extensions' => 'pdf',
    'file_directory' => 'sel',
    'description_field' => TRUE,
  ])
  ->setDisplayOptions('view', [
    'type' => 'file',
  ])
  ->setDisplayOptions('form', [
    'type' => 'file',
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

A classic CRUD form allows me to create a service:

Lets say I upload a file with spaces in its name. As you can see if I hover the file name in the form, the link appears to be http://jdp8:8888/sites/default/files/sel/name%20with%20spaces.pdfwith space replaced by %20 and the link works:

So far, so good...
I have a View to display this content entity:

The 'file' field is rendered as a '•' with a link to the file that allows to open the content of the file (a .pdf file) in another window.
When the file name contains spaces, it is rendered as http://jdp8:8888/sites/default/files/sel/name%2520with%2520spaces.pdf with %2520instead of %20.
And of course the links leads to a The requested page was not found error.
I have recently updated Drupal to 8.9.13.
Before I was running Drupal 8.9.1 and I am pretty sure that it was working.
Any idea on what is going wrong? Is it Drupal? Is it Views?
As I suspect Views (everywhere else, it works), here is the way the file field is handled in the view:

I found a kind of workaround: I wrote {{ file__target_id|replace({'%20': " "}) }} in the definition of 'file' field in the view.


Integrating websockets server to the database I'm running a headless Drupal+Angular application where I want to run a server with some clients using WebSockets (and Ratchet). I managed to make a server script detached from Drupal sending messages to multiple Angular apps. Now I want to implement the server to Drupal in order to update an entity and pass the updated entity to all clients.
I'm struggling with the best architecture and what is possible.
Scenario I
Implement the server in a Drupal module in order to access the database directly to get and update the entity and then pass the entity to clients.
Scenario II
The server connects to the database directly, do custom queries and pass the entity to clients.
Scenario III
Create API's where the server can get and update the entity and pass the entity to clients.
For security reasons, I want to avoid Scenario II. Scenario I seem to be the nicest approach, but I'm unsure whether it's possible.

First, Drupal (PHP) makes a lousy websocket server (it’s completely engineered the other way around for it) with php 8 we are getting closer but that’s out of scope for drupal.
But Drupal services (with possibly a JWT or openID Connect endpoint) seems like the best path forwards.
(That would be a variant of option 3)


How do I update core to 8.4? I checked the other questions related to this topic, but half of them didn't get any useful answer and the other half didn't help me out.

I face with several issues building up a site using Drupal 8:

The view exposed date filter doesn't work properly in 8.3.x
The administrative theme doesn't work for roles other than administrator users

I wanted to upgrade a site from 8.3 to 8.4 as most of the patches are provided for 8.4, and I hoped that I would get less troubles.

Drupal 8.4 is just available as development snapshot, at this moment, and Drush didn't let me update the site to this version.

On top of all, the installed Drush version (v8.1.9) is not compatible with Drupal 8.4.

How do I update Drupal to 8.4 using the version of Drush I installed?

Make a database backup.
Make a Drupal code source backup.
I had to know which drush I use:

$ drush version
Drush Version   :  8.1.9

which isn't good for me.
I had to find out whether it is a local or a global installation

$ locate drush
/usr/local/bin/drush
$ dpkg -l | grep drush
rc  drush    5.10.0-2ubuntu1

it looks like the ubuntu package was removed before
and it wasn't installed by pear:

$ pear list

Installed packages, channel pear.php.net:
=========================================
Package          Version State
Archive_Tar      1.4.0   stable
Console_Getopt   1.4.1   stable
HTTP_Request2    2.2.1   stable
Net_URL2         2.2.0   stable
PEAR             1.10.1  stable
PEAR_Manpages    1.10.0  stable
PHP_CodeSniffer  2.5.1   stable
Structures_Graph 1.1.1   stable
XML_Util         1.3.0   stable

So, it can be only a global phar installation.

I chose the WRONG WAY of the installation in the beginning which resulted a lot of more issues (I don't list them here) and finally a drush installation which I wasn't able to update my drupal
Just for the record here is the wrong way: I decided I install drush by composer and if the global version confuses its functionality I will remove the old one from the file system manually
I ran this command from the root directory of my drupal project
$ composer require drush/drush
This installed a lot of other packages and updated my drush from 8.1.9 to 8.1.12. Everything looked good at this point.
$ drush version

Drush Version   :  8.1.12

$ drush up drupal
resulted

Unable to load class \Drush\VersionControl\Backup.

I removed the drush 8.1.12 and installed the drush 9.x version.
I wasn't able to update my drupal site, so I removed the local drush package and its dependencies.

the WORKING WAY
remove the composer version if that exists and install drush globally by phar

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

I updated my drupal from 8.3.4 to 8.3.5
$ drush up drupal
I got the package name of the drupal 8.4 by this command
$ drush dl drupal-8 --select

 [0]  :  Cancel
 [1]  :  8.4.x-dev  -  2017-Jul-22  -  Development
 [2]  :  8.3.5      -  2017-Jul-05  -  Supported, Recommended
 [3]  :  8.3.4      -  2017-Jun-21  -  Security

I chosed 0

I updated my drupal from 8.3.5 to 8.4
$ drush pm-update drupal-8.4.x-dev

Update information last refreshed: Mon, 06/26/2017 - 18:31
 Name    Installed Version  Proposed version  Message
 Drupal  8.3.5              8.4.x-dev         Specified version available

Do you really want to continue? (y/n): y

At the end I got 3 errors, but the update was successful.
Unfortunately the drupal 8.4.x-dev version didn't fix any of my issues.


How to repeat events with the calendar module? I have installed the calendar module. I create a content type call Events and I added a Date field using the Pop-up Calendar control type. So when I create a event node I'm able to give it a Date. So far so good.

Now I need to have something like "repeat every day", "repeat every month", "repeat every year".

Can I accomplish this with the calendar module? Do I need to install another module?

thanks

Check that Date repeat API is checked on your module listing page


htmlLawed in text format corrupts Scald insert in CKEditor module I have htmlawed text format filter. When I enable it for any filter that it is used by any CKEditor profile, it causes corruption for inserted Scald atoms in the CKEditor.

In other words, the following is a correct code for an image atom as shown in CKEDITOR source view:

After changing the text format to a format that it uses htmlawed and saving the node and then edit it again and switching to Rich Text Editor, I got the following code in CKEDITOR source:

This cause alerting an error message:

Just removing htmlawed filter makes ecerything works fine, but this is not an option for me.

I tried the following settings - in the screen shoe - for htmlawed:

However, it does not work as expected to preserve the scald attributes.

I alse tried to change the order of the filter by making it before or after Embedded atoms filter

Where is the mistake?

The solution, simply, is to change a Security setting of the CKEditor profile meant by this issue as follows:

1 - go to `admin/config/content/ckeditor/edit/(TheProfileName)

2 - In Security tab, goto Security Settings and choose Run security filters only when CKEditor is set to start automatically.

Of course, you have to notice that CKEditor in this profile is not started automatically.


what is the meaning of $Id$ at the head of module files? I have seen this line at the head of many files in Drupal modules:

; $Id$

what the meaning of it? What does it do?
Is it important ? Should I put it when I am writing my own module?

Its legacy left behind of a no longer used version control system (CVS) used by Drupal.org/projects before the current  version control system (git) was adopted.

You should not use this when writing your own code.  The automated code checker tool at Drupal.org will actually complain if these are present.

And, btw: Git rules!


Drupal 7 and google maps v3. Which is the module to use ? I need to store lat/lng into a content type for the obviously normal thing: display a google maps. But for the moment I have see that the better modules for google map integration using v2 that it is deprecated.

In my content type I request the others data (street, city, country, county) so I do not need a module that need to insert this data. This because I need to insert this data into a SOLR server.

So, which is the best module for Drupal that use google maps v3 ? Or I need to create one custom that use (for example) gmap3.net's js script ?

Thanks.

M.

The approach should be map agnostic. You need to break things in two parts:

Storing location data
Displaying this data on a map

1) Data storage.

You'll need three modules here:

Address field to store addresses (http://drupal.org/project/addressfield)
Geofield to store latitude/longitude (http://drupal.org/project/geofield)
Geocoder to geocode addresses from addressfield into lat/lon for geofield (http://drupal.org/project/geocoder)

It may look difficult, but it is really easy to configure these three modules to play nicely.

2) Data display.

Now having data stored in database we can choose any display approach we want. Here you have two+ choices:
  - GMap (http://drupal.org/project/gmap)
  - OpenLayers (http://drupal.org/project/openlayers)
  - As a third option, you can have a custom js code which plays with Google Maps

Everything depends on your final goal. OpenLayes plays with different map engines and to me it looks a bit bloated. If you go with GMap you'll get Google Maps V3 support which is better to stick with instead of Google Maps API V2. Google Maps API V2 development has stopped, no new features are being rolled and it can be abandoned at any moment, so why to risk?

Go with custom js maps code if GMap module doesn't give you what you need. But I do really suggest you to look at GMap module a little bit closer.


Multi-language menu's / menu-items setup I might not understand Drupal 8 and the different Multilingual approach completely, but I'm bumping into all sorts of issues.

What I simply want, is a single Menu , containing links from 2 different languages.

To make this happen :

I enabled the Language module, and set-up 1 additional language. Install was done in NL, and I added FR
I enabled the Content Translation module
I checked both 'Content' & 'Menu Link' under, so that I can translate both the Node & the menu title ( admin/config/regional/content-language )
Set the language of the Main Menu to '- Not applicable'. I'm not sure if this is right, but the menu would contain links from 2 languages, so I thought this was best option ( admin/structure/menu/manage/main )

Issue #1 :

When I create a NL node & enable menu-link, all is fine on /nl , but on /fr the menu-link still pops up.
This seems weird, as I have no translation or menu-link for FR.

Issue #2 :

When I click 'Translate' on the NL node, I get the FR edit form. I type my content, and I change the menu link title ( the field is visible & pre-filled with the NL menu link title ).
I now have both a NL & FR version of my node, but my original NL menu link changed with it.
I would assume that automatically , a FR version of my menu link would be created.
However, that's not the case. I have to manually go to Structure > Menus and click 'translate' on my NL menu link

Am I setting up the wrong way ?
Should I go for a separate NL/FR menu ?
Will I have to manually add functionality, to create a menu-item on the fly when I translate a node ?

Has someone done something similar and experienced the same issues? And perhaps have any solutions ?

At the moment it is not possible to translate the menu items in the node form:

  Unfortunately the node form's menu widget was not made ready for menu
  item translations (yet), so if you provide the French menu item title
  there, it will be updated in the original item and not going to create
  a translation. Until that is fixed, use the menu item translation
  process as with the contact menu item.

Drupal 8 multilingual tidbits 20: combination use cases with content and menus

The solution presented by Gábor Hojtsy in the link is to translate the menu in the menu management or use different menus for every language.


How to add custom node field into page title? I have a custom node field I want to add into the page title. How can I do this?

Content type is a property listing and I want to have area size and location printed next to the title.

e.g. Large Mansion 900 sq ft (Chicago)

Location is also a taxonomy term in a dropdown list.

Do I need a preprocess_page function to extract the field and then use page.tpl.php?

A hook_preprocess_page function in your template.php file would certainly be one way to do it:

function MYTHEME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'article') {
    $data = $node->field_custom_field[$node->language][0]['value'];

    $vars['title'] = $vars['title'] . ' ' . $data;
  }
}

In page.tpl.php your $title variable should contain your new string based on the field.

You'll probably want to do a couple of extra checks in there as well, for example making sure the node is of the right type, etc.

EDIT

To address your comments I guess you'd want to do something like this:

$area_size = $node->field_area_size[$node->language][0]['value'];
$location = $node->field_location[$node->language][0]['value'];

$vars['title'] = "$vars[title] $area_size sq ft ($location)";


Generate a fancy PDF certificate from form? Anyone have ideas on how to generate a fancy PDF certificate in drupal based on user-supplied form input? Here's an example of what I want to do here:

http://www.infiniteskills.com/cert/01596

This form just collects a name and build a nice PDF. Not sure if the email address is used for anything (other than perhaps collecting email addresses).

I've attached a screenshot of the final PDF so you can see the result without using the form.

Thanks for any ideas or pointers.

Edit: Adding a link the Drupal certificate module: http://drupal.org/project/certificate

This module requires the print module and seems a little heavy for what I'm trying to do. Also, as far as I can tell, it will only create a PDF from existing HTML page.

You can build a proper fillable PDF form and then use the Fill PDF module to merge it with data from a node or a webform.

Have a look at the demo on the Fill PDF service website.


Block above content should be simple however I have a site where they are wanting to have a block above various pages without having a ton of blocks on the blocks layout page. For example they want a block above the login form on the user login page with a welcome message and or instructions that they can easily edit. They also want another "description block" above other pages that we cannot easily add blocks to without giving them admin access such as editing views etc. Does anyone have suggestions as to a way for me to go? I originally thought of using page manager however page manager does not let you use the main content block within itself when you override the path of an existing page.

There is a number of Block related access modules that can help you:

Block Access allows you to set individual Block permissions. So after you create those Blocks, allow the specific user Role to edit only those particular blocks above Login and other pages.

You might also create a special Region within your theme just for this purpose, and set permissions for that Region blocks with Block Region Permissions.

You can set finer control over the Admin Block pages with Block Content Permissions.


twig call macro in different folder i build a macro that contains a function. The function basically crop a text without catting words. My problem is how to call that twig macro if it is in different folder. if it is i same folder its easy. i just import the twig name. {% import 'croptext.twig' as cropText %}
But since this file contains a useful function all templates will call it so its better to put it in special folder like "tool" or "filter". But i still have any way to call it any help ?

{% macro crop_text(text, len) %}
  {% if text | length < len %}
    {{ text }}
  {% else %}
    {% set break = false %}
    {% set croppedParagraph = '' %}
    {% set paragraph = text | split(' ') %}
    {% set totalLength = 0 %}
    {% for word in paragraph  if not break %}
        {% if totalLength >= len %}
          {% set break = true %}
        {% else %}
          {% set totalLength = totalLength + 1 +  word | length %}
          {% set croppedParagraph = croppedParagraph ~ ' ' ~  word %}
       {% endif %}
    {% endfor %}
    {{ croppedParagraph ~ ' ...' }}
 {% endif %}

{% endmacro %}

The function is working. I think its better to share more code to have a better idea about what i am doing. this is my project structure.

You can call the macro by:

In the same twig Using _self:
From Documentation:

  It's possible to place the macro within the same twig from which you call it. The _self context is used in this case...

{{ _self.crop_text(text, len) }}

From External File using import :
Like the following:
Just move your croptext.twig into yourtheme/templates folder and then you can use the following call in any twig:

{% import '@yourtheme/croptext.twig' as cropText %}

For more information take a look at Macros in Twig Templates documentation.


Form post tag missing I am writing a module which uses a template to output results from a database; these results can be edited. I use a form with a fieldset of submit buttons. Each result has an edit button. I get the buttons rendered but there is no <form> tag so nothing happens when the buttons are hit.
Below is my code. I believe I am missing something fundamental, or there is a better way to do it.

  function eventhistory_menu() {
    $items['personal-history'] = array(
      'title' => 'Event history',
      'page callback' => 'historypage_rendered',
      'access callback' => TRUE,
    );

    return $items;
  }

  function eventhistory_theme() {
    return array(
      'eventhistory_template' => array(
        'variables' => array('output' => NULL, 'hist_form' => NULL),
        'template' => 'eventhistory_template',
      ),
    );
  }

  function historypage_rendered() {
    $output = array(
      '#theme' => 'eventhistory_template',
      '#type' => 'markup',
      '#hist_form' => drupal_get_form('historyEdit_form'),
      '#output' => getHistory(),
    );

    return $output;
  }

 function historyEdit_form($form, &$form_state) {
   $form['#tree'] = TRUE;
   $num_hist = 0;

   $form['history']  = array(
     '#type' => 'fieldset',
   );

   if ($form_state['hist_num']) {
     for ($i = 1; $i <= $form_state['hist_num']; $i++) {
       $form['history']['num' . $i] = array(
         '#value' => 'Edit',
         '#type' => 'submit',
       );
     }
   }

   return $form;
 }

In the template I have print drupal_render($hist_form['history']['num' . $count]);. The buttons show, but they are not surrounded by any <form> tag.

What am I doing wrong?

Your way of implementation is partially wrong. Please try it like that:

function eventhistory_menu() {
  $items['personal-history'] = array(
    'title' => 'Event history',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('eventhistory_edit_form'),
    'theme callback' => 'eventhistory_template',
    'access callback' => TRUE,
  );

  return $items;
}

function eventhistory_theme($existing, $type, $theme, $path) {
  return array(
    'eventhistory_template' => array(
      'variables' => array('output' => NULL, 'hist_form' => NULL),
      'template' => 'eventhistory_template',
    ),
  );
}

function eventhistory_edit_form($form, &$form_state) {
 $form['#tree'] = TRUE;
 $num_hist = 0;

 $form['history']  = array(
   '#type' => 'fieldset',
 );

 if ($form_state['hist_num']) {
   for ($i = 1; $i <= $form_state['hist_num']; $i++) {
     $form['history']['num' . $i] = array(
       '#value' => 'Edit',
       '#type' => 'submit',
     );
   }
 }

 return $form;
}

I've discarded the historypage_rendered function from your code and called the form directly in hook_menu implementation. I also added the theme callback to hook_menu, and also renamed your form function to follow Drupal coding standards.


Google rich snippets, custom content type I use Drupal 7.

I have a custom content type which, among other fields, uses Fivestar ratings.

I would like to have my node content enriched with microdata/microformarts/rdf so that it appears in Google Rich Snippets.

I tried RDF module, but it cannot apply detailed formating at the Fivestar module results, because Fivestar produces rating and number of reviews as one field.

I would like to recreate node.tpl.php, by printing field by field and not just $content.
Also I would like to find out how to break down the fivestar two number results down to each compenents, so that I can put the right microdata in the markup.

More information about rich snippets is at http://www.google.com/support/webmasters/bin/answer.py?answer=99170.

How I can find out the variables and arrays that are used to print the content of a node?

How can I print one by one at node.tpl.php, so that I am able to put the right rich snippets markup in between?

edit: ok, till now I have found about devel module and that I must use dpm($content) inside my node--type.tpl.php. I manage to print render($field_names) of various other fields, but I could not yet understand yet about fivestar module values.

This can be accomplished by printing the values you're self instead of letting fivestar do the default rendering.

Here's an example:

$results = fivestar_get_votes('node', $node->nid, 'tag');
//$results now has everything you need to do microformats

The results will have the average and counts. You can print those variables where ever you like. Also note you probably should disabling the text display on the fivestar widget.

There is also an issue over at http://drupal.org/node/901260.


how to add the radio button intead of checkbox in tableselect drupal 7 How can I add the yes/no radio button instead of check box in the table-select module?

As per Adding checkboxes to a table, you need to set #multiple on the element:

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);


How to alter rendered commerce line item on order entity view? I need to add a column(a "checking logistics picking" link) to each line item on order page(i.e. user/%user/orders/%commerce_order page), but I cannot make it done.
I tried hook_entity_view_alter and hook_block_view_alter, but seems they can only alter order entity view, cannot alter line items part of the order.

How to alter line item on order page?
It became urgent, please help! Thanks.

I know it is a bit late, but here is what I did to modify the line items on an order view.

For my example, I wanted the type field to be displayed, so I altered the view of the commerce_line_item entity using hook_views_pre_view(&$view).  Here the code that have:

switch ($view->name) {
    case 'commerce_line_item_table':
        $view->display['default']->handler->options['fields']['type']['exclude'] = FALSE;

This is all I needed to do since type was already there in the commerce_line_item_table view defined in commerce_line_item.views_default.inc, but if you want to add a field to the view, it would look something like this

        $view->display['default']->handler->options['fields']['type']['id'] = 'type';
        $view->display['default']->handler->options['fields']['type']['table'] = 'commerce_line_item';
        $view->display['default']->handler->options['fields']['type']['field'] = 'type';
        $view->display['default']->handler->options['fields']['type']['relationship'] = 'commerce_line_items_line_item_id';

Please note, that when you later the view for the user/%user/orders/%commerce_order page, it also alters admin/commerce/orders/%commerce_order/view since they both use entity_view


Remove dots ( ... ) from default search results descriptions ( snippet ) I want to remove dots from search results items descriptions to search result page ( Default Search ), i have used Drupal default search for the search result page so how to remove the dots from the search descriptions.

I tried with search and replace function using theme preprocess search result function but no luck.

  theme_preprocess_search_result()

function theme_preprocess_search_result(&$variables) {

  $variables['search_excerpt'] = str_replace("...", "", $variables['snippet']['#markup']);

}

But it's not work as expected,if have any solution please put into comment.

Thanks in advance.

You use incorrect variable name.

Take a look for the search-result.html.twig template.
We have a snippet template variable.

Your code should looks like:

function theme_preprocess_search_result(&$variables) {
  $variables['snippet']['#markup'] = str_replace('…', '', $variables['snippet']['#markup']);
}

Pay attention to …, this is a special symbol, not ... (three dots).


Enabling a new content type in the add new content i have created a new content type but when i go to add content, it does not appear but only appears under content types. I have even tried to clear the caches but all in vein, what could be the cause? i will glad for your help

Go to structure >> Menus >> Navigation (admin/structure/menu/manage/navigation) and make sure to enable the content type link in that list.

Here I'm showing example for Article Content type.


Writing a field formatter for D6 So I'm almost embarrassed to ask this, but it's been so long since I've touched Drupal 6. We've been asked for something which requires another Field Formatter for a File field.

Form the code below, I'm able to select File download formatter in Content Type Display. However, when looking at the rendered page, I see no output for this field.

During drush cc all I see the reponse "TEST ONE" print in the console denoteing that MODULE_theme() is running. But there is not a connection to  theme_MODULE_viewer.

Once I get this wired up, I'm sure I can finish this in a hour, but what am I missing?

<?php
**
* Implementation of hook_field_formatter_info().
*/
function MODULE_field_formatter_info() {
  return array(
    'socf' => array(
      'label' => t('File download formatter'),
      'field types' => array('filefield'),
      'description' => t('TO DO: add description'),
    ),
  );
}

/**
* Implements hook_theme().
*/
function MODULE_theme() {

  print "TEST ONE";

  return array(
    'MODULE_viewer' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

function theme_MODULE_viewer($element) {

  print "TEST TWO";
  return 'Future response here. ';
}

From my understanding hook_theme creates an awareness of theme_MODULE_viewer in the array key MODULE-viewer.

In the Devel Tab, I see that the field contains data in both Load and Render panels.

Well I did this in a slightly different way. By using hook_preprocess_content_field(), I search through all of the fields in a node and do a str_replace() on those items. This does solve my problem but I'm open to a more elegant solution.

function MODULE_preprocess_content_field(&$variables) {

  for ($i=0; $i < count($variables['items']); $i++) {
    $searchfor = variable_get('file_directory_path') . '/special_folder';
    $replacewh = 'portfolio/asset';
    $variables['items'][$i]['filepath'] = str_replace($searchfor, $replacewh, $variables['items'][$i]['filepath']);
    $variables['items'][$i]['view'] = str_replace($searchfor, $replacewh, $variables['items'][$i]['view']);
  }
}

Side note: The path portfolio/asset is part of this same module and defined in hook_menu. I would have preferred to have this done with a field formatter in the above code, but I've got to move on.


Result should return a value greater than or equal to the selected facet Here is the scenario. I have created a facet which list all GPA's (these are decimal numbers). e.g. 2.0, 2.5, 3, 3.5 etc.

What I wanted is when say a user choose 2.5 GPA from the facet, the returned contents should be contents that has a GPA of 2.5 and above.

I have been trying to figure it out using views alone, but I can't get it to work. If It can be done with just views, can you please suggest what to do? Or do you think this can only be achieved by code?

I wasn't able to find answers on how to solve this with Facets alone, or writing custom code which is related to facet API. Honestly, I've been ignoring the most obvious solution to my problem which is Views exposed filter, and this is how I managed to solve my problem:

Create an exposed filter for GPA, which filters result that are greater than or equal to the provided GPA. I made this hidden by default.
I disabled the GPA facet I was using, and wrote my own GPA filter block. It's just a matter of querying the GPA field table, disregarding duplicates.
Wrote a custom script that captures the selected GPA value, from the custom GPA block I created, and then feed it hidden views exposed filter.
I added few more customization to it so that it behaves exactly like the rest of the facets.


How to show order total components in a block? I would like to create a block that shows the current user's order totals including all components, as follows:

 - Subtotal
 - Discount or coupon
 - Sales tax
 - Total

I would be happy with a block that simply renders the footer of the shopping cart view. I've played around with commerce-line-item-summary.tpl.php, but it only renders the number of items in the cart and the total amount. It doesn't have to be a form, just a summary of the shopping cart totals.

I would like to show this block during the checkout process in a sidebar region.

Any ideas how to create this?

Quoting @Clive from the comments above:

  Commerce has a "Commerce Order: Order total" component that can be used in Views- it does exactly what you're looking for.

Thank you!


Pass along field delta value to a rendered entity in an entity reference field I have a field on a node type that references another node type. On the display side, I am setting it to a view mode to be rendered.

What I want to do is add a zebra stripe class. Every other node needs an extra class on its wrapper. I figure this should be done at the field twig level, but how do you pass in a value when it is rendered?

field--field-related-content.html.twig:

{% for item in items %}
  {{ item.content }}
{% endfor %}

In the node view mode template:

      {% include "@mytheme/svg/general/how-to.html.twig" %}

How-To

{{ label }}

      DESCRIPTION HERE

The node is unaware of where it is, so, whats the best way to pass a class? Is that possible? The field.html.twig file in classy wraps the field with a div, but thats not what I need to do here.

I suppose one way to do it is change the field twig to something like:

{% for item in items %}
  {% set classes = '...' %}

    {{ item.content }}

{% endfor %}

But that feels dirty, and doesn't really make it reusable, not to mention I would have to inject the background image url through a field preprocess instead of just handle it in the node rendering.

I did something like this in Drupal 7 and did have caching issues as 4k4 mentioned, but I think the cache issues would be easier to avoid in D8. I think you could do this by creating a new Field Formatter that extends EntityReferenceEntityFormatter.

You should be able to alter just the viewElements() method and add the delta information to the referenced entities. You'll have an issue with the view mode being cached with your delta info. For example, you may have an entity be the first item the first place it's referenced and the second item the second place it's referenced, but it'll be cached from the first call so your delta alterations won't work how you'd expect. I think you can update the #cache settings for the entities and add a new key for the delta. I would start by calling parent::viewElements() and then make a pass through that result to make the alterations (adding the delta value and updating the cache settings). I think this will work, but I still get confused by the different caching layers in D8.

I would still alter the field template for the parent EntityReference field and add the class to a wrapping div rather than on the entity itself. You could create your own template file and add your own theme suggestion to make it more reusable, something like field__zebra, rather than relying on the default theme suggestion you mentioned above, field__my_field_name. I love Display Suite so I would create a Zebra DsFieldTemplate that I could easily reuse on any field I wanted.


Why does CACHE_TEMPORARY have the same value as DRUPAL_NO_CACHE I'm trying to change the cache of my block (hook_block_info_alter) but it seems if I change from CACHE_TEMPORARY to DRUPAL_NO_CACHE, it doesn't make a difference.
Drupal declared them like this:

define('CACHE_TEMPORARY', -1);
define('DRUPAL_NO_CACHE', -1);

Why do we have the same value if they're meant to be different?
How can I change the value in hook_block_info_alter?

They have different uses. CACHE_TEMPORARY and CACHE_PERMANENT are values that cache_set() accepts as its last parameter. DRUPAL_NO_CACHE is used from Drupal only for blocks.

Two variables are allowed to have the same value, and this doesn't create confusion, as long as they are used in different context.

While both the variables have the same value, you should not use them when appropriate, at least because it makes more difficult to upgrade your code to Drupal 8.

In hook_block_info_alter(), as with other hooks for blocks, you should use DRUPAL_NO_CACHE. Keep in mind how the data passed as first argument to the hook is structured. With $blocks['forum']['active']['cache'] = DRUPAL_NO_CACHE; used in hook_block_info_alter(), you would avoid the block showing the active forum posts is cached from Drupal.


Link to exposed filter view? I'm building a block view that shows content related to whatever node is being viewed.  It uses a contextual filter to pull the node author, and then displays content I've tagged as related.  I also have a page view that has an exposed filter so the user can select an author and see all their work.  I want to use the "more" link in views to take the user from the block to the filtered page of that author's work.

Since exposed filters doesn't change the URL, how can I link directly to a view with the correct filter already applied?

While exposed filters don't change the path, they do in fact change the url by adding the filters in there as variables.  As an example, if you had a View with a page display at your/path and an exposed filter that filtered on content type, it would create this url after the exposed filter was selected:

www.example.com/your/path?type=NODETYPE

So, depending on what your exposed filter adds, you can create a link to

www.example.com/your/path/?filter=value

and go there directly.  Just look in your browser afterwards and you should see it, assuming you aren't doing something fun with AJAX here anyway.


How can I find webform e-mail submission values keys? I created a Webform and now I want to send an email on submit to the customer. But I'm not understanding how to take the submission values one by one and use it in the email body.

The submission tokens description says:

  %value[key] - A value without additional formatting. Elements may be
  accessed such as %value[fieldset_a][key_b]. Do not include quotes.

What kind of key the %value array have got? How can I find they?

Here is the answer.

Lets say I've 4 fields in Webform

 Label    -   Field Key

First Name - first_name

Last Name - last_name

Phone Number - phone_number

Message - message

Here is the way to access them in template field

For example if you want to display name as the combination of First Name and Last Name

Name:  %value[first_name] %value[last_name]

Then this appears in mail like

Name: Krishna Mohan

If you want to access a individual field value with Label

For example Phone number

%email[phone_number]

This appears in mail like

Phone Number - 555-555-5225

I've tested this and works great! Hope this helps


add arbitrary descriptions div in a node edit or add form the need seems simple but I don't find anything about this.

I'd like to add descriptions (div class="description"), non related to specific cck fields. I though I could use these to compute informations inside it (to sum up some of the choices of tricky content types) or to show up an information when choosing a particular option (like, to show a "cck description" rather than a true cck widget when using conditionnal field).

template.php does not seems to be the right way : I got a lot of ccks, and a lot of content types, I just cant create a hook for each case I need this is not flexible enough. I suppose.

is there any 'dummy' cck field with just a description array and no widget I could use like a normal cck, and locate as any other cck in my forms ?
or : how could I write a 'cck description' module (I'm ok with php and drupal module simple setup)

Im using D6.x

it sounds like you want a custom div to show for certain form values ... or on some conditional ajaxy thing on the form ...

I would basically use hook_form_alter with a case statement probably, or some use of nested array keys to add #prefix elements into the form.

The simplest example would be:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_content_type_node_add') {
    $form['field_FOO']['#prefix'] = '
a description goes here...
';
  }
}

You said you had a million of these, all over the place ... no big deal. Somewhere in your module as a variable or tucked away in a function:

// A simple array lookup of $form_id => $fields => $descriptions ...
$descriptions_map = array(
  'my_content_type_node_add' => array(
    'field_FOO' => 'a description goes here ....',
     ),
    'field_ANOTHER_BAR' => '...',
  ),
  'some_other_content_type' => array ...,
);

Using this simple lookup table (which could help tidy up your code) ... you then make hook_form_alter use it by looking at the array keys and eventually setting form values ... I'm leaving out an ugly bit of code with for loops and calling like array_keys but ...

$form[$field_key]['#prefix'] = $field_key_description;


Context path conditions I am using Context with Delta and Omega3. I am trying to make the Drupal Commerce Checkout, Review and Complete pages each appear differently.  These are their default paths:

checkout/*
checkout/*/review
checkout/*/complete

The problem is that if you set a condition path to 'checkout/*' in one context then the 'review' and 'complete' condition paths will both be overridden by it.

Is there a way to get separate contexts for each of the 3 pages?

Create 3 different contexts, in each context add path condition and set the paths as follow:

First Context:

checkout/*
~checkout/*/review
~checkout/*/complete

Second Context:

~checkout/*
checkout/*/review
~checkout/*/complete

Third Context:

~checkout/*
~checkout/*/review
checkout/*/complete

According to Context documentation ~ character (tilde) can be used to exclude one or more paths.


Flagging users as spam and giving a reason for doing so I am creating a community site using Drupal7. The users of my site should be able to report other users as spam users. For this I am using the Flag module. I have created a flag called Report User for Abuse, and placed it on the user profile so that other users may report the user by clicking on the flag.

I want that the flagging user should give a small summary for the reason he or she is reporting the other user as spam etc.

Once this was done, I created a view for the site admin which shows him/her all the reported users. The admin may then see the reason, verify it and take appropriate actions.
Am I going in the right way about this or is there any other way as well?

Why not use the Flag Note module.

  Extends the Flag Module to allow users to enter a note when they flag
  a piece of content and eventually build a flag history.

  Usage examples:

  flag nodes or comments for abuse providing a descriptive reason
  flag users as friends leaving a hint

  It's possible to opt to keep old notes even when the content gets
  unflagged


Can we call a custom block inside our hook_block_view()? I have a module of type block.Now based on the user i want to display different blocks .
So i have a written the module but my dilemma is if its possible to call a block(default) inside our custom block? Here's my code m trying !

<?php
/**
 * Implements hook_block_info().
 */
function sample_module_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current Users Of the Drupal Website'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}
function sample_module_block_view($delta = '')
 {

 $block = array();
global $user;
  switch ($delta) {
    case 'current_posts':
      $block['subject'] = t('Logged in User Currently');
$block['content']=$user->name;
      break;
/**
 switch ($delta) {
 case 'current_posts':
global $user;
print "The current user is: ";
print $user->name;
if($user->name == "admin")
print " This Shit Works ";
*/
    }
  return $block;
}
   ?>

Now in block['content'] i want to display another block!
Can somebody lead me to how to do this ? If possible ?

Yes, you can load any block

....
$block['content']= sample_module_block_content();
....
function sample_module_block_content(){
  $block = block_load('module_name', 'block_name');
  return _block_get_renderable_array(_block_render_blocks(array($block)));
}


How do I display/edit the machine name for a View? How do I display/edit the machine name for a View?

Reason for asking is that I tried cloning a view but the name I gave was rejected because it had already been used but I couldn't see where.

You can export view, change values, delete original and import view back.

There is a import option in the views listing page. Just paste this url after your current url and you will see the import views page. By seeing your tags I am assuming you are using Drupal 7, so the given below url will work only for Drupal 7.

Below is the url to be added :

#overlay=admin/structure/views/import

To export view:

go to /admin/structure/views
under 'operations' column click on arrow and select 'export'
copy code and edit/change in external editor
go to /admin/structure/views/import and import changed view You can first delete existing view or select 'Replace an existing view if one exists with the same name' on the import settings –