How to inherit base class dependencies without redefining theme in child class service arguments? The current system
I have a set of services classes that extends the same base class ex:
class NodeHandler extends ContentEntityHandlerBase {}
class ParagraphHandler extends ContentEntityHandlerBase {}

and this base class receives these dependencies:
class ContentEntityHandlerBase extends ControllerBase {

 public function __construct(EntityTypeManager $entityTypeManager, RequestStack $requestStack, PermissionsService $permissionsService, LoggerChannelFactoryInterface $loggerChannelFactory) {
    $this->entityTypeManager = $entityTypeManager;
    $this->request = $requestStack->getCurrentRequest();
    $this->permissionsService = $permissionsService;
    $this->loggerChannelFactory = $loggerChannelFactory;
  }

So for each child class ex:(NodeHandler , ParagraphHandler) I need always to inject the parent class dependencies ex:
services:
  sacd_rest_api.node_handler:
    class: 'Drupal\sacd_rest_api\service\NodeHandler'
    arguments: ['@entity_type.manager','@request_stack','@sacd_user.permissions','@logger.factory']
  sacd_rest_api.parapgraph_handler:
    class: 'Drupal\sacd_rest_api\service\ParapgrapHandler'
    arguments: ['@entity_type.manager','@request_stack','@sacd_user.permissions','@logger.factory']

The problem
I don't want to re-inject the parent dependencies each time I create a service class that extends it unless I want to inject a new dependencies that is not inherited from the Base Class for ex:
services:
  sacd_rest_api.node_handler:
    class: 'Drupal\sacd_rest_api\service\NodeHandler'
  sacd_rest_api.parapgraph_handler:
    class: 'Drupal\sacd_rest_api\service\ParapgrapHandler'

So in order to prevent re-injecting the base class dependencies for all baseClass child service ex: (NodeHandler and ParagraphHandler) so I have use the create() factory method but this doesn't work:
class ContentEntityHandlerBase extends ControllerBase {
 public function __construct(EntityTypeManager $entityTypeManager, RequestStack $requestStack, PermissionsService $permissionsService, LoggerChannelFactoryInterface $loggerChannelFactory) {
    $this->entityTypeManager = $entityTypeManager;
    $this->request = $requestStack->getCurrentRequest();
    $this->permissionsService = $permissionsService;
    $this->loggerChannelFactory = $loggerChannelFactory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('request_stack'),
      $container->get('sacd_user.permissions'),
      $container->get('logger.factory')
    );
  }
}

Question ?
is there any way to ineject the Base Class service , when defining a child class service (NodeHnadler , ParagraphHandler) wihout using the arguments: part in the service definiton ?

The question asks:

Is there any way to inject the Base Class service , when defining a
child class service (NodeHandler , ParagraphHandler) without using the
arguments: part in the service definition

Yes. For example, look in core.services.yml to see how this is done in core Drupal. Most core Drupal plugin managers have a parent service named default_plugin_manager. The default_plugin_manager service is defined like this:
  default_plugin_manager:
    abstract: true
    arguments: ['@container.namespaces', '@cache.discovery', '@module_handler']

As you can see, there are three services injected into the default_plugin_manager service. Because it is declared as "abstract", this service definition is more like an alias or a placeholder - it's simply there to define a set of arguments. Note there's no class associated with this service.
A concrete plugin manager, for example the plugin.manager.block service, is then defined like this:
  plugin.manager.block:
    class: Drupal\Core\Block\BlockManager
    parent: default_plugin_manager
    arguments: ['@logger.channel.default']

This service has FOUR arguments injected; the three defined by the parent default_plugin_manager plus the addition argument defined here.
When you look at the concrete class BlockManager that implements this service, you see that BlockManager has a constructor that looks like this:
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, LoggerInterface $logger) {
...
}

As you can see, this constructor takes four arguments. The first three defined by the default_plugin_manager service and the last one defined by the plugin.manager.block service.
Core Drupal defines a DefaultPluginManager base class which is extended by BlockManager and other plugins. BlockManager accepts all four arguments in its constructor. Note that if the parent (DefaultPluginManager in this case) has a constructor then you need to call that from the subclass constructor. This way many different plugin managers can extend DefaultPluginManager and inherit those three injected services.
In your specific case, your services.yml file might look like this:
  my_parent_service:
    abstract: true
    arguments: ['@entity_type.manager', '@request_stack', '@sacd_user.permissions', '@logger.factory']

  sacd_rest_api.node_handler:
    class: Drupal\sacd_rest_api\service\NodeHandler
    parent: my_parent_service
  sacd_rest_api.parapgraph_handler:
    class: Drupal\sacd_rest_api\service\ParagraphHandler
    parent: my_parent_service

You do not need a create() method anywhere, and you do not need to use ControllerBase at all.


Can I use the function menu_tree() in Drupal 7 to customize a menu and add CSS classes? Can I use the function menu_tree() in Drupal 7 to customize a menu and add CSS classes? I've tried to customize a main_menu by adding CSS classes: Is it the right way?

The easiest way to add custom classes to menu items in Drupal 7 is the Menu Attributes module.

If you really want to do this programmatically, then you can override the theme_menu_link() function in your theme's template.php file. Be sure to read the drupal.org documentation on Overriding Themable Output.


How to check spelling of user typed text in a form textbox I built a form which have a text field for take input from user.

Now I want to implement a spell check module or something which can check spell when user type some word or sentence in the text field. I Googled a lot but didn't find any result for my search. Find spell checker for WYSIWYG editor but not for my search.

How can I implement spell checker for text field in a form.

You can use HTML spellcheck Attribute for the textfield. The spellcheck attribute is new in HTML5.

  The spellcheck attribute specifies whether the element is to have its spelling and grammar checked or not.

You can use this attribute in your textfield like follows. I've tested this and working fine.

  $form['check'] = array(
        '#type' => 'textfield',
        "#attributes" => array("spellcheck" => "true")
      );


How can I recognize when the user is editing or inserting something? I have a form which adds some information. I used hook_form() for inserting and loading data. units/add calls the form to insert data and units/%unitid/edit calls the form to edit data. In hook_form_submit(), how can I recognize when the user is editing or inserting something? Should I use $delta, or is it no longer available in Drupal 7?

Field nid is unset if node is created. Optionally, you can check if arg(1) === 'add'


hook_menu implementation page not found error drupal 7.10 I am trying to figure out why hook_menu implementation is not working anymore after upgrade from 7.4 to 7.10 for a custom module
Menu links were working properly until update to latest version. after update all custom module links are deleted from table menu_links and menu_router.

ex. of one of the menu link:

$items = array();

$items['a/main'] = array(
'page callback' => 'main',
'description' => 'Main front page',
'access callback' => TRUE,
);

return $items;

This code was working properly in 7.4 but not anymore.
Have tried to do all cache clearing, menu_rebuild()... etc. nothing seems to work.

Even tried to copy sample code from hook_menu API page like
    function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
    }

function mymodule_abc_view($ghi = 0, $jkl = '') {
// ...
}

and does not work as well.

So I am wondering if anything changed after 7.4 version or I am really missing obvious details?

Thank you for comments.

Try adding a 'title' to your return array.

I noticed that the D7 menu documentation lists 'Title' as required:

"title": Required. The untranslated title of the menu item.

Now there is a comment on the doc page that claims it is not required.

But That comment is from March 20, 2011.

Perhaps the title is now finally required in a more recent release.

Edit:
Your code from comment:

/** * Implementation menu(). / */
function misite_menu() {
    $items = array();
    $items['a/main'] = array(
             'title' => 'main',
             'page callback' => 'main',
             'description' => t('Main front page'),
             'access callback' => TRUE, );
    return $items;
}

/* * Implementation hook_theme(). */
function misite_theme() {
    return array( 'main' => array (
        'template' => 'main',
        'variables' => array('title' => NULL),
        ),
    );
}

function main() {
    $path = drupal_get_path('module', 'a');
    $title = t('');
    $build['mainelement'] = array( '#theme' => 'main',
                                                '#title' => $title, );
    $output = drupal_render($build);
    return $output;
}

Several observations.
1) I think your inclusion of hook_theme could be causing needless grief. Try getting an example of hook_menu working independent of hook_theme.

2) I wouldn't use 'main' as a page callback name; it may not be conflicting with another function elsewhere but I don't think it is a good idea regardless.

Try this:

function misite_menu() {
    $items = array();
    $items['a/my_main'] = array(
             'title' => 'my_main',
             'page callback' => 'my_main',
             'description' => t('Main front page'),
             'access callback' => TRUE
            );
    return $items;
}

function my_main() {
    $output = 'HERE I AM';
    print($output);
}

Then navigate to a/my_main and see if you can see "HERE I AM". If you can then you know your hook menu is working and that your problem is in your hook_theme.


Advantages of using drupal mobile technology over mobile middlewares This is a very serious question that every one asks. I have a drupal website now which is not mobile ready. I will tell the scenario. We gave a demo to client of kurogo, which we modified to show content from drupal website. So 1st question was, whats the benefit of this over creating mobile ready themes with in drupal. So my question is, will there be any extra benefit of using external mobile middle ware like Kurogo, then developing drupal mobile themes.

You can do everything in Drupal. My recommendation is to run an m.site.com domain (either to a different multi-site or with branching logic in settings.php) that not only changes to a mobile theme, but also switches to an alternative anonymous page cache bucket and sets a few variables for later use.

Then, whether you are using panels or not, you can set ctools page_manager overrides for your homepage, content listings, node views etc. and have these only kick in for the mobile domain. This way you can potentially hit the database less for logged in users by showing simple pages, and you can also switch imagecache/'image styles' to be more appropriate to the device and save on bandwidth.

That way you can get all the output you'd get from Diazo or Kurogo but keep it all in Drupal. Which is you are working in a team of Drupallers, is surely a good thing

Hopefully that little ramble described the approach well enough to be useful ;)

I think the http://drupal.org/project/mobile_tools module contains ways of doing this if you don't know how to write it yourself.


CKEditor scayt Plugin module I'm trying to build a scayt module to be able to use the CKEditor scayt Plugin. I tried to use this module but it did not work for me. https://github.com/nikhildodeja/scayt  I created my own but I get a WSOD when I veiw a node creat page. The module is below. What am I doing wrong?

        <?php

    /**
    * @file
    * Definition of \Drupal\scayt\Plugin\CKEditorPlugin\Scayt.
    */

    namespace Drupal\scayt\Plugin\CKEditorPlugin;

    use Drupal\ckeditor\CKEditorPluginBase;
    use Drupal\editor\Entity\Editor;

    /**
    * Defines the "Scayt" plugin.
    *
    * @CKEditorPlugin(
    *   id = "scayt",
    *   label = @Translation("Scayt CKEditor")
    * )
    */

    class Scayt extends CKEditorPluginBase{

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getDependencies().
    */
    function getDependencies(Editor $editor) {
    return array('panelbutton','floatpanel','menu','menubutton','dialogui','button');
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getLibraries().
    */
    function getLibraries(Editor $editor) {
    return array();
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::isInternal().
    */
    function isInternal() {
    return FALSE;
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getFile().
    */
    function getFile() {
        return 'libraries/scayt/plugin.js';
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginButtonsInterface::getButtons().
    */
    function getButtons() {
    return array(
      'Scayt' => array(
        'label' => t('Spell Check'),
        'image' => 'libraries/scayt/icons/scayt.png',
      ),
    );
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getConfig().
    */
    public function getConfig(Editor $editor) {
    return array();
    }
    }

Without seeing the error it's difficult to know, but you do at least need to extend CKEditorPluginBase rather than PluginBase:

use Drupal\ckeditor\CKEditorPluginBase;

class Scayt extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

Otherwise the required interface methods won't be satisfied.


A way to put a unique ID on a node based on the taxonomy it has? I've been tasked with building a system that assigns job numbers categorized by client. Each job number is made up of a 3 letter abbreviation of the client, the current year, and a numerical number, starting from 0 and counting up for each job created.

For example a job # would look like this: ABC1400001

The 2nd job number under client ABC would be ABC1400002 etc etc

ABC = the abbreviated client name
14 = the current year
00001 = the first job created under client ABC

I'm trying to figure out a way to do something like this with drupal where each node would be a job and each client would be a taxonomy term. Grabbing the "ABC" is easy as it could just be the taxonomy term. 14 is easy as it would just be the year. The part that is tripping me up is how to get that numerical value of 00001, 00002, 00003 etc. Then lets say I had another client named DEF the first job under that client would need to start at 00001 as well. So its not as easy as just appending a node ID on to it unfortunately.

Any ideas on how I could accomplish this?

This looks very possible with the Serial Field module in combination with Rules and Token modules

Serial Field module page reads:

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

  The allocation of serial numbers by this module is atomic. In other
  words, the serial values are unique even when multiple instances of
  the same content type / entity are created simultaneously.


#states hide by radio won't work The problem is all in the title. So here is my code (i cut some part to make it more visible) :

Constructor :

public function __construct() {
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $this->sub_forms['user'] = \Drupal::service('entity.form_builder')->getForm($user);
    }

buildForm :

public function buildForm(array $form, FormStateInterface $form_state) {
        $sub_forms_keys = array_keys($this->sub_forms);
        // INC ALL SUBFORM INTO THE MAIN FORM
        foreach ($this->sub_forms as $key => $sub_form) {
            // REMOVE THE PROCESS CALLBACK
            if (!empty($sub_form['#process'])) {
                unset($sub_form['#process']);
            }

            // ALTER THE SUBFORM
            if ($key == $sub_forms_keys[0]) { // user Alter
                foreach ($sub_form as $field_key => $sub_form_field) { // Pour tous les champs
                    if (substr($field_key, 0, 10) != 'field_user') { // Si ce n'est pas un champ personnalisé friterie
                        unset($sub_form[$field_key]); // Cacher le champ
                    } else if (array_key_exists('widget', $sub_form[$field_key])) { // Si c'est un champ friterie et qu'il dispose d'un widget
                        $sub_form_field_widget = $sub_form[$field_key]['widget'][0];
                        $sub_form_field_widget['#states'] = array(
                            'visible' => array(':input[#edit-proprietaire-0]' => array('checked' => true))
                        );
                        dsm($sub_form_field_widget);
                    }
                }
            }

            // ADD THE SUBFORM INTO THE MAIN FORM
            $form[$key] = [
                '#type' => 'container',
                'form' => $sub_form
            ];
        }
        return $form;
    }

Here is a pastern link of a dsm() of a field to show you the structure and that the #states is include : http://pastebin.com/1a8AqVzm

Then here is the HTML code of the entity i want to focus (it's a radio button) :

<input class="clear-panel-field panel-field-inline container-inline form-radio" data-drupal-selector="edit-proprietaire-0" type="radio" id="edit-proprietaire-0" name="proprietaire" value="0">

'#states' => array(
  'visible' => array(
    ':input[name="your checkbox"]' => array('checked' => TRUE),
  ),
)

add this to the element you want to hide.this will be visible only when the checkbox is checked.


Get the username of a user who is being added to an organic group We're using organic groups, and we'd like to notify an administrator every time someone joins a group.

At the moment, we've set up a trigger for this, and set up an action to send an email. We're using the %username token in the email, but this refers to the username of the person who created the group in the first place, not the username of the person joining.

Is there any way to send an email that includes the username of the person who is joining the group?

I nice and simple way of accomplishing this will be to download the token (http://drupal.org/project/token) module. Once you've downloaded the token module be sure to enable token and token_actions module.

The token module will give you more "tokenize" options besides the default %username.

Now instead of creating a "send email" action create a "send tokenize email" action, this is going to give you a lot more token options to choose from.

The two options we care about are [author-mail] and [mail], in your case author-mail is the group manager email address and [mail] is the email address of the user that's joining the groups.

So add [author-mail] to the recipient option in the action and [mail] to where ever in the body you want to put it.

Now all you have to do is go to the Organic Group trigger page and add the new action we created to the "New user joins a group" trigger. That should do it. If you can't seem to be able to add that option to the trigger check out the triggerunlock module (http://drupal.org/project/triggerunlock) which will fix that problem for you.

Hope this helps.


How can I turn several Fields into a menu via a View? I have 3 text Fields that I use for URLs, attached to a Panel Page. I'd like to create a menu with these URLs.

I've sort of done this with a View, by setting the Contextual Filters to use the node ID, then adding the Fields output and setting the Format to a pre-made Menu format I've used in the past. I've used Rewrite Results to make the  tag.

However, the issue is that all my fields are treated as a single menu item, not 3 individual ones.

Instead of the desired result being something like:

Link Name
Link Name
Link Name

The result I get is:

Link NameLink NameLink Name

Would anyone know how I can iterate through and Format each Field within a View?

OK, so the only way I could do this was to adjust the Features .module file to register both a theme and a CTools plugin:

/**
 * Implements hook_theme().
 */
function mycomponent_theme() {
  return array(
    'mycomponent_links_menu' => array(
      'path' => drupal_get_path('module', 'mycomponent') . '/templates',
      'template' => 'mycomponent_links_menu',
      'variables' => array(
        'config' => array(),
      ),
    ),
  );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mycomponent_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner === 'ctools' && $plugin_type === 'content_types') {
    return 'plugins/content_types';
  }
}

Then, I needed to create an .inc file (mycomponent_links_menu.inc) to enable me to add the menu as a component. On that file I created the plugin, , eg:

$plugin = array(
  'single' => TRUE,
  'title' => t('Link Menu'),
  'description' => t('Displays links.'),
  'category' => t('Mycomponent'),
  'edit form' => 'mycomponent_link_menu_panel_settings',
  'render callback' => 'mycomponent_link_menu_panel_render',
  'defaults' => array(),
  'all contexts' => TRUE,
);

and rendered the panel to a block, grabbing each Field from the node's array:

function mycomponent_link_menu_panel_render($subtype, $conf, $args, $contexts) {
  $node_context = reset($contexts);
  $block = new stdClass();

  $field_text1_items = field_get_items('node', $node_context->data, 'field_text1');
  $field_text2_items = field_get_items('node', $node_context->data, 'field_text2');
  $field_text3_items = field_get_items('node', $node_context->data, 'field_text3')

  $panel_content = array(
    '#theme' => 'mycomponent_links_menu',
    '#config' => array(
      'link_to_something' => l(t('Something'), $field_text1_items [0]['safe_value']),
      'link_to_anotherthing => l(t('Anotherthing'), $field_text2_items [0]['safe_value']),
      'link_to_somthingelse' => l(t('Invision'), $field_text3_items [0]['safe_value']),
    ),
  );

  $block->content = render($panel_content);
  return $block;
}

Then I created a .tpl file that actually wrapped the rendered links in HTML, eg:

  <li class="menu__item">
    <?php print $config['link_to_somthingelse']; ?>
  </li>


Configuration translation is not saved I'm working on a page where the backend needs to work in different languages.

That's why I started translating individual labels in the configuration translation (/admin/config/regional/config-translation). After I looked at the first changes, I realized that the terms were not translated.

I went back to the translation page and see that my changes have been overwritten with the original language again.
So I re-translated and saved the term, which showed a success message. Then I called the translation again and it was again the value of the original language there.

Is the translation generally broken or do I have to do a specific setting?

Bug created by a module. Which enterd the system a bit to early.


Create a node using services with PHP I want to add a new page node using drupal services and REST server.

$postdata = http_build_query(array(
      'type' => 'page',
      'title' => 'aaa',
      'field_test[en][0][value]' => '
test
\n',
      'field_test[en][0][format]' => 'filtered_html'
      )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/json'."\r\n".
                     'Cookie: ' . $sessid."\r\n",
        'content' => $postdata
    )
);

    $context = stream_context_create($opts);
    $contents = file_get_contents($main_url."node", false, $context);

    echo json_encode($contents);

When I run above code I get an error:

Warning: file_get_contents(http://192.168.1.129:80/test/node)
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0
401 Unauthorized:
Missing required argument node in D:\xampp\htdocs\serv\server.php on line 61

I think that you need make an authenticated request, unless you want any user to create nodes.
I have created nodes before using curl. You need enable the "Session authentication", activate the user login action in the resources section of you service, and enable request "application/x-www-form-urlencoded" in the server section.

This is the code

    $base_url = 'http://localhost/endpoint';
    $params = http_build_query(array(
       'username' => 'admin',
       'password' => 'qwerty',
    ));
    // set up the request
    $curl = curl_init($base_url . '/user/login.json');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    // make the request
    $response = curl_exec($curl);
    curl_close($curl);
    $user_data = json_decode($response);
    // login successful
    if (isset($user_data->sessid)) {
      $node_params = http_build_query(array(
        'type' => 'page',
        'title' => 'Test page',
      ));
      // set up the authenticated request
      $curl_node = curl_init($base_url . '/node.json');
      curl_setopt($curl_node, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl_node, CURLOPT_POST, true);
      curl_setopt($curl_node, CURLOPT_POSTFIELDS, $node_params);
      curl_setopt($curl_node, CURLOPT_COOKIE, $user_data->session_name . '=' . $user_data->sessid);
      // make the authenticated request
      $node_response = curl_exec($curl_node);
      curl_close($curl_node);
      var_dump(json_decode($node_response));
    }


Limit size of cachetags table One of the site has fairly large cachetags table at over 418K records. Is there a way to limit the size of this table.
This table is not cleared on cache clear.
Since Drupal 8.4 there has been a way to limit the size of cache tables, as noted in change record. However, these settings do not affect the size of cachetags table. I tried adding the following to the settings.php file, but these don't work.
$settings['database_cache_max_rows']['cachetags'] = 50000;
$settings['database_cache_max_rows']['bins']['cachetags'] = 50000;

Is it safe to limit or purge the cachetags table?
Is there a way to limit the size  of cachetags table without resorting to manually truncating the table?

So it appears that Drupal core neither limits the size of cachetags table and not it provides a mechanism to limit it via a setting, like it offers for other cache bins.
Cachetags table is not cleared on cache reset, neither via web browser no via drush.
There is another issue noted in Drupal core that cachetags table can grow endlessly as has been the case that I have come across.
So a blunt method or periodically cleaning the cachetags need to be performed. Something like follows with drush or direct sql statement via mysql cli client or php-myadmin.
drush sqlq "TRUNCATE cachetags;" -l <uri> --no-interaction


How to implement a Subscribe block functionality? I wonder how to implement a block similar to the block shown below, to integrate with the Subscriptions or Notification module.

Basically it sends emails to user everytime a new article is added.

Any suggestions?

Assuming this question is about D7 (at least), I wouldn't recommend using either of both modules anymore. This because these days there is a way better alternative available, which is the Message Stack. It consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of the modules' object orientated architecture).
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
Attention: the Message Stack is really amazing (I think), but also not obvious to get started with it. Especially if you try to do so only using site building techniques. But after you climbed this Drupal Message ladder, you might not ever want to consider building a site without it ... trust me.


Class not found error on creating a custom service inside a module I want to create a class with list of helper functions, so I created a module and placed the helper functions inside it. I created a service.yml inside that module folder.

services:
  helpers.helpers:
    class: Helpers

Helper class file:

class Helpers {
   public function buildPage($page_template, $template_variables) {
      echo "Dheivamey oru vazhiya"
   }
}

I make it as a dependency inside another module.

dependencies:
  - helpers:helpers

I tried using it inside a controller file like this

public function buildSomePage(Request $request) {
  $helper = \Drupal::service('helpers.helpers');
}

But I am getting a Helpers class not found error. Someone help me before my head explode.

This issue resolved after I included the full namespace from Drupal\module-name and placed the file inside the src folder. I included the namespace earlier, but I missed placing the corresponding "Helper" file in the src directory.


drush inheritance, site-ssh and site-list It's possible I'm going about this all wrong, and I should be setting up my aliases file differently.

We have a set up with 4 load-balanced production servers running the same code and accessing the same database. I want to set up a drush aliases file to access them by a short name and also allow commands to be run on all of them simultaneously. Here's what I have so far, in ~/.drush/cust.aliases.drushrc.php:

<?php
$aliases['production'] = array (
  'root' => '/var/www/cust',
  'uri' => 'www.example.com',
  'databases' => array(
    'default' => array(
      'default' => array(
        'database' => '...',
        'username' => '...',
        'password' => '...',
        'host' => '...',
        'port' => '3306',
        'driver' => 'mysql',
      ),
    ),
  ),
  'site-list' => array(
    'production.1',
    'production.2',
    'production.3',
    'production.4',
  ),
);
$aliases['production.1'] = array (
  'parent' => '@production',
  'remote-host' => '...',
  'site-list' => array(),
);
$aliases['production.2'] = array (
  'parent' => '@production',
  'remote-host' => '...',
);
$aliases['production.3'] = array (
  'parent' => '@production',
  'remote-host' => '...',
);
$aliases['production.4'] = array (
  'parent' => '@production',
  'remote-host' => '...',
);
?>

Now the problem I have is that the site-list variable is being added to the individual definitions, so the site-ssh command thinks that they are a list. I've tried a few things to sort this out, including adding 'site-list' => NULL, 'site-list' => array() and 'site-list' => '' to the the production.x definitions, but this doesn't work since site-ssh just uses isset. Neither do my attempts to use the unset function because the inheritance happens after I've tried to unset it.

The problem here is that Drush will always prefer the non-empty 'site-list' in @production over any empty value you provide in the specific site aliases.  This is regrettable, as it makes it Hard to delete values.

There are a couple of alternatives, though.  The most straightforward solution is to just take advantage of the fact that Drush alias files are executable php.  You can refactor your alias definitions like this:

<?php
$common = array (
  'root' => '/var/www/cust',
  'uri' => 'www.example.com',
  'databases' => array(
    'default' => array(
      'default' => array(
        'database' => '...',
        'username' => '...',
        'password' => '...',
        'host' => '...',
        'port' => '3306',
        'driver' => 'mysql',
      ),
    ),
  ),
);
$aliases['production'] = array (
  'site-list' => array(
    'production.1',
    'production.2',
    'production.3',
    'production.4',
  ),
);
$aliases['production.1'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.2'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.3'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.4'] = array (
  'remote-host' => '...',
) + $common;

Your second option is to take advantage of a Drush feature that automatically creates group aliases for all aliases that are defined in a single alias file.  Start with your alias file definition as you show it in the question above; then:

1) Delete 'site-list' from the 'production' alias.

2) Move the 'production' alias to a different file (I use servers.aliases.drushrc.php to store aliases to all of the servers that I have sites on).

3) Keep the individual site aliases as they are, with 'parent' => '@server.production'.

Once you have done that, you may use @cust as an alias list for all of the aliases defined in cust.aliases.drushrc.php.


Allow users to manage other users but all content is site-wide not based on group I am building a website that requires a UserA to be able create UserB, UserC, etc...and have whatever content they create to be managed by UserA (edit, delete, update, etc...)

However I don't think role based permissions are the way to go. I only want UserA to be able to manage those subusers, not assign them a "manager" role where another manager (say, UserX) has created UserZ and if both UserA and UserX are "managers", UserX can change UserB's content.

It looks like the Subuser module is the way to go, however, it is hardly updated and seems to be incomplete. Is there another module or set of modules that can do the same thing?

Organic groups also gives me the access control I need, however, the content that all users should be site-wide and not actually tied to any group. I don't need a container to keep nodes, just the access control for users to manage other users within their own sphere.

Does any one have any other way in which this can be accomplished?

This could be convoluted but this is how I would do it.

To start with, I would use rules and have either entity reference fields or integer fields for the users and content.

With rules, when the new users are created, USER A is referenced (or their UID in the integer field) using rules.

Then, using rules, every node the new users create have this entity reference (or UID integer) applied to it automatically.

For editing, I would give USER A's role editing permissions and then write a custom module that redirects users from the node edit page if the node's field doesn't match the user's field. (And allow certain roles like admin and also allow the node author).

One benefit of this is that you could create a view for USERS A that only shows nodes they can edit and provide a link per node. And I'd use an intreger field as a preference.

Edit: You could do all of this without any extant contrib modules or rules and just custom code. But I always have rules so it's an obvious go to for me.


Facing Repetition in records when I use multiple relations in Views I am trying to use views fetch the News and Articles for display on my custom content type "Industries". On Industries content type I have node reference fields to the News and Articles content types.

I've added two relationships in 'advanced' section and in Contextual filter selected Content: NID. I also enabled Distinct > pure distinct settings in the query settings section.
View's Snap are Here : http://prntscr.com/b8mrmp

But still the records are repeating. If 6 news and 10 Articles, then each article is listed for each news node.
Result : http://prntscr.com/b8mscg

Have a look at the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.


Conditionally switch jquery version In order to get a necessary jQuery plugin to work I had to upgrade my jQuery version to 1.4.

To do this I installed jquery_update and manually put 1.4 in the module directory.

That's working just fine for the public facing side of my site, but now various AHAH elements (like Views UI or FileField uploads) no longer work on the admin side.

I'd like to use Drupal's jQuery for admin/edit pages, and jquery_update's jQuery for everything else.  What's the least hacky way of doing this?  Or is there a totally different solution for this?

I had to do this recently also. Revert your jquery_update to 1.3.2 (or whatever it provides by default) and follow the instructions at http://drupal.org/node/1058168.

They key is to notice that you load the newer version of jQuery before the <?php print $scripts; ?> in your page.tpl.php.

The final thing you need to do, which is not mentioned there, is to load your jquery plugin in between the new jQuery and the jQuery.noConflict(). This will make it so you don't have to modify the plugin (That pages tells you how to modify the plugin if you can't do this final step).


How to acces gmap markers after map is generated? I've got a problem with Google map markers and I don't find a way to solve it.

I've got a map page view generated with the GMap module where I show certain nodes. I've got also a view block that show some of the same nodes that appear in the map in an unformatted list. What I need is to relate the nodes on the list with their respective markers in the map (so hovering the list change the marker icon or vice versa).

I could relate the nodes with the markers since I've got the exact coordinates of the node which coincide with the marker coordinates (obviously). My problem is that I don't know how to get a list of the existing markers on the map.

From what I've read I should push the markers in an array when they're generated so later I can acces to the markers using the elements in the array, but I couldn't found where does gmap generate the markers. I've tried creating a global array and pushing the markers in the gmap_marker.js inside:

obj.bind('addmarker', function (marker) {
  // ... //
    mymarker.push(marker.marker);
}

but even I can see any result. I tried counting the markers that are generated  with something like countmarkers += 1; but the output is also 0.

Anyone has a clue on hou could I achieve this? Any advice would be appreciated.

  Edit:  Ok, I solved this problem.  It looks like what I did was fine
  and the problem was in the timing of the process. I called:

mymarkers.forEach(function(marker) {
        //funciona OK
        alert(marker.getPosition().lat() + ' - ' + marker.getPosition().lng());
    });

  inside a setTimeout(function(){}); with a 10ms delay. By increasing
  the delay to 5000ms all the markers have enough time to be created and
  I can finally access the markers array.

Here is a quote from the Comparison of mapping modules:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


How to trace Drupal 7 Core Logic Using Netbeans with xdebug? I'd like to understand how Drupal core works by tracing core logic and how functions unfold. I installed Netbeans with xdebugger and started a new project. The project includes drupal installation run on localhost. I read several Netbeans quickstart manuals and began studying core by putting breakpoints. But when I start debugging the project they do not seem to work. Please explain any productive approach for studying drupal 7 core logic using Netbeans with Xdebug?

Thanks!

In my opinion, studying drupal core using netbeans and xdebug is somewhat too overwhelming. Starting in index.php will lead you through the whole bootstrap and other parts which do not need to be studied by someone who is starting to understand drupal. The most important parts to be familiar with are menu system and node system. These two parts are the basic building blocks on which you can build further (entities, taxonomy etc.). To study these, I would recommend the combination of 3 approaches:

Study the documentation

menu - you can start with hook_menu (https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7)
node api hooks (https://api.drupal.org/api/drupal/modules!node!node.api.php/group/node_api_hooks/7)

Study the examples module (https://drupal.org/project/examples) - it provides a lot of very well documented code which you can see in action (by turning on the module and its submodules)
Playing around with your own code snippets (=trying out what you learned)

I think xdebug comes later into this mix because it is a debugging tool (by definition) and even though jumping from function to function, from module to module can give you some understading of the flow of things, it is usually easier to just check it out in the documentation.


Menu Call Back for Ajax not working Below is the code in my module. I want to do an ajax posting to path test_call. But when am doing that am getting a 404 error message.

<?php

function callback_permission() {
  return array(
    'access simple page' => array(
      'title' => t('Access callback'),
      'description' => t('Allow users to access callback'),
    )
  );
}

function callback_menu() {

   $items = array();
   $items['test_call'] = array(

    'page callback' => 'callback_test',
    'access arguments' => array('access simple page'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function callback_test()
{

 return "success";

}

I am

Your menu item looks fine so make sure you've done the usual things, make sure the module is installed and enabled, and make sure you clear Drupal's caches so the menu is rebuilt and your new item can be picked up.

On another note, if this callback is meant for AJAX you probably want to be printing something rather than returning it in your callback function. Something like this:

function callback_test() {
  print 'success';
  drupal_exit();
}


How to detect the region of a block programatically I need to create a custom submit handler when blocks that are assigned to a certain region are saved (whether an existing or a new block)

I am using :

function MY_MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  if ($form['#id'] == 'block-admin-configure'){

    //If the block being saved is in region "Header" then do something
  }

Can someone tell me what to replace my commented line with please ?

You can implement hook_block_save($delta = '', $edit = array()) to execute your custom code.


Redirect after submitting custom entity form I'm working with a custom entity and would like to programmatically set the redirect based on submitted values.

When I set the redirect path however, the user is redirected to the canonical path instead of the path I'm setting in the redirect.

In the file mymodule/src/Form/MyEntityForm.php, I'm doing something like this:

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    // Note: Same results with the order of the next 2 lines reversed.
    parent::submitForm($form, $form_state);
    $form_state->setRedirect('mymodule.overview', ['state' => 'CA']);
  }

So how would I set the destination of an entity form submission dynamically?

Probably you need to override EntityFormInterface::save():

  Form submission handler for the 'save' action.

  Normally this method should be overridden to provide specific messages
  to the user and redirect the form after the entity has been saved.

submitForm() is the first submit handler called and should not be used to override submit actions.


How do I create an AJAX callback to Drupal video link? We have a number of videos which are hosted locally and are simple HTML5 video tags. We want to keep track of play clicks. So to be clear, we don't want to track clicks on the URL, we want click tracks on the video tag.

So I want to write a little jQuery() to get the onclick() and then call a Drupal function to update a Drupal entity to store the # of clicks and their source.

I've written AJAX in other environments (PHPBB, Wordpress) but not Drupal. I guess I'm looking for a 'starter kit' which demonstrates interfacing Drupal CRUD functions with js.

You need a route and callback defined in a hook_menu. Below is a kickstarter not a complete example ;)

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

  // an endpoint to add an entity to the default flag_list
  $items['node/%/play'] = array(
    'page callback' => 'example_module_video_count',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'delivery callback' => 'ajax_deliver',
  );
  return $items;
}

Here is the callback

function example_module_video_count($nid = NULL) {
    /* do you stuff */
    $node = node_load($nid);
    $commands = array();
    /* add some ajax commands if required, look at ajax_command_invoke */
    return array('#type' => 'ajax', '#commands' => $commands);
}

Hit the URL from jQuery.ajax()

$.post("/node/1/play", function(data) {});


Any way to add an associated url redirect to a content view? I want to display the url redirect by which a user entered my site on the commerce orders view so that we can easily see if certain redirects we have set up for direct mails, magazine ads etc have been successful in generating an order. I can't seem to find a way to do this - I'm not a developer so would needs something that can be achieved through the cms.

I know I could do something similar with google analytics/campaigns but I can't use that for this.

Thanks.

Set that variable in the user's $_SESSION and then when an order gets created, check to see if that $_SESSION variable is there when you save a new order and if it is, write it to $order->data.

Alternatively, you can check out Commerce Affiliate which allows you to set up affiliates and provides some extra conditions and actions that you can use. This includes grabbing URL params and storing them on the session.


Create my own slideshow like views_slideshow and views_galleria? I want to create my own slideshow module using view.
I want to use jquery/javascript provided by client and create slider using views.
In short i want to make my own module/slider like views nivo slider

Your question lacks a lot of information about what you already have in place but I'll try my best to answer you. You have a couple of options here.

Clone the nivo_slider implementation an use your own javascript in place of nivo.
Add your JS to the page using drupal_add_js and call the necessary functions to init the js.


Services 3 and node locations I'm trying to create a node via services 3 in Drupal 7. The node os created, but when I try to pass the location parameters in, it does not work. If I pass an lid that already exists, it seems to reference that location; if I try to pass a new lid, the information is not registered.

Is there such thing as a location resource for the services module? THis is the JSON string I am using.

{
"title":"test",
"type":"test_type",
"locations":[
      {
         "lid":"4",
         "name":"",
         "street":"",
         "additional":"",
         "city":"",
         "province":"",
         "postal_code":"",
         "country":"us",
         "latitude":"40.663062",
         "longitude":"-73.969760",
         "source":"1",
         "is_primary":"0",
          "locpick":{
            "user_latitude":"40.663061",
            "user_longitude":"-73.969760"
         },
         "province_name":"",
         "country_name":"United States"
      }
   ],
}

var node = {
                title: "Sample Location",
                body: {
                    und: [{
                          value: 'Sample Body'
                          }]
                },
                field_location_type: {
                    und: [{
                          latitude : '37.4861987023',
                          longitude : '-122.2312',
                          country_name : 'United States',
                          province : 'CA',
                          city: 'My City',
                          postal_code : '12345',
                          name : 'Place Name',
                          }]
                },
                type: 'location',
                language: 'und',
            };

This sets a variable 'node' for Javascript. CCK field is "location_type". All the other parameters are being inserted into the node (city, postal_code,...) , but the Lat/Lon is still not being posted. I suspect that it may be because a node can have many 'locations'. Any help here would be great.

Take a look at the debug log: admin/reports/dblog for the json interaction. You need to turn on Services Debug "Debug mode enabled" located at admin/structure/services/list/api where 'api' is the endpoint.


How to use the D3.JS library for data visualization? What are the available options for using the D3.js library in Drupal for creating data visualizations?

D3.js (Data-Driven Documents) appears to be a charting engine with an ever growing popularity. So I wonder how to somehow use D3.JS as a charting engine.

There are at least 3 contributed modules which may help to use the D3.js library (open source, released under the BSD license) in a Drupal 7 site:

Charts and Graphs:

  Charts and Graphs is an API for developers. It can be extended by third-party modules that want to add their own charting implementations. It does nothing by itself. It should only be installed if some other module requires it.

D3 (Alfa release only):

  creates visualizations as libraries (alpha version only) which allows one to add/remove visualizations, share them between modules, and integrate them with (for example: Views) through library .info files.

The Basic module configuration presentation provides a short intro about how to use the module in combination with Views.
Forena

Comment 7 in issue 2364427 contains an example of a custom module to use the Forena module for creating charts using the d3.js library.
Issue # 2383509 describes the approaches for using D3 with Forena.

If you decide to not use any of these modules, it may help to get started with D3.js integration in Drupal by just looking at the code of these modules. Either to roll your own D3.js cookies via a custom module, or at least to get an idea of the required effort.

The D3.JS Tutorial is a great place for documentation about how to use this library.


Insert image tag in checkboxes list A Form having a form element of term reference with checkboxes widget. I want to insert a image tag with each taxonomy term name,

For example here is the html of taxonomy term reference

< div class="form-item form-type-checkbox
form-item-field-user-interest-und-24">
  < input type="checkbox" id="edit-field-user-interest-und-24"
name="field_user_interest[und][24]" value="24" checked="checked"
class="form-checkbox ajax-processed">
  < label class="option
like-taxonomy-term" for="edit-field-user-interest-und-24">-uejo
< /label>
< /div>

so how can i insert image tag inside div tag so that its html become this

< div class="form-item form-type-checkbox
form-item-field-user-interest-und-24">
  < input type="checkbox" id="edit-field-user-interest-und-24"
name="field_user_interest[und][24]" value="24" checked="checked"
class="form-checkbox ajax-processed">
  < label class="option
like-taxonomy-term" for="edit-field-user-interest-und-24">-uejo
< /label>
< img src="image=path" alt="image-text">
< /div>

You should be able to add a prefix or suffix with the field. See Field Suffix in the Form API, So your code might be:

$form['copy'] = array(
'#type' =>'checkbox',
'#title' => t('my taxonomy term.'),
'#field_suffix' => '<img src="myimg.png" />',
);

You can use field_prefix if you want it to come before.


How can I upload a CSV file and expose it in a "views table" for Drupal 7? I am looking to create a simple table with 3 fields (columns) but at least 25 rows of possible entries.  Then I want to display this in a views table (with pagers etc.)  -  I have done this by creating a content type with 3 custom fields, then filling out 25 of these custom content types (nodes) - then exposing all 25 nodes in a views table to get these results.  However- there should be a simpler way to simply upload a CSV table that is already formatted (in Excel or Spreadsheet or text file) in rows and columns and simply use views to display the data in a simple table.

This would greatly reduce the amount of unnecessary published content as well as the workload to create a simple, searchable table from views.

Any other ways to make this work without hacking into the Drupal Database?

As far as I know the short answer here is you can't. Views is pretty much a query building machine.

The next best thing would be to create a script and/or use some views plugin to mass import your nodes from the CSV document and then present them to a view.

And I am proposing a scripted solution in case your nodes are more than 25. Else you might as well do it by hand :)


Searching way to **not** send mail after user registration I want user from a certain domain to be able to register without approval, while others need te be approved by a user manager.

I defined a rule that after a new user registers, through text comparison on the user's mail address, checking if it is from the "safe" domain, unblocks the user. This works very well, but Drupal will send both the mails:
 - welcome, pending approval and
 - your account has been approved.

Is there a way to achieve that the welcome, pending approval mail is not sent?

Is there a way using rules where you can rule out Drupal actions, like saying: "When this happens, do not take that action?"

Mailcontrol worked like a charm.
If you are looking for the configuration it is right with the Drupal user configuration.

it provides the necessary UI additions for D7 (and D8) to enable site admins to enable/disable any standard Drupal mail


How can I make kint() load faster when debugging twig templates? I've seen quite a bit of discussion about how kint() from the Devel module is difficult to work with because it maxes out PHP memory limits and makes the browser drag. I've heard some thoughts on improving its speed by limiting the number of levels. For example, in settings.php, you can do the following:

require_once DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php';
Kint::$maxLevels = 3;

Any other ways to improve the speed of kint()?

There are two other ways other users have mentioned for setting the max output levels in addition to the settings.php method mentioned in the question, plus a couple other ideas below:

Create a /modules/contrib/devel/kint/kint/config.php file and add / modify the line $_kintSettings['maxLevels'] = 3; (by @mdrummond on Slack)
In a preprocess function, add the following: (by @thpoul on Slack)

kint_require();
Kint::$maxLevels = 3;

Be sure to never click the + sign, that shows the entire tree. Click the block instead. You can click the right arrow to open the output in a new window for easier viewing (like when the output is in a block). (by @cwightrun on Slack)
Instead of using kint(), create a preprocess function and use a debugger to explore the variables. (by @danny_englander on Slack)
Pass kint() a specific variable instead of making it roll through the whole tree (by @No Sssweat below).
If you just need to know what variables exist, you can just view the keys by doing a {% for key, value in _context  %} loop (by @mortendk below)


How to add a Location field in drupal 7 I have my location module enabled but I cannot see a location field while creating a new form.How can I add location field to a content type.

You need to have the Geofield module installed instead. You can then add location information e.g Longitude/Latitude.


How to make "Announce on LinkedIn" on by default? I am using Linkedin module.

I want "Announce on LinkedIn" turned on by default. I am using Feeds module for RSS. It automatically created Feed and Feed Item Content types. RSS content is automatically saved as new node. But that node is not posted in Linkedin. I have to edit the content and manually check "Announce on LinkedIn" to have it posted:

I want it posted automatically. How can I achieve that? Please anyone help to me. Thanks in advance

The issue here is the LinkedIn post functionality is tied to the node form; the form is altered to add the form component & submission hook. However, Feeds isn't using this form so it will never get a chance to process the submission handler.

If you look at the submission handler you can pull out the relevant function, linkedin_put_profile_field(),  to make this happen. Combine this with hook_feeds_after_import(), and you can come up with an implementation that will trigger a LinkedIn post upon a feed import:

function MYMODULE_feeds_after_import(FeedsSource $source) {
  if(function_exists('linkedin_put_profile_field') && isset($source->feed_nid) && $node = node_load($source->feed_nid) {
    $status = variable_get('linkedin_default_format_'. $node->type, '');
    linkedin_put_profile_field($node->uid, 'current-status', $status);
  }
}

Note: there will probably need to be more checks & altercations here based on your needs (e.g. setting the right UID to post as, throttling posting so your feed importing doesn't get marked as spam on LinkedIn).


language back to default language after Ajax reload To simplify the question and maybe reproduce the problem, I made a simplier version of what I am doing. I have a form field with ajax. When it triggers it reloads a small piece of html. In it is t('text in one of tree languages'); If I open the page for the first time the same html is loaded and it is in the correct language. But after the reload from the ajax call it is in the website's default language. This only happens when logged in. It is possible that this has to do with the administrator language module. Any help would very much be appreciated.

Ajax Code at hook_form

function hook_form($form, &$form_state) {
  $form['update'] = array(
    '#value' => t('Update'),
    '#type' => 'button',
    '#ajax' => array(
              'callback' => 'callback_function',
              'wrapper' => 'div-to-replace',
              'method' => 'replace',
              'effect' => 'fade')
  );

  // Other form elements

}

Ajax callback function

function callback_function($form, $form_state) {
    return t('test string that should get translated');
}

The ajax callback should return the dynamic form element (and not directly the value). I've created some sample code where the translated content / string is correct after an ajax reload.

function YOURMODULE_form($form, &$form_state, $file_group)
{
    $form['update'] = array(
        '#value' => t('Update'),
        '#type' => 'button',
        '#ajax' => array(
            'callback' => 'YOURMODULE_form_ajax_cb',
            'wrapper' => 'ajaxWrapper',
            'method' => 'replace',
            'effect' => 'fade'
        )
    );

    $form['ajax'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => 'ajaxWrapper',
        ),
    );

    $form['ajax']['text'] = array(
        '#type' => 'markup',
        '#markup' => t('My translated string'),
    );

    // Rest of the form
}

function YOURMODULE_form_ajax_cb($form, &$form_state)
{
    return $form['ajax'];
}


Is there a module that simply adds an 'add more' AJAX CCK field to a node form? Drupal 7:

So I want to have this type of functionality:

The user needs to be able to add an unlimited, or up to a certain value of cck fields to the node edit form.

Basically, we want to create tutorials, and then add dynamic 'steps' via ajax. (because the amount of steps will always constantly change)

An example would be the poll module.

You can set any field to allow more than one value on the same node. But if you need some kind of a group of fields, which you want to add dynamically, then I would suggest you to have a look at the Field Group module.


Form in a block with results is the same block I have a custom module that uses a form in a block that will be displayed on a node page. This form is used to retrieve datas from a custom table.
What I want to achieve is :

The user arrives on the page : the form is displayed and the 10 lasts items retrieved from the database are also displayed
The user selects a data via the form
The user submits the form
The node page containing the block is refresehed with the 10 new items retrieved from database. I also need the form to be displayed on top of the block with previously selected values selected

I've been able to create a form class extending the FormBase class. Then I've created a block extending BlockBase class. In the build method I  get the form using the Drupal::formBuilder()->getForm() method

public function build(){

$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\my_form');

  return array(
      '#theme' => 'my_theme',
      '#form' => $form,
    );
}

At that step, my node page + the block containing the form is correctly displayed, but I've not been able to render the default 10 last items. I've no idea on how to achieve this since the buildForm method of the form class is supposed to return an array to render the form. I've tried to implement it in the build method of my block :

return array(
      '#theme' => 'my_theme',
      '#items' => $items,
      '#form' => $form,
    );

It works, but after form submission, those first 10 default items are always displayed because the block build them on every refresh. Is there a way to know if the included form has been submitted ?

Concerning the form validation, redirection is definitly not the way I should go since a need the results of the database query to be displayed in the same page / block.

Based on this topic, I feel the $form_state->setRebuild() / $form_state->isRebuilding() methods are the way to go. Do you confirm ?

I've been able to refresh the item list after form submission doing so :

  if ($form_state->isRebuilding()) {
  $myfield_value = $form_state->getValue('myfield ');

  $model = Drupal::service('my_module.model');
  $items = $model->getLastItems(10, $myfield_value );

  return array(
    '#theme' => 'my_theme',
    '#form' => $form,
    '#items' => $items,
  );

}

This works, but only half of the time the form is submitted. The second time it's like it never passes in the if($form_state->isRebuilding()) {} statement. Moreover, the results are nested in the form markup. Maybe it's not the proper way to inject the form...

For information here is an example of my twig markup :

{{ form }}
<div class="row">
    {% for track in tracks %}
        {# print stuff...#}
    {% endfor %}
</div>

To be able to inject the form in the if($form_state->isRebuilding()) statement of the buildForm of the form class, I must wait the form array is completly defined in code... Doing so, I'm unable to set fields values to the ones the user has submitted.

In brief, my questions are :

How can I populate the default items list before the form is submitted ?
How can I properly inject the form from the if($form_state->isRebuilding() statement, so that everything works
How can I set the fields selected values after form submission.

Sorry for this long post, but I'm quite new to the drupal ecosystem, so any help would be greatly appreciated !...

Cheers

PS : I've also read about the BlockBase::blockForm and BlockBase::blockSubmit methods, but as far as I understand, it's more about block configuration froms. Does somebody confirm that ?

Thanks 4k4, the main point I was missing here is that a form is just a specific form of render array... I though it was only possible to define form elements to be rendered. But as you pointed me out, it's possible to define anything one wants to render, like... form result... Since what I need to render is a bit more complicated than simple markup, I've created a new template in my .module file :

function my_module_theme() {
return array(
'my_module_form' => array(
  'variables' => array(
    'form' => array(),
  ),
'template' => 'my-module-form',
),
 'my_module_results' => array(
  'variables' => array(
    'tracks' => array(),
  ),
 }

And then, my buildForm method looks approximately that way :

public function buildForm(array $form, FormStateInterface $form_state) {
// define default values...
$defaultValue = 3;

// define form fied + submit button...
 $form['my_field'] = array(
  '#type' => 'select',
  '#required' => true,
  '#default_value' => $defaultValue,
  '#options' => array(1 => 1, 2 => 2, 3 => 3)
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Go'
);

// define field default value that will be overwritten whe  form is submitted
$my_field_value = 1;

//get submitted value
if ($form_state->isRebuilding()){
    $my_field_value =  $form_state->getValue('my_field');
}

//get datas from database
$results = $model->getResultFromDb($my_field);

 $form['result'] = array(
    '#theme' => 'my_module_results',
    '#results' => $results,
    );

return $form;
}

Then is the "my_module_results" you can use the $results var as in any other template :

  {% for result in results %}

 {{ result.title }}

  {% endfor %}

For the results not to be nested in the "form" markup, I had to build manually the form in its own template and call the result var where I needed the result template to be inserted :

    <form method="{{ form['#method'] }}">
        {{ form.form_build_id }}
        {{ form.form_token }}
        {{ form.form_id }}
        {{ form.my_field }}
        {{ form.submit }}
    </form>

    {{ form.result }}

Not sure it wes the only way to do that, but it works like a charm...

Hope this would help somebody...


Showing content associated with node reference in a view I have created a "Node Reference Field" in a content type named "TV Shows" . ( And it is  referring to another Content Type "Episodes")

I created a view which takes the NID of "TV shows" from Contextual filters . How to  display all the fields of related "Episodes" to that "TV show ."

cheers :)

If I understand correctly, you have a single node (type TV Show) with several related nodes of type Episodes, each Episode node describing an episode of the particular TV show.

If this is correct, this is a common error. Your node reference field should be on the Episode type, and should refer to the TV Show type.

Then a simple view of Episodes with a contextual filter on Node ID will give you what you want. Just make sure the reference goes in the correct direction.


How to specify the file path for the private file system? Environment: Shared hosting, Apache.
Home directory: /home/someuser
Website at: /home/someuser/public_html/stuff
I've spent 2 days trying to get this to work, and realise that as soon as I'm answered it will be blindingly obvious, but I'm failing miserably right now.
I have created a directory in my public_html directory called private_files with a sub-directory called stuff. Both have access rights 755.
I have edited settings.php to include the line:
# $settings['file_private_path']
= '/home/someuser/public_html/private_files/stuff';

I have cleared all caches.
The file system configuration page shows:

Private file system path
Not set

What stunningly stupid mistake am I making? Why is what I'm doing wrong?

In order for this question to be marked as answered, @Clive pointed out here that the problem was the leading # character, which made the 1st line a comment, meaning that the file_private_path was never set.

The correct line should be

$settings['file_private_path'] = '/home/someuser/public_html/private_files/stuff';


Drush 8.0.3 cannot update custom module I have a few custom modules that updates are being served from a D6 site with the Feature Server (fserver) module. Before updating drush, the drush up command on a site would see there were updates for them just fine. Now I get:
$ drush up uni_blocks_antares
Update information last refreshed: Mon, 03/07/2016 - 09:13
Name                Installed Version  Proposed version  Message
uni_blocks_antares  Unknown            Unknown           Specified project not
                                                         found

No code updates available.                                           [ok]

But when I check that module's info it exists.
$ drush pmi uni_blocks_antares
Extension        :  uni_blocks_antares
Project          :  uni_blocks_antares
Type             :  module
Title            :  UNI Blocks Antares
Description      :  This module pulls in the feed of Toolbar and Footer links
                    from the UNI Features website and creates blocks
                    containing those links.
Version          :  7.x-2.7
Package          :  UNI Custom Modules
Core             :  7.x
PHP              :  5.2.4
Status           :  enabled
Path             :  sites/all/modules/custom/uni_blocks_antares
Schema version   :  module has no schema
Files            :  none
Requires         :  none
Required by      :  none
Permissions      :  none
Configure        :  admin/config/content/uni-blocks

I found that updating through the web interface of the site will see an update(version 2.8) and update the module.
How do I get drush up to work again for it?

What I ended up doing was updating drush to 8.0.5 and that solved it.


DrupalSettings are not passing the values from block to js? I have been trying to pass the variables from block to jquery.

In Block.php,

return [
      '#theme' => 'block--exampleblock',
      '#value' => 'test',
      '#attached' => [
        'drupalSettings' => [
          'example' => [
            'data' => $data,
            'color'=> $color,
          ],
        ],
        'library' => [
          'example/examplejs',
        ],
      ],
    ];

and I used the data and color values in js

drupalSettings.example.data;
drupalSettings.example.color;

and belows are added the dependency in the library

dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

After uninstalled and installed the modules, The variables have been passing from block to js.

But After clearing cache or sometimes Its not working.

Its showing an issue like

Uncaught TypeError: Cannot read property 'data' of undefined
    at Object.attach (charts.js?v=1.x:10)
    at drupal.js?v=8.6.16:25
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (drupal.js?v=8.6.16:22)
    at drupal.init.js?v=8.6.16:16
    at HTMLDocument.t (ready.min.js?v=1.0.8:4)

I am not able to fix this issue.

Can anyone help to solve this?

99 % sure it is the way your js file is set. as the above should work. for a test please do this:

(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.testStuff = {
    attach: function (context) {
        alert('yes i am attached');
        console.log(drupalSettings);
        if (drupalSettings.example) {
           console.log(drupalSettings.example);
        }
    }
  };
})(jQuery, Drupal, drupalSettings);

if you don't see that in the log then try this ...

$build = [];
$build['stuff'] = [
  '#theme' => 'block--exampleblock',
  '#value' => 'test',
];
$build['#attached']['drupalSettings']['example'] =  [
        'data' => $data,
        'color'=> $color,
];
$build['#attached']['library'][] = 'example/examplejs';
return $build;

remember to clear your cache too.


Show views active filter values as pills without using Facets I have this requirement where selected filter values need to appear as "pills" on the page with an "x" which, when clicked, would unset the filter and reload the search without that value. I've used Active Facet Pills once before to achieve this. However, the view I'm working with is just a plain vanilla view (no facets). I've done a lot of searching, but nothing seems to come up on how to implement this.
How does one achieve this in D7 views?

Facet API seems to be the common module for Facets in D7.
It seems there is the "Summary" option that is the "pills" feature you're looking for.


How to update disabled modules using Drush? Is there a way to update disabled modules with Drush?

Currently, when I try to update a disabled module with Drush, I get this message:

  Project has no enabled extensions and can't be updated

Enabling the module is not an option as this is a live site, actually many sites. They all run off of the same Drupal code base. Some modules are used by some sites but not others (possibly not on the main site).

If Drush can't handle this, what's an easy alternative for updating modules?

I use:
    drush pm-updatecode --check-disabled
followed by:
    drush @sites updatedb

The --check-disabled option was added 2014-11-04


Blocks disappeared when I changed themes Some blocks are no longer showing under Block Layout (or under custom blocks). Some of the blocks came from views. And the views are still there and in block mode. Another block was of the type "Contact Block".

why does my views-block not appear? And why did the contact block disappear?

All I did was change the default theme to a standard theme. Then I uninstalled the previous theme and removed all its files. Then I put in a new theme and activated it and set it as default.

Just click Place block and in the filter up top, search for them and place them again.


Issues with Composer at module dependencies The Currency module requires Composer dependencies. I am trying to install it with the following command:

composer.phar require drupal/currency

It returns the following error.

  [InvalidArgumentException]
  Could not find package drupal/currency at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

What am I doing wrong?

Furthermore, if I specify the version of currency with composer.phar require drupal/currency:8.x-3.1, I get this error:

  [UnexpectedValueException]
  Could not parse version constraint 8.x-3.1: Invalid version string "8.x-3.1"

Anything is going wrong and I don't know what. The file composer.json and composer.phar are both in root directory of the Drupal installation.

The error message could make you think there isn't any stable release of the module, but since there is a 8.x-3.1 version, that is not the case.

The possible causes are:

composer.phar require drupal/currency is not executed from the directory containing the composer.json file you are using, or the one Drupal comes with
The composer.json file doesn't list as repository the one having drupal/currency as package
The repository listed from the composer.json file as the one containing the drupal/currency package is the wrong one
The composer.json file is referring, in the repositories section, a server that is not anymore active, or where the packagist service has been disabled

Keep in mind that Composer, by default, looks at the packages in https://packagist.org. That is why the composer.json file that comes with Drupal 8.4 contains the following lines.

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

If you were using https://packages.drupal.org/7 for Drupal 8, you would get the wrong modules. If you are using https://packagist.drupal-composer.org, that repository is not anymore working.

Keep also in mind that, if you were previously using https://packagist.drupal-composer.org, and you passed to https://packages.drupal.org/8, the package versions need to be accordingly changed; for example, using https://packages.drupal.org/8, composer require honeypot:1.27 is requiring version 8.x-1.27 of the Honeypot module.


How to run tests in my contrib module? I'm writing a contrib module but I can't find the documentation to run the tests - unit and functional. I know that I'm supposed to use PhpUnit, but I can't find examples of PhpUnit configuration files and more importantly, there is no resource on how to execute functional tests - i.e. having the module tested against a running Drupal instance.

I've been looking at some famous contrib modules like Paragraphs and there is nothing about running tests in their documentation - and no phpunit dependency at all. Which doesn't make sense to me since there are some functional tests implemented.

How are we supposed to provide tests for contrib modules?

You have to include phpunit/phpunit package in composer, alredy done if you took default drupal installation :

composer require phpunit/phpunit --dev

A file should be filled which describe yours testsuites, generally phpunit.xml

It looks like this ./phpunit.xml :

<phpunit bootstrap="web/core/tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">

<php>
  <ini name="error_reporting" value="32767"/>
  <ini name="memory_limit" value="-1"/>
  <env name="SIMPLETEST_BASE_URL" value="http://drupal-8.localhost"/>
  <env name="SIMPLETEST_DB" value="mysql://drupal-8:drupal-8@localhost/drupal-8"/>
  <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/var/www/sites/default/simpletest"/>
</php>
  <testsuites>
    <testsuite name="testname1">
      <directory>web/modules/custom/your_module/tests</directory>
    </testsuite>
    <testsuite name="testname2">
      <directory>web/modules/custom/your_module2/tests</directory>
    </testsuite>
  </testsuites>
</phpunit>

In this example, drupal is located in ./web/ directory with ./vendor/, both in root path (./) .

You can add test for contrib module, but they are already tested (if they contain tests) when authors are pushing their sources to drupal.org ( https://www.drupal.org/pift-ci-job/1339317 ) :

<testsuite name="toolbar">
    <directory>./web/modules/contrib/admin_toolbar/tests/src/FunctionalJavascript</directory>
</testsuite>

Then you can run tests with :

./vendor/phpunit/phpunit/phpunit

To use a specific description file :

./vendor/phpunit/phpunit/phpunit -c phpunit-other.xml

To run a specific testsuite :

./vendor/phpunit/phpunit/phpunit --testsuite=testname1


Is drush required on the remote server to do sql-sync or rsync operations? I am working my way through the Drush chapter in Definitive Guide to Drupal 7 by Apress. I want to sync the mysql database and files to/from my local MAMP developer stack and the remote live server (shared hosting).

Given that the drush rync commands deal with the files and the database, then surely it is not necessary to have to have drush on the remote server? If it has to be on the remote server the I accept that but please explain why. I do appreciate that other drush operations would require it e.g. core-status though but the aforementioned operations I am doing involve just the drupal code and database not anything to do with drush.

Please advise, guides don't state everything and make assumptions sometimes.

Drush is needed on the remote server only to fetch the database credentials for the remote system.  If you declare your databases array in the site alias for your remote systems, then Drush will not need to have Drush installed on the remote machine to work.

I don't remember if I explained this in detail in the book, but there is an example on how to define database records in aliases in the example alias configuration file, example.aliases.drushrc.php.  Also, try running drush @site sa --with-db to see the whole site alias record for the given site with the databases array included.  This won't help you if Drush is not installed on the system where the site is installed, but you can run it on a local site, and edit the result to match the necessary settings for the remote end.


How can I override a node's post date theme? HTML5 provides a time element, and a lot of modern sites are using the time element for their content post dates.

How can I override a node's post date theming, so I can change the rendering from a div element to a time element?

Currently, the markup looks like:

2015-01-17

I want it to render it as:

<time datetime="2015-01-17T12:00">2015-01-17</time>

I would like to handle this in my theme, since I have an Omega 4 subtheme I use as a base theme for client sites and want it to handle the functionality.

I'm using Display Suite, which takes over the node's created timestamp and turns it into a field named post_date.  Therefore, I overrode the field.tpl.php file and named it field--post-date.tpl.php, and added the time element to the markup:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><time datetime="<?php print $datetime; ?>"><?php print render($item); ?></time>

    <?php endforeach; ?>

To get the $datetime variable, I added the following code to theme_preprocess_field():

function mytheme_preprocess_field(&$vars) {
    // check for Display Suite fields.
    if ($vars['element']['#field_type'] != 'ds') {
        return;
    }
    switch ($vars['element']['#field_name']) {
        case 'post_date':
            if ($vars['element']['#entity_type'] != 'node') {
                break;
            }
            $node = $vars['element']['#object'];
            $vars['datetime'] = date_iso8601($node->created);
        break;
    }
}

I'm just handling nodes, and a node always has one created time.  The loop in the tpl file can probably be removed, since there will always be one value.


How can I display the block only to the content types and a specific page? Created a content type.

Name: Cities we serve

Machine name: cities_we_serve

Created a page using views.

Page URL: examplesite.com/blog

Created a block.

I would like to display the block to the above content type and the views pages.

Edited the block as follows:

$nodeType = "Cities We Serve";

// valid node id in view mode
if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE ) {
    $node = node_load(arg(1)); // cached
    if ( ($node->type == $nodeType) OR ($node->nid == blog) ) {
        return TRUE;
    }
}
return FALSE;

Now I see the block on all pages. How can I display the block only to the content types and the blog pages?

There is another way to answer your question, without PHP in the block settings: you can use the Rules block visibility module for this. Here is a quote from its project page:

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

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

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

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

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

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

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the appropriate menu block is shown on the appropriate pages). And combine this with a check in such rule for your specific content type ("Cities we serve").

For an illustration of how to use this module, refer to my answer to "How to show blocks by url, when nodes have multiple paths?". It includes some Rules Components (in Rules export format), which you should replace by your variations to make it match your specific question.

To actually "determine the path structure in rules", you might want to use a Rules Condition using a regular expression. Similar to the Rules Condition in the rule I included in my answer to "How to automatically skip intermediate redirects?".

Using regular expressions opens up many more situations (on top of the Rules block visibility module) where this solution can work. If you're not familiar with Regular Expressions (not obvious ...), then maybe you also want to look at my answer to "How do I suppress a warning or error message for site users?".

Bonus:

This approach does NOT require the PHP filter to be enabled either (which you should try to avoid whenever possible) ... Refer to "PHP in database: bad practice but" for more details about this.


SQL queries with AND/OR conditions I'm transferring SQL statements from a Drupal 5 installation to Drupal 8, and struggling with And/Or condtions. eg given the original SQL:

    SELECT .....
    WHERE .....
          AND classes.description = "Photographer"
          AND (classoptions.description = "Name of photographer here"
           OR classoptions.description = "Not assigned").

I've translated it to:

$query = $this->dbConnection->select('classes');
....etc....
$query->condition('classes.description', 'Photographer');

So far, so good. Then I need an OR condition for

$query->condition('classoptions.description', 'Name of photographer here');
$query->condition('classoptions.description', 'Not assigned');

Looking at documentation on-line, using db_or() is suggested, as in :

$query->condition(db_or()
 ->condition('classoptions.description', 'Name of photographer here');
 ->condition('classoptions.description', 'Not assigned'));

..but this is a) deprecated, b) gives error 'db_or function not found'
The replacement for db_or() is to obtain a new Condition object, but what am I supposed to do with it?  The function

 $query->orConditionGroup();

Will return a new Condition object, and the code

$query->condition(orConditionGroup()
 ->condition('classoptions.description', 'Name of photographer here');
 ->condition('classoptions.description', 'Not assigned'));

Formats a Condition object with the conditions to be ORed just fine.But again, how do I incorporate this into the query?

Have a look how orConditionGroup() is used in core.
For example, in ConfigEntityQueryTest it is used this way:

$query = $this->factory->get('config_query_test', 'AND');
$and_condition_1 = $query->orConditionGroup()
  ->condition('id', '2')
  ->condition('label', $this->entities[0]->label);
$and_condition_2 = $query->orConditionGroup()
  ->condition('id', 1)
  ->condition('label', $this->entities[3]->label);
$this->queryResults = $query
  ->condition($and_condition_1)
  ->condition($and_condition_2)
  ->execute();

I am sure you can apply this to your problem.


Add custom class to link outputted by views I'm using views to output a link. The user gets two fields in which to add the href and the text on the link. I wan't them to be able to put a class on the link as well. How can I do this?

In views I have set a fixed class to all those links, but I wan't to be able to add another class if I wan't to, from the backend.

You can do this on the server side with a Views field tpl.php file, or on the client side with jQuery.

For the server side method, go to your view edit -> Advaced -> Theme:Information -> chose your field you need to create a one template file (in your theme/templates folder):

For example: if your field name is title you will see something similar to this:

Field Content: Title (ID: title): - click on it and cope the code

views-view-field--YOURVIEWNAME--page--title.tpl.php -paste it here

Now you have 3 variables to play with

 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.

Easy way - do it with str_replace function :D

<?php $output = str_replace('<a', '<a class="someclass"', $output); ?>
<?php  print $output; ?>

Also you can play around with($row) and create your own output. To easy development install devel module so you can dpm($row) and see what it contains. or you can print_r($row). have fun <3

Fastest way to do this with jQuery you can simple add class to your fields anchor tag.

$(document).ready(function() {
    $('.your-views-class-name .your-view-field a').addClass('someclass');
}

open firebug(int firefox) and find your view class name and field class name which contains anchor tag and add class to it. You can do this in YOURTHEME - scripts.js or any other js file you want.


In drupal, Show own unpublished comments By default if comment is not approved it is not show to user. In my scenario I want to show own unpublished comment to user in light gray background if comment is not approved

Try the view_unpublished module

  This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.

After installing the module, navigate to your user access page and assign the appropriate permissions to the roles you wish to be able to view unpublished nodes.

Similar module : Comment Access

  Comment Access allows your users to control the comments on their posts. It adds permissions to administer, approve, and delete comments on nodes they create without granting full comment administration access. Permissions are granted by node type, so it's a great way to allow your users to manage comments on their own blogs,


node.html.twig gets cached while other templates do not I disabled cache with the command

  drupal site:mode dev

I have overridden html.html.twig and node.html.twig.

If I change something on html.html.twig and refresh the page, the changes take place.

If I change something on node.html.twig and refresh the page, the changes do not appear, unless I also clear the cache or edit the node.

If I open the same page with a different browser, changes do take place, but if I make another edit and refresh, it won't work.

So I thought of some kind of browser caching, but clearing the caches in Chrome doesn't help.

How can I force Drupal to re-read node.html.twig without clearing the caches or editing a node everytime?

Thanks!

drupal site:mode dev won't turn off all the caches. Tunning caching for dev purpose requires manual changes to the settings.(local.)php.

Open the example.settings.local.php file located in the sites directory and copy its content over to site's settings.(local.)php file.
Focus on the cache bins - in your case render and dynamic_page_cache.

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';


How hidden the user_filter_form to a specific role? How can I hidden with alter_form to hide the user_filter_form in the page of list of users to a specific role?

hook_form_alter() wouldn't actually be the best place for this; the form is actually called in from user_admin() so the best place for your code would be hook_page_alter().

The first thing you should do is create a custom permission that you can assign to the role:

function MYMODULE_permission() {
  return array(
    'access user filter form' =>  array(
      'title' => t('Access User Filter Form')
    ),
  );
}

Then implement hook_page_alter() to hide the form:

function MYMODULE_page_alter(&$page) {
  // Make sure this is the right page
  if (arg(0) == 'admin' && arg(1) == 'people') {
    // Make sure filter form actually exists
    if (isset($page['content']['system_main']['user_filter_form'])) {
      // Check user access
      if (!user_access('access user filter form')) {
        // Deny access to the form if necessary
        $page['content']['system_main']['user_filter_form']['#access'] = FALSE;
      }
    }
  }
}


How do I include a JavaScript library without using a module? Note: I'm very new at using Drupal, so I may be missing something.

I've searched high and low, but I can't seem to find an answer to this.

I've got a custom Drupal theme based on Zen, and I want to include a jQuery plugin (specifically, Lightbox) into a page that needs it (I'm using Panels and Views to create custom landing pages). Frankly, I'd be happy even if I had to include it on the entire site.

I looked at JavaScript Libraries Manager, jQuery Plugins Module, but these didn't seem to be able to include CSS or images, which Lightbox requires.

I tried placed the script and CSS/image files in my theme's folder, and then using the following in mytheme_preprocess_page() in my theme's template.php:

$options = array('group' => JS_THEME);
drupal_add_js(drupal_get_path('theme', 'mytheme') . "/js/jquery.lightbox.js', $options);

This loads the JavaScript file OK, but it doesn't function correctly because it's looking for the images at the web root / (and I didn't include the CSS file, anyway).

I saw an example of using hook_library(), and this looks promising as it allows specification of CSS files as well, but I'm not sure where/how to include this setup code.

Also, I realize that there is a Lightbox module, but because the way that my content types and views are done, I can't add rel="lightbox" to the anchors...

It doesn't sound like you need to hook the theme system or deploy a module, why not try including the paths to Light Box's dependencies in one or more of your template files?

Better yet add the CSS and JS file paths (relative to the theme folder) to your theme's info file.

Stylesheets

Scripts


How to add RDFa to fields in a view? I have installed a Drupal 7 views module called Islandora Solr Views and I can create views from the Islandora solr search results. My next goal is to add some semantic data to these fields but after searching around several days, I still can't find a way to do that.

At the moment the HTML for one of the fields look like this:

  Author:
  Mr LLoyd Marshall

I want to add the following RDFa data the to the field:

        Mr LLoyd Marshall

Is there a module to do that? If not how should I go about achieving this?

According to the post Allow custom attributes on Semantic Field wrapper tags, I wonder if there is a module to do this at the moment.

Look at the Fences modules to change the output of a field to a span as you have here. Then use https://drupal.org/project/semanticviews to wrap the span field with semantic markup.   I'm on my phone gluck