How can you add a field value to css? I know this is possible in views -> style settings of a field, but what if you can't customize the fields?

I would like to add css to the mini calendar from the calendar-module depending on the value of a field called 'field_location'.

So class="fri mini future has-events " becomes class="fri mini future has-events field_location"

I copied the calendar-mini.tpl.php and on line 49 I changed

< td id=" < ?php print $cell['id']; ? >" class="< ?php print $cell['class']; ? >">

into:

< td id=" < ?php print $cell['id']; ? >" class="< ?php print $cell['class'] ' ' . $node->field_location['und'][0]['value']; ? >">

If I use $node = node_load(736); it works, but it adds the 'field_location' of that node to all classes.
I need to place the right 'field_location' in the right class.

Copying out the relevant portion of the template:

  <?php foreach ((array) $rows as $row): ?>

      <?php foreach ($row as $cell): ?>
        <td id="<?php print $cell['id']; ?>" class="<?php print $cell['class']; ?>">
          <?php print $cell['data']; ?>

      <?php endforeach; ?>

  <?php endforeach; ?>

If you want the  wrapping your cell to have an additional class based upon what is inside that cell, you will need to do something like this:

  <?php foreach ((array) $rows as $row): ?>

      <?php foreach ($row as $cell): ?>
        <?php
          $new_class= // grab information out of $cell['data']
        ?>
        <td id="<?php print $cell['id']; ?>" class="<?php print $cell['class'] . ' ' .  $new_class; ?>">
          <?php print $cell['data']; ?>

      <?php endforeach; ?>

  <?php endforeach; ?>

If it's not easy to do, $cell['data'] is probably HTML since it is just being printed, you do have the entire $view object to work with, and there, you can grab stuff out of $view->result and correlate that to these cells.


Implementation of drupal behaviours in drupal garden sites If it possible to implement drupal behaviours in drupal garden site? if yes then what will be the syntax for it?

Drupal behaviors are just javascript functions, so the answer is pretty simple:

If the service you're using allows you to add javascript to your pages, then yes, you can use behaviors. If it doesn't, you can't.

Syntax will be identical unless the service uses a patched version of Drupal core. If you have reason to believe they might do, it would be wise to get in touch with them directly and ask.


page not found on install So i wanted to install Drupal on my local mac. I download drupal 7.12 put its content into my htdocs (i'm running MAMP) goto localhost got through all the steps and his save and it took me to "http://localhost/install.php?profile=standard&locale=en" where i get this message

then if i goto localhost i get this

I can't seem to figure out what went wrong Could some one point me in the right direction ?

I'm not sure exactly what your problem is, but it's probably faster to simply try re-installing again from the start than to troubleshoot your installation.  It's hard to estimate how much time it will take to troubleshoot when you don't know what's wrong but you know roughly how long trying to install it again will take.

Although I use MAMP with Drupal myself, if you're a first-time user it might be easier to try Acquia Dev Desktop, which is an "Apache server in a box" like MAMP but already includes the latest version of Drupal and is ready to go as soon as you install it.  Acquia is a company run by the founder of Drupal so you know you're in good hands.

Alternately, although not specifically a Drupal company, Bitnami offers Drupal as an "Apache server in a box" like MAMP as well as as a virtual machine and as a cloud server on Amazon cloud.

There's also Pantheon, which is a Drupal platform that will let you register an account and create Drupal sites in the cloud for free (note that Pantheon will, however, charge you if you decide to take your site live on their service).

I listed many options; of them all, Acquia Dev Desktop is the simplest to set up and get running.


how to redirect users to a page after login only when a specific menu item is clicked? I have a link "Add a Post" (url: /node/add/mypost) which is not directly accessible to users.

I want to display a menu item titled "Add a Post" so that when users click on it, user goes to login page and THEN goes to "/node/add/post"

I have tried using "logintoboggan" and "rules" modules but these redirect user to "node/add/mypost" EVERYTIME a user logs in - I also have a "log in" only link where I just want the user to come back to home page after logging in.

Question Summary: How to have redirect users to a node add form based on a menu item that they clicked on? (menu item here = separate than the "log in" link)

You could add the link like this:

user/login?destination=node/add/post

after login they'll be sent to the add post form.


Getting book pages in same level like getting child pages I have a book called courses with several subpages, I want to show the list of ot other subpages when one subpage is open.

Example:

-Courses
---Course1
---Course2
---Course3
---course4

I want to show course1, course2 & course3 when course4 is open. I know to get childpages, but have no idea how to get pages in same level. I am using Drupal 7.

If book module is enabled, it also creates a block called "Book navigation". You can display the block in any of the "Region" defined in your theme (e.g. "Sidebar first" in Bartik theme), by visiting http://your-site-url/admin/structure/block.

The block will be displayed(in the selected region) whenever you open the book page. And by default it will show the the book pages at the same level(sibling) pages.


hook_query_alter, AJAX, views_get_view : have to submit twice A view is embedded in a page template via this code. It's AJAX enabled and uses exposed filters which I have to mess around with for business purposes :

$view = views_get_view('rechercher', $reset);
$view->set_display('default');
$view->set_use_ajax(TRUE);

$set_exposed_input  = array();
if (isset($_GET['commune'])) {
  $set_exposed_input['field_commune_value'] = filter_xss($_GET['commune']);
}
if (arg(1) == 646 && ! isset($_GET['raz'])) {
  $set_exposed_input['field_type_vente_value'] = 'LOCA';
} elseif (arg(1) == 645 &&  ! isset($_GET['raz'])) {
  $set_exposed_input['field_type_vente_value'] = 'VENT';
}
if ($set_exposed_input) {
  $view->set_exposed_input($set_exposed_input);
}
$view->execute();
print $view->render();

It works perfectly.

Now the query must be altered via hook_query_alter :

function my_module_views_query_alter(&$view, &$query) {

  // Unrelevant stuff here

  if ($view->name == 'rechercher') {
    $view->query->add_table('field_data_field_cp');
    $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' . $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');
  }

As soon as I uncomment this code, I have to submit the view twice to have the results refreshed.

Except for this, the view behaves as expected (query returns the right data, etc.).

I guess it's some kind of cache and/or form caching issue but can't figure what exactly.

Any help would be appreciated.

EDIT : Some more details

Please forget AJAX : it has nothing to do with it, as the behaviour is exactly the same without it.

One more info : the query is correctly altered on the first filters form submission. Dumping proves it.

So it boils down to something that happens AFTER query altering. The mistery remains as to what and when.

It was some kind of mess with the $_SESSION variable, which I used for independant reasons.

I corrected my code this way :

  if ($view->name == 'rechercher') {
    $view->query->add_table('field_data_field_cp');

// Old code
// $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' .
// $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');

// New code
    $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' . $view->exposed_data['field_commune_value'] . '%', 'LIKE');
  }

... and everything seems to be fine, AJAX and all.

Thanks to Clive for the help.


How do I display a block on a page I simply want to display a table generated from an external database on a page.  In researching this I found it would be easiest to do it by writing a module.  Using a tutorial I created a block module that does what I want, but I can't figure out how to make a block module appear on a normal page. This must be something people do on a regular basis.  This is version 7.

Is there such a thing as a page module rather than a block module?

Thanks,
Jim

Just to extend this a bit, eventually I want to be able to add a select form element and perhaps write a bit of javascript (jQuery calls) to change the query that generates the table, etc.  But for now just to be able to display the table on a node/page would be fine.

There are a couple of ways to tackle this...

If you're coding the node content yourself you can use the following snippet to get the output of a particular block into a string:

$block = block_load($module, $delta);
$render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = render($render_array);

There's the Block Reference module

  Defines a field type Block reference which creates a relationship to a block and allows the block to be displayed as the content of the field. It saves this relationship using the block's bid, not its delta + module.


Other modules like the Devel module? I've just started learning Drupal, and the devel module is great and everything but I had a couple of questions about it:

Is it possible to change the output text when generating article or basic page content? For example, instead of using Latin Lorem Ipsum filler text, I'd like to be able to use something that puts out actual English words, like Candy Ipsum.
I noticed that when generating article content, it will also generate a small image to go with it, but the images are not of a uniform size. Is there any way to set it to use a fixed resolution?
This is more of a personal preference, but the user names it generates are a little hard to work around. Back when I worked with Django, I had whipped up a script that put together random user names using common first and last names I had compiled into a text file. Is it possible to do something like that here?

Any suggestions on how I could go about doing these things? Is there perhaps another module(s) I could use to get these functions?

I believe devel generate uses a pattern like [FIELD_NAME]_devel_generate() when deciding who/what to ask for generated data, and then devel implements those functions itself for the core fields.

Unfortunately I don't really see a way to alter this behaviour as there is no Factory pattern or similar that one could use to instantiate derivative/overridden functionality.

What my team usually does is creating content more to our liking in the install profile. This allows us to gradually build in some basic content that the client will want anyway into the development process, and we use a variable to tag nids that won't be useful one we go live, so that we can easily remove the junk content.

If we stick with using devel, here's what I would do:

Hack the module. The code you are looking for is in devel/devel_generate, and then split up into many files, mostly one for each type of content it creates.
Make the functionality generally useful.
Post a patch in the issue queue saying. "I wanted to use devel like this instead, is there a way to incorporate this into Devel?".


admin only can log from a certain country I want that the admin user to only be able to log in from a certain country, and that the other users that are not administrators will be able to log in from every country.

I would use the Smart IP module (https://www.drupal.org/project/smart_ip), you can add an extra validation on the login form that checks the country (https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_validate/7).

You should check if the username exists on validation, when it exists you can check it's role and when it's the administrator role you make sure only users with the IP of your selected country can log in as admins.

There might be easier ways.


How to search by hierarchical taxonomy in views? I have a view with a Global: Combine fields filter with some fields, one of theese fields is a hiererchical select field of a taxonomy terms. But it doesn't work.

How can I set a search box to search by text in a hiererchical select field (and other fields)?

You can use Chosen Module and it supports for hiererchical select

  By default the module will automatically apply itself to any select
  elements that have more than 20 options, which is a reasonable default
  for which having Chosen will be useful. To change or disable this
  automatic enhancement, you can change the selectors (or remove all
  selectors) from the Apply Chosen to the following elements field on
  the Chosen administration page.


Changing the html and order of system fields(pass/email/locale/etc) of user edit form I have changed a number of forms accessible by users to fit a certain style. To do this I used an #after_build function that adds prefixes and suffixes to fields, as well as a bit of javascript. This was straightforward enough(and I hope the appropriate way to do that, though I'm not sure).

However, coming upon the user edit form, it does not behave as other forms do. The default system fields such as password, locale, email, etc, cannot be reordered and I can't seem to add prefixes or suffixes to them to insert my HTML.

I have read some things about using a template for forms via hook_theme() function, however I could not get Drupal to use my template file for the user profile edit form, though it works just fine for other forms. This was a last resort, however, and I prefer other means if possible.

How do I correctly alter the layout and html of the user profile edit form? Thank you for your time.

The reason the template method was not working on my site was the result of a caching issue.

To use a template file for the user profile form you can put this(or find the existing implementations of the hooks) in your template.php:

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

function yourtheme_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'templates/form--user_profile',
    ),
  );
}

Template file name, in this example, becomes form--user_profile.tpl.php


How to group content in view by taxonomy terms? I have a content type called blogs and in which I referred a Taxonomy term which have three different terms in it.
Now what I want to achieve is three blocks with two recent posts for each taxonomy term.
Which should look like :
||       TERM 1            ||          TERM 2           ||        TERM3        ||

         title1                        title1                     title1
          desc                          desc                       desc

         title2                        title2                     title2
          desc                          desc                       desc

         read more...                  read more...              read more...

I know we can create using seperate blocks each.
I need this to be created in a single block in views if this is possible.
I've tried group by in field settings, but it yields me something like this:
TERM 1

title1
desc

TERM 2

title1
desc
title2
desc
title3
desc

TERM 3

title1
desc

Since I specified 6 nodes to be displayed it displays 6 recent post irrespective of the taxonomy term.

I don't think a single View can you your job.

In the case you have fixed Term a non best practise approach will be to create 3 Views and a custom module

Views:

Create new view without add a page or a block
Add a filter to taxonomy term = 'Term 1'
Limit the results to the desired number, remove pager, add read more link.
Do the same for Term 2 and Term 3

Module:

term_display.info

name = 3 Term display
description = Display the articles of 3 terms
core = 7.x
package = My custom modules
version = 7.x-0.1

term_display.module

<?php
/**
 * Implements hook_block_info().
 */
function term_display_block_info() {
  $blocks['term_display'] = array(
    'info' => t('term display'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function term_display_block_view($delta = '') {
  // Initialize a block array.
  $block = array();
  // In case that we have more that one blocks the $delta will define witch one
  // to render.
  switch ($delta) {
    case 'term_display':

      // Give a block title.
      $block['subject'] = t('Term Display');

      // Tells the theme to render the content using ul list.
      $block['content'] = theme('item_list', array(
        'items' => term_display_create_items(),
        'type' => 'ul',
      ));
      break;
  }
  return $block;
}

/**
 * Create the items that will be render in the block.
 *
 * @return array
 *   Return an array of the block's items.
 */
function term_display_create_items() {
  // Initialize the items that will be rendered.
  $items[] = array(
    'data' =>  'Term 1' . views_embed_view('trem_view_1', 'default'),
  );
  $items[] = array(
    'data' =>  'Term 2' . views_embed_view('trem_view_2', 'default'),
  );
  return $items;
}

All the job is done in term_display_create_items() that embeds the View views_embed_view('VIEWS_MACHINE_NAME', 'DISPLAY_ID');

A better approach will be to give the Term as a parameter to the views_embed_view() and fetch it from the View. So you will have a single View that uses Contextual Filters to give you your results. But follow the above steps and you will find your way ;)

A third and more dynamically solution is using the Views Field Views but it will add a huge overhead to your site + will take more time to build it.


how to use "views field view" for entity reference - Not taxonomy I've got a view of "webinars," that contains an entity reference "speakers" that can have multiple entries. I can't get those entity references and their own fields into the listings for each webinar, correctly.

I've tried to do this with Views Field View module, but every tutorial shows Taxonomy ID is used. I can't. This isn't a taxonomy. I tried using Content ID, but it doesn't work. What the heck am I missing?

I want:

  WEBINAR 1
   speaker1, title, company
   speaker2, title, company

  WEBINAR 2
  speaker 2, title, company
  speaker 3, title, company

You don't need additional modules to introduce data from referenced entities into your views, you can do it with Relationships.

Your question title is about the Views field view module, but your question text reveals what you're really after, so I won't go into the Views field module solution because it's not the best way to go (performance-wise) if you can do it otherwise.

The Entityreference field on your "Webinar" nodes only lists titles of the "Speaker" entity, both on node pages and in Views.

To display information other than Title of the "Speaker" entities within "Webinar" views you have to add a Relationship through the entityreference field. That acts as a bridge to the other tables/data and makes them available for use within views.

In your case you should:

Add a Title field and the "Speaker" entityreference field for your "Webinar" nodes (you probably already have this step)
Edit the Speaker field and under Multiple field settings untick Display all values in the same row.

This will make every speaker display as a separate views row.
Add a Relationship Content referenced from field_speakers (or whatever the field name is in your case), require it if you don't want to see webinars in your results that don't have any speakers selected
Add the "Speaker title" field, it will automatically use the above Relationship
Add the "Speaker company" field, it will automatically use the above Relationship
Under Format Settings set the Grouping field Nr.1 to Title (the Webinar one).

This will take care of the way you want results grouped under each webinar title.
Edit the Title field (Webinar) and set it to Exclude from display and under Style settings set the Customize field and label wrapper HTML to H2 or whatever makes the most sense in your case.


Common meta tag description for a particular content type I am working with meta tag module in drupal8.I want to add common meta title and description for a particular content type.How can i do this?

Visit /admin/config/search/metatag
Click on "+ Add default meta tags" button
On the next page, select the content type or entity you want
Define your defaults there


Getting Bootstrap Carousel to set Active class? I have a Drupal 7 site that has 2 Bootstrap carousels.

One that rotates automatically and takes up the width of the page.
One that has 3 smaller items and only when the page is narrowed (e.g. on mobile device) does it need to rotate.

The first carousel works fine.
The second carousel does rotate until I manually add the "Active" to the class.  Once I do it then begins to auto-rotate between the items.

...

...

...

...

I am trying to figure out how to set one of the items as " active" when the page loads so that if the page is on mobile or resized to small enough it begins to auto-rotate.
I use nodequeue to order the items and bootstrap view to lay them out.
Thank you for any direction you can point me to.

Looks like a bug occurs on this line for the 2nd Carousel where $key never equals $first_key – No Sssweat

That's exactly the answer!

    <?php foreach ($rows as $key => $row): ?>
      <div class="item <?php if ($key == $first_key) {print 'active';
     } ?>">
        <?php print $row ?>

    <?php endforeach ?>

Whoever set up the site or theme commented out the part about printing "active" in the  class list.  Probably so it wouldn't auto-rotate, but unfortunately it also made it become hidden when the screen is made narrow.


How to find meta tag source? I have a site where the conditional,

<!--[if IE]><![endif]-->
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

shows in the header, but I can't figure out where it's coming from. I've checked the template.php, .htaccess, html.tpl.php, common.inc, an everywhere else i can think of.  Any ideas of where this is hiding, or how I can find it would be greatly appreciated.

I was going to check the theme for you but it looks like that's a private theme so I'll try to outline some other places you can check.

The most common places you would find it are html.tpl.php and template.php but it sounds like you've covered those.  If it's not in html.tpl.php then it is likely being added with drupal_add_html_head().

Other places to look outside of the ones you've already checked could be in your /modules folder - looking for any custom modules that came with the theme.  If the tag is being added with drupal_add_html_head() then it could be in a custom module.

If not in template.php, check if the theme uses individual files for preprocess functions.  ie look for html.preprocess.inc or something similar.

The theme might have some *.inc files for random features - you can check those as well.

A quick grep of your theme folder for drupal_add_html_head or X-UA-Compatible would likely get you your answer quickly.


Webform is not sending body as HTML Within the e-mail handlers I've selected the body as 'twig template'.
But no HTML is sent.
I've activated Swiftmailer to send attachments ... is that the problem?

Submitted values:

{{ webform_token('[webform_submission:values]', webform_submission, [], options) }}

 URL: {{ webform_token('[current-page:url]', webform_submission, [], options) }}

 Page name: {{ webform_token('[current-page:title]', webform_submission, [], options) }}

Value in body (email):
Submitted values: *Name* sfd dsf *E-mail* test@test.com [1] *Phone* sdfsdfsdf [2] *VAT* sdfsdfdfs *Question?* Yes *Newsletter* List1, List2, List3 *Message* sdfsdf sdf sdf s dfsdfs URL: https://test.test.com/page/title/subtitle Page name: Pagename [1] test2@test.com [2] tel:sdfsdfsdf

I had similar issue with emails sent from webform module (Drupal 9.0.7 & webform 6.0.0-alpha20), solved using following steps.

Install and enable Mail mail module https://www.drupal.org/project/mimemail
Ensure email format is "Full html" at /admin/config/system/mimemail
Go to /admin/config/system/mailsystem and choose "Mime Mail mailer" for
"Formatter" and "Sender" fields under default mail settings.
In your webform, go to settings-> Email/handlers -> Advanced tab. Make sure "Send email as HTML" is checked.


How to use Entityfieldquery with two field conditions for the same field I need to make a query where the same filed must have one value OR another. Basically:

->fieldCondition($field_example, 'tid', (array) $var1) ... OR
->fieldCondition($field_example, 'tid', (array) $var2)

Already saw some examples using TAG but I really don't understand how it's done.
In alternative, can I use dbquery? Or should I avoid it?

Thanks!

You should be able to use db_or(), something like this:

$or = db_or()
  ->fieldCondition($field_example, 'tid', (array) $var1)
  ->fieldCondition($field_example, 'tid', (array) $var2);
$query->condition($or);

More info here.


Insert user password into e-mail body sent by Rules for Ubercart's order completion I have a Rules for Ubercart

Event: Order Checkout Complete
Do :  Send a mail to a user

I need to insert the password of the user the mail is sent to but there is no token for it.

How can I insert the user password into the mail body set by Rules modules?

This is impossible because Drupal saves hash of passwords in the database, so you can't access the original password.


How can I detect if the current viewed page is administrative? How do I detect whether the user the page is currently viewing, is considered administrative?  An administrative page can be recognized when the administration theme is activated.

In my case I would like to print a notice if this condition is met, and if the user can 'administer modules'.

This can be done with path_is_admin(current_path()).

For example, the following hook implementation can be used.

function mymodule_init() {
  if (user_access('administer modules') && path_is_admin(current_path())) {
      drupal_set_message(t('Message'));
  }
}


How to write session data for another user? I need to switch to another user, create session for him, write data into the session(his UID), save the session id, then switch back to original user and work with the session id.

The account switcher is disabling session and I haven' been able to make it work manually with session or session_manager services.

I'd delete this question but someone might find this useful.

It toke me half a day to figure this thing out and the result feels quite hacky and not Drupal-way in any shape or form but it's the only working solution I have been able to put together. The SessionBag is just a simple wrapper around session information - for my purposes.

/**
   * Creates session for provided user without destroying
   * the current user's session.
   *
   * @see user_login_finalize()
   * @see \Drupal\Core\Session\SessionManager::regenerate()
   *
   * @param int $uid
   *
   * @return \Drupal\foo_auth\SessionBag
   *   Session information.
   */
  public function createSession(int $uid): ?SessionBag {
    $session_options = $this->sessionConfig->getOptions($this->requestStack->getCurrentRequest()) + session_get_cookie_params();
    $session_id = Crypt::randomBytesBase64();

    // @see \Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag
    // @see \Symfony\Component\HttpFoundation\Session\Session::set()
    $data = [
      '_sf2_attributes' => [
        'uid' => $uid
      ]
    ];

    // Special handling for session serialization.
    $current_session = $_SESSION;
    $_SESSION = $data;
    $serialized_data = session_encode();
    $_SESSION = $current_session;

    // @see \Drupal\Core\Session\SessionHandler::write
    try {
      $this->database->insert('sessions')
        ->fields([
          'uid' => $uid,
          'hostname' => $this->requestStack->getCurrentRequest()->getClientIP(),
          'session' => $serialized_data,
          'timestamp' => REQUEST_TIME,
          'sid' => Crypt::hashBase64($session_id)
        ])
        ->execute();
    } catch (\Exception $e) {
      watchdog_exception('foo_auth', $e);
      return NULL;
    }

    return new SessionBag(
      $session_options['name'],
      $session_id,
      $session_options['cookie_lifetime'] + REQUEST_TIME,
      $session_options['path'],
      $session_options['cookie_domain'],
      $session_options['cookie_secure'],
      $session_options['httponly']
    );
  }


How to make EntityListBuilder sortable? When defining custom content entities one can use EntityListBuilder to build a list of those entities for administrative purpose.

By default such entities are ordered by ID, however it is possible to change ordering by overriding EntityListBuilder::getEntityIds(). Nevertheless this is only ordering of the items. But how to make that table sortable (by clicking on column header to sort ascending and descending)?

This is how i sort my entityListBuilder :

i use the method load() :

  public function load() {

    $entity_query = \Drupal::service('entity.query')->get('produits_entity');
    $header = $this->buildHeader();

    $entity_query->pager(50);
    $entity_query->tableSort($header);

    $uids = $entity_query->execute();

    return $this->storage->loadMultiple($uids);
  }

Then i build my header like this :

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {

    $header = array(
        'id' => array(
            'data' => $this->t('N° produit'),
            'field' => 'id',
            'specifier' => 'id',
            'class' => array(RESPONSIVE_PRIORITY_LOW),
        ),
        'nom' => array(
            'data' => $this->t('Nom'),
            'field' => 'name',
            'specifier' => 'name',
        ),

        'prixHT' => array(
            'data' => $this->t('Prix HT'),
            'field' => 'prixHT',
            'specifier' => 'prixHT',
        ),

        'statut' => array(
            'data' => $this->t('Actif'),
            'field' => 'actif',
            'specifier' => 'actif',
        ),

    );

    return $header + parent::buildHeader();
  }

you need to add in your buildHeader() 2 param for each field you want sort :

  name of field and specifier


Link one title to a different page other than its content of a view page I have a Drupal 8's views page in which Title and body of a specific content type is listed. I have enabled the title to link its content (node).

Supose if I have a list of 10 titles with its body listed, is there any way to override the link of one or two titles in order to redirect to a different page rather than its content/node.

I could achieve this by using jquery. I attached a jquery in global library (To add jquery and css to drupal 8 refer this page)

I needed a url redirection while clicking on the link /node/7 from the views field to /another-page. The jquery for which is as follows

$('.view-class a[href$="node/7"]').attr('href', '/another-page');

This selects the anchor tag with the 'view-class' and href attribute value ends with 'node/7' and redirects to '/another-page'


Creating a form using a path argument I'm writing a simple module to handle newsletter subscriptions and I want to create a form which is based on information passed in as a url argument.

Example path: /subscribe/verify/eiurhgiergierugskdfadsf

I'd like to create a form for /subscribe/verify which takes "eiurhgiergierugskdfadsf" as a parameter so that I can lookup the user by that hash value and then populate the form with their subscriber id and other information.

I can't seem to figure out how to get url arguments available in my form function though.

$items['subscribe/verify'] = array(
    'title' => 'Verify Email',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('subscribe_terms_form_verify'),
    'access arguments' => array('access content'),
);

function subscribe_terms_form_verify($unique_id) {
   ...
}

How do I safely get access to the url parameter in my form callback?

You need to introduce the argument as a 'wildcard', and pass it through to your function in the page arguments like so:

$items['subscribe/verify/%'] = array(
  'title' => 'Verify Email',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('subscribe_terms_form_verify', 2),
  'access arguments' => array('access content'),
);

The hook_menu() docs are worth read, they explain wildcards in good detail.

Your form function will have this signature:

function subscribe_terms_form_verify($form, &$form_state, $unique_id) {

}

$form and $form_state are provided as parameters to your form through drupal_get_form(), so the 3rd argument will contain the information passed from the URL.


How do I manipulate votes on a node? I have nodes that I want people to be able to vote on. I am currently using the Rate module for this. My use case also requires me to be able to change vote values on individual nodes if necessary. Please how would I do this?

I do not want to go into the database directly. The end user needs to be able to do this in the Drupal interface. I would also like to be able to restrict to access to this feature to certain roles using the permissions system

Undo/Cancel in individual vote

Head over to relative path /admin/structure/rate, and use the edit link for the rate widget for which you want to be able to Undo/Cancel a vote.

Next, within /admin/structure/rate/id/edit (with id corresponding to the widget you selected), scroll down to the section titled "Interaction". There you'll be able to change the value for "Should a second click on the same button delete the vote?" from "No" to "Yes". Save your changes, and repeat for each of the rating widgets for which you want to enable this facility.

Set or delete votes for selected roles

There doesn't seem to be a Drupal interface for this. However, you may want to use the Services Voting API, which provide Services endpoints (actions) for Voting API module. From its project page:

  You are allowed to get votes as flexible as Voting API allows it.
  You are allowed to set votes as flexible as Voting API allows it.
  You are allowed to delete votes.

From its README.txt:

  After enabling the module as usual...

  Go to admin/people/permissions
  Enable the following permissions for your desired user role(s):

  Retrieve votes
  Set votes
  Delete votes

  Go to admin/structure/services
  Click 'edit' next to your endpoint
  Enable the following resources under the 'votingapi' service:

  select_votes
  set_votes
  delete_votes

And the issue about How to use this services resources? contains an interesting (JSON) samples about how to actually set votes*.


Creating a user reference field based on a similar field on a referenced node I have 2 content types (project and issue), you can think of this as an OG style set up, the child nodes reference the parent node via a node reference field called "project" on the issue node type.

The "project" node type has a user reference field called "members".

I'm trying to build a view to create a user reference field on "issue" called "assignee", I would like to limit the users that may be referenced to the users who are in the "members" field of the project node.

So I've created a user view with a reference type and am playing with adding contextual relationships and references, but I am getting no results. I know this is a pretty complex way to use these modules, and typically I would just write a module to achieve this, but I would really like to do this without writing a new module.

Has anyone ever dealt with anything like this?

Create a view with all users.
Create a relationship of type reverse join to project via the members field.
Create a relationship of type reverse join to issue via the project field.
Add a contextual filter on nid using the second join we created (issue).
Set the view type to "references".
Done :)


Is it possible to replace more than one form element (wrappers) triggered by only one #ajax trigger element? function ajax_example_simplest($form, &$form_state) {

  //This is my ajax trigger element
  $form['element_trigger'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      'callback' => 'ajax_example_simplest_callback',

      /** Q: Can I somehow declare more than one wrapper? **/
      //Say for instance, something like:
      'wrapper' => array('replace_div_1', 'replace_div_2'),

     ),
  );

  //replace_div_1
  $form['element_to_be_replaced_1'] = array(
    '#type' => 'textfield',
    '#title' => t("My conditional field one"),
    '#prefix' => '
',
    '#suffix' => '
',
  );

 //... more form elements here

  //replace_div_2
  $form['element_to_be_replaced_2'] = array(
    '#type' => 'textfield',
    '#title' => t("My conditional field two"),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  return $form;
}

function ajax_example_simplest_callback($form, $form_state) {

  //... do my stuff here

  //normally I would return only the form bit for replacing a single wrapper
  //declared in the trigger element, like this:
  return $form['element_to_be_replaced_blahblah'];

}

Is it possible to return more than one form bit in the callback function telling the AJAX framework that $form['element_to_be_replaced_1'] should replace
 and $form['element_to_be_replaced_2'] should replace
?

Instead of returning the HTML of the single element to update, your ajax callback can return an array of ajax commands. So it can return two ajax_command_replace to replace each element.

function ajax_example_simplest_callback(&$form, $form_state) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#replace_div_1", render($form['element_to_be_replaced_1'])),
      ajax_command_replace("#replace_div_2", render($form['element_to_be_replaced_2']))
    )
  );
}


How To add Comments to Profile 2 with five star rating on parent node I need comments on profile2 but with option to vote on  parent node / profile after posting a comment.

I've tried reply module but it doesnt support besides I'd have to theme it unlike the original comments in drupal. So I tried to implement below solution that was posted here in other question. Unfortunately don't fully understand and in the quotas you Can find two places that need claryfying. Still I'm not sure if this attached node to profile will work with fivestar?

  A nice workaround is to use Rules, Entity reference and Display Suite
  (or views). First, you create a new content type
  'profile_ref_node_type'. Add only comment fields and delete any
  unnesseccary fields.

  You can now create a new node of the type upon creation of the profile
  via rules. Add the 'entity has field' condition to be able to access.

Which field exactly?

  your field. As the action I've used my own PHP code, but you can
  probably use the standard rules as well. My PHP code for creation of
  the node and entity reference:

  $node = new stdClass; $node->type = 'profile_ref_node_type';
  $node->title = 'Profile - [profile2:field-name]'; $node->uid = 1;
  node_object_prepare($node); node_save($node);

  $profile2->field_node = array('und' => array(array('target_id' =>
  $node->nid))); profile2_save($profile2); You then can use this entity
  reference with display suite to show only the comments on that node
  (make a new display type if you want to use multiple fields of your
  node).

I'm not sure what exactly should i do in the DS so it would work.

Mentioned by Marcus,

  You should create an entityreference field from the profile2

Please let me add a picture to explain this sentence in detail,

Using hook_profile2_presave instead of using Rules

Make a node with Fivestar
Add Nid into profile 2

function mymodule_profile2_presave($profile) {
  // is_new is important becase we will add fivestar into mint profile2
  if ($profile->is_new && ($profile->type == 'main')) {
    global $user;
      // Make node for Fivestar and comments
      $node = new stdClass;
      $node->type = 'profile_rate';
      $node->title = 'Rating for the profile';
      node_object_prepare($node);
      $node->language = LANGUAGE_NONE;
      //TODO: Who should be the owner?
      $node->uid = $user->uid;
     // No promote to front
      // Published node
      $node->status = 1;
      $node->promote = 0;
      //  Comments open
      $node->comment = 2;
      // Try to save node
      $node = node_submit($node);
      node_save($node);
      // Save Fivestar NID into profile 2
      $profile->field_article_ref[LANGUAGE_NONE][0] = array('target_id' => $node->nid);
  }
}


How do I set a value based upon other values? I have a content type of product, and want to set the postage cost for the item which is dependent upon length,width,height, weight but also product kind - e.g. hazardous items needing special courier etc. I have a series of prices for the various weights and size limits, so I'm wondering how can I utilise these prices for the postage field automatically.

At the moment, the prices aren't inserted in Drupal, would these prices be better as a separate content-type or as fields inside a courier content-type? If the latter would they be as easy to reference?

This is not for a commerce site, merely somewhere to manage all my stock from all the various suppliers - a product information manager.

If you have a small number of settings to store, you might consider using system_settings_form() to store them in Drupal's variables table. Take a look at the core modules that implement this function for more examples.

If the rates group logically, and/or need to be edited by users, you might make a postage_rates content type with fields on that for the information that changes in addition to any constants set by an admin using the first method. You can then add a entityreference field from you product to the postage_rate.


How to use some code only in the template of selected content types? I have some code (calling JS and CSS) in the head section that I only want to appear if the HTML template is used for the content type 'home page'.

I did it like this in the html template:

<?php if ($variables['node']->type = 'home_page'){ ?>
Code....
<?php } ?>

But if I check the source code of my pages, the code is showing up in all off my pages, not only on the pages that use the 'home page' template.

Any tips, code, links?

PS: I'm not good at PHP (I normally cut and paste)

Typo:

if ($variables['node']->type = 'home_page'){

change it into:

if ($variables['node']->type == 'home_page'){


How can I define the activity and/or case in a CiviCRM-integrated webform? I have a Drupal webform that is integrated to my CiviCRM installation and uses numerous custom fields that are associated with a particular activity type. I want to use the form to allow specific contacts to edit an activity that is part of a pre-existing case.

The contact who will be submitting the webform (contact 1) has an assigned role in the case and a relationship to the case manager. We're using Views to show some data to this contact including a link to the webform. I understand that I can pass a case ID and/or an activity ID into the form via the URL that is presented to the contact in the View, and I can see how I can do this by rewriting the output of one of the Views fields.

The question is: do I need to pass in both the case ID and the activity ID, or is it enough just to pass in the activity ID?

And what should I have as the settings for the case and activity in the CiviCRM tab for the webform?

Case and activity settings are a bit tangled up with each other in the current (v4.9) version of the module...

BUT, I've just committed several changes to 4.x-dev (soon to be released as v4.10) which:

Support multiple activities and multiple cases on a webform
Detach the activity and case tabs from each other so you can more cleanly work with one or the other
Allow you to file an activity on a case without having to go through the entire case configuration on the webform

When I get this into working shape (probably next week) I would love your help testing it out.

And to answer your question, if you are updating an existing activity it should be sufficient to pass the activity id. In the current version this will only work if contact 1 is the creator or target or assignee of the activity. I may be able to make this more flexible in the next version.


How to load theme style(s) in CKEditor? In Drupal 8, how can you have CKEditor load additional stylesheets when using a configured filter format? In Drupal 7, you could give the WYSIWYG module paths to CSS sheets to load, which made the editor text reflect the theme as much as possible. I am not seeing this option.

Here is one way to do it... not sure if there are others (admin based):

/**
 * Implements hook_ckeditor_css_alter().
 *
 * Injects our CSS sheets anytime CKEditor has loaded.
 *
 * @param array $css
 * @param Drupal\editor\Entity\Editor $editor
 */
function mymodule_ckeditor_css_alter(array &$css, Editor $editor) {
  if (!$editor->hasAssociatedFilterFormat()) {
    return;
  }

  $known_formats = [
    'basic_html',
    'full_html'
  ];

  if (in_array($editor->getFilterFormat()->id(), $known_formats)) {
    $css[] = drupal_get_path('theme', 'mytheme') . '/build/css/style.css';
  }
}


How to convert existing taxonomy terms (to ucwords) with Termcase module? I'm using the Termcase module to make all the taxonomy terms ucwords in a specific vocabulary.

It also has the option: Convert the existing terms in this vocabulary immediately

It works for making the term UPPERCASE, lowercase but doesn't work for ucwords although it has the ucwords (propercase) option (first character of each word uppercase).

And if needed this is the related code part in termcase.module:

case TERMCASE_PROPERCASE;
  $words = explode(' ', $original_string);
  foreach ($words as $key => $word) {
    $words[$key] = drupal_ucfirst($word);
  }
  $converted_string = implode(' ', $words);
  break;

What should I do to make all the existing terms ucwords?

Not a perfect solution but this is the way I used to solve the problem while converting terms to ucwords:

If all the letters of terms are lowercase then applying ucwords is working correctly.

Go to the vocabulary page you wanted to convert terms (admin/structure/taxonomy/VOCABULARY_NAME).
Select the "Convert all characters to lowercase" option.
Enable the "Convert the existing terms in this vocabulary immediately."
Save and then it will updates (converts) all the terms to lowercase.
Then select the "Convert the first character of each word to uppercase" option.
Save and then it will updates (converts) all the terms to ucwords.

Done.

original -> step 1-4 -> step 5-6

my first term -> my first term -> My First Term
MY SECOND TERM -> my second term -> My Second Term
My Third Term -> my third term -> My Third Term
mY FourTH TErm -> my fourth term -> My Fourth Term

It works correctly.

(If you directly apply "Convert the first character of each word to uppercase" option to these terms above, the results would become:

original -> ucwords

my first term -> My First Term
MY SECOND TERM -> MY SECOND TERM
My Third Term -> My Third Term
mY FourTH TErm -> MY FourTH TErm

Doesn't work correctly if the words has uppercase letters. So do as I mentioned above (steps 1-6).


Rule to Send email to Admin when user points category reaches a certain value I want to create a rule that sends an email when a user has points for a particular category that reaches a certain value, e.g., 100. Having problems with the condition.
I have a User Points category = Contest.

Rule Event: User was awarded points

1st Condition: Data Comparison Data to compare: [userpoints-transaction:tid], Data value: Contest

2nd Condition:
i)  Tried, Data Comparison, userpoints-transaction:points, equals, 100

ii) Tried, Data Comparison, userpoints-transaction, but not correct option as the value to compare doesn't allow an integer

Action: Send mail, I have email, subject and message.

With just the 1st condition, the Rule works, I get an email when someone gets a point for the Contest category, not for other categories.

Can't figure out a condition so  that will send an email when someone reaches 100 Contest User Points.

Anyone done this?
Thanks

Perhaps you can use the patch that's provided here: https://drupal.org/node/1109992.


render() and theme() fields I would like to assign some content from a node, lets say the body field, into a region. so I cannot theme this content in my node.tpl.php

In the template_process_page(&$vars) i can easily set $page['my_region'] = HTML.

with $vars['node']->body i can access to my body field dada. from there I would like to use the regular theme function to render the body field. to use theme('field',$variables) or render($variables) I need to bring the body-array from:

Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [value] => TEXT
                    [summary] =>
                    [format] => full_html
                    [safe_value] =>  TEXT
                    [safe_summary] =>
                )

        )

)

to sth like:

Array
(
    [#theme] => field
    [#weight] => 1
    [#title] => Body
    [#access] => 1
    [#label_display] => hidden
    [#view_mode] => full
    [#language] => und
    [#field_name] => body
    [#field_type] => text_with_summary
    [#field_translatable] => 0
    [#entity_type] => node
    [#bundle] => article
    [#object] => stdClass Object
        (...)
    [#items] => Array
        (
            [0] => Array
                (
                    [value] => TEXT
                    [summary] =>
                    [format] => full_html
                    [safe_value] => TEXT
                    [safe_summary] =>
                )
        )
    [#formatter] => text_default
    [0] => Array
        (
            [#markup] => TEXT
        )
)

But I don't know how exactly.  how can a generate my field with the second array-achitecture. if possible without more db-queries.

thank you for help!

You are looking for field_attach_view

What you would need to do, with your loaded node is something like this:

$fields = field_attach_view('node', $node, 'full');
$body = $fields['field_body'];


How to deny access to invalid $_GET parameters For example, there is a pager with 10 pages. How to deny access if $_GET['page'] is bigger than 9 or is not numeric?

There's no 'catch-all' method for this sort of thing, but on an individual basis you would probably want to perform a manual check in hook_init() in a custom module:

function MYMODULE_init() {
  if (isset($_GET['page'])) {
    if (!is_numeric($_GET['page']) || $_GET['page'] > 9) {
      drupal_access_denied();
    }
  }
}

I imagine you'll need to add further conditions to the above code to make it more contextual to your specific situation.

EDIT

As MPD mentions it might be better to use drupal_not_found() in place of drupal_access_denied()...it's a better semantic representation of what you're actually doing.


How to see the call stack of the functions being called in a page I am beginning to work on a project that has quite a few modules(around 20) which I am not really familiar with. Is there a tool or suggestion, besides dpm-ing the function name, to detect the functions and modules being used in a random page?

If you want to see the complete callstack of the functions being called, you should set up a debugging environment for doing so.
The quickest way to do is by downloading the Quickstart: Prebuilt Drupal Development Environment, which is a virtual machine copy of preconfigured ubuntu. The netbeans IDE is configured for debugging the Drupal code. It also has an display to look at the callstack at the bottom of the IDE, when in debug mode.

What all is included in it:

Support for Drupal 7 and Drupal 6
Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
Firefox (with developer plugins) and Chrome
Drush, drush make, and custom drush commands
Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
Netbeans and Eclipse, configured with XDebug
XHProf and Webgrind profilers. Emails logged as files
cvs, subversion, git, bazaar

You can have a look at its dedicated youtube channel for helpful screencasts.


Month Year granularity on views exposed filter for a custom table exposed to view I have a custom table exposed to view with a column of type int where I am storing current time stamp. while exposing the custom table I have kept views filter handler as "views_handler_filter_date", but this is not allowing to create expose filter with month and year granularity.How can I get month and year granularity for my date_of_purcahse

Here is the snippet exposing the field to views.

  $data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

In order to get month, year granularity we can use date handler as defined by date module so while exposing field to use it will be all about choosing the right filter handler so I used "date_views_filter_handler_simple" handler.

Code while exposing the custom table field with proper filter handler.

$data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'date_views_filter_handler_simple',
    ),
  );


Ship to multiple addresses on single order We have below requirement,

We can add multiple products to single order(which is normal).
Our client expect a functionality to ship to multiple address in single order. Which means we should have option to add multiple address in single order and based on client's need, different products should ship to different addresses.

Any one has any experience or idea about the implementation? Or we have to write our custom module for the functionality?

This is one of those tasks that take a lot more time on Drupal 7 than Drupal 8, since the Drupal 7 version of Shipping doesn't have native support for multiple shipments.

Your best bet is investigating the Commerce Shipment and Commerce Fulfillment modules, choosing one of them, and then coding the rest.


Create just one .tpl.php file for several nodes? I created these .tpl.php file for two node:

html--node__39.tpl.php
html--node__14.tpl.php

Question: can I create just one file for both node?, something like:

html--node__39&&14.tpl.php

Here is an example to change the template dynamically on node type with a preprocess function. Of course you can also use this based on nids. https://www.drupal.org/node/1142800


How to filter GraphQL query by content language? I am coding Drupal 8/Angular app and Angular is fetching data from Drupal using GraphQL. Everything works fine except now I need to query nodes in a particular language. This is my query:

{
  nodeQuery(filter:
    {conditions: [
      {field: "type", value: "akcia", operator: EQUAL, language: EN},
      {field: "field_datum", value: "2018-02-12T18:00:00", operator: GREATER_THAN_OR_EQUAL}
      {field: "langcode", value: "en", operator: EQUAL}
    ]}
    sort: {field: "field_datum", direction: DESC}
  )
  {
    entities {
      entityLanguage {
        id
      }
      ... on NodeAkcia {
        nid
        langcode {
          value
        }
        title
        fieldDatum {
          value
        }
        body {
          value
        }
        fieldObrazok {
          url
        }
        path {
          alias
          pid
          langcode
          pathauto
        }
      }
    }
  }
}```

Notice the `{field: "langcode", value: "en", operator: EQUAL}` line - that's the best thing I came up with, however, the query returns Slovak version of that node, not the English one.

Is there any better way ho to filter nodes based on their translation?

Your query is almost correct but you need to retrieve the entityTranslation in your entities, something like below for an article in English for example:

 entities {
    ...on NodeArticle {
      entityTranslation(language: EN) {
        entityLabel
      }
    }
  }

See also here for a similar question and answer.


Render array doesn't render children I can't add a form to a node. Using the following code, the generated HTML show only the node. If I return $form, the form is rendered correctly. What is my mistake ?

function hook_menu() {

$items['presse/rss'] = array(

'title' => 'RSS',
'access callback' => TRUE,
'page callback' => 'press_rss_page',
'page arguments' => array('fr'),
'menu_name' => 'nav-fast-links-fr',
'file' => 'press.rss.inc',
'type' => MENU_NORMAL_ITEM,

);

FILE: press.rss.inc

function press_rss_page($lang) {

     $nid = variable_get('press_rss_nid_' . $lang, 0);
     $page = array();
     if ($nid) {
        $page = node_view(node_load($nid));
     }

     $path = $_SERVER['HTTP_HOST'];
     $path .= $lang == 'fr' ? '/presse/rss/' : '/press/rss/';
     $form['#weight'] = 1000;
     $form['container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
     );

     $form['container']['all']['title'] = array(
        '#markup' => '
' . 'All the press room content' . '
',
         );
     $form['container']['all']['text'] = array(
        '#type' => 'textfield',
        '#title' => t('All the feeds', array(), array('context' => 'frontend')),
        '#value' => $path . 'all',
        '#disabled' => TRUE,
        '#id' => 'rss-1',
        '#attributes' => array(
        'onClick' => "this.select();",
        'readonly' => 'readonly',
),

);

  $page['form'] = $form;

   return $page;

}

Return your renderable page build with 2 entries, one for the node and one for the form:

return array(
    'node' => $page,
    'form' => $form,
);


How can I show comments on nodes displayed in a view? I've got a content type with comments enabled for each node, and I've created a view that will just display all nodes of this type.

I'd like it for users to be able to add and view comments in this view. Currently, one solution is to set
Row Style: Nodes, which gives me the full node and the comments; however I want to be able to tweak and control what is displayed on the node (such as shorten the date format, remove some fields).

The other alternative I've tried is to set Row Style: Field, which gives me control on what fields to display, but I can't see any way of getting comment functionality to appear.

What's the best way to address this problem?

My suggestion is that you use the 'node' display, but make changes to your node.tpl.php file in your theme. This will give you the results that you want, but it obviously won't be very point-and-click.


Views Refresh Results are Scrambled Syntax On several beta builds recently that use Views, when I am configuring a new page or block view,  when the results are refreshed manually or automatically I am getting a scramble of code/script/syntax garbage instead of a proper Drupal Views admin page with query results. I have a number of other modules installed and have been unable to determine where there might  be a conflict and process of elimination has been more miss than hit. Returning to the main Views admin page and attempting to configure my primary view fine, and the rest of my beta site runs fine. Has anyone encountered view refresh/results during configuration that are just a scramble of syntax output? What solutions? Any known conflicts?

Yes, I saw this problem recently on a Drupal 7 setup. The modules involved in my case were jQuery update + Calendar but the behaviour in views was the same. Setting jQuery update back to the default (I want to say it's 1.5, not sure) solved the issue with Views and Calendar for me.

Of course I needed jQuery 1.7 for a different purpose, so I had to change it back once the views were done and ready to be used. Not exactly ideal but it worked well enough. Everything functioned fine besides actually making changes to the views.

If you are using jQuery update give changing the jQuery version back a try.


Questions and answers module Drupal 6 Are there any modules for questions and answers website in Drupal 6? I want it to have theme.

The Answers module should do the trick:

  Answers provides a question & answer service. Users can post questions and other users can answer them.

  ...

  The displays are based on standard CCK node displays and Views, so can be themed in the typical ways.


Flush cache on specific drupal 8 page/route I am building a CRUD form in Drupal 8. Users get navigated to it from a list that shows the entities they are editing. After an edit or add they get redirected to the list again. The list is generated in a twig template that is being cached. It's a custom route/controller.

How do i invalidate/delete the cache on that specific list page/route after an edit/add of an entity?

The data in the list is build in custom action, it's no view, and as far as drupal knows, there are no nodes shown in the template. So no default cache functions are triggered.

AFAIK, cache invalidation should not depend on the page or route. When an entity (eg. node #5) is changed, it should in validate all caches tagged with "node:5". If the list of entities is correctly tagged with its cache dependencies, you should be fine.

I realize this answer is rather theoretical and not very specific. Hopefully other answers will be more detailed.


How to hide published content to anonymous user programmatically? I have created a new content type programmatically and I would like to set permission so that anonymous users do not see this content when it is published.

How can I do this?

By default, Drupals permission system does not support specific view permissions by content types. You will need a module for that. Have a look at Controlling Access to Content Overview. In Drupal 6 projects I have used Taxonomy access control lite quite offen.


Assigning roles and permissions Drupal 7 I have a hierarchy of roles which are Admin -> shop_admin -> food_manager / drink_manager / supplies_manager

So the Admin can edit the permissions of all the roles. Is there a way to allow the shop_admin to edit the permissions of drink_manager, food_manager and supplies_manager?

So basically my question is - Is there a way to give a user permission to manage other roles and permissions?

If you go on www.yoursite/admin/people/permissions#module-user you can decide witch kind of user can edit user permissions, so in your case only admin and shop_admin.

Of course you do not want the shop_admin to edit admin permissions, and all the pages where you can edit single user permissions are forms so you can use hook_form_alter in order to hide unwanted options or add conditions based on user role


How do I stringify objects or at least get a string value? The item.content for my field item is 'active'. However, when I use a comparison operator as seen below, it never equates to True but always False. I thought maybe some spacing issues was the reason, but that seems to not be the case.

Is the content in item.content not a string? I am assuming when I call item.content, its probably a object, but I can't find any documentation on how to turn a object's value into a string so it equates to true.

{% for item in items %}
  {% if item.content == 'active' %}

{{ item.content }}

  {% else %}

{{ item.content }}

  {% endif %}
{% endfor %}

You can try this instead

{% if element['#items'][key].value == 'active' %}


How to find out a node's comment status (open, closed) from node ID? Having a view of comment fields here that is embedded into another view via Views Field View module. The comment view has a contextual filter: the nid. Works quite nice.

Now I want to hide the view if comments ain't allowed (per node). Of course I have the node's ID as $argument. How can I check the comment status from that to specify the validate criteria?

The following code should do the trick:

$node = node_load($argument); // load the node object based on the nid
if($node->comment == COMMENT_NODE_CLOSED) {
  // comments are closed - hide the view
}

There are 3 constants that define the different comment states:

COMMENT_NODE_HIDDEN
COMMENT_NODE_CLOSED
COMMENT_NODE_OPEN

For more information see the Node object reference.


Is the Search API module able to do range facets on numeric values? I'm using Drupal Commerce, Search API, and Facets API; I'd like to put the product prices as a facet. Configuring my search API index, I managed to get this facet, but the Search API module doesn't seem capable of handling price ranges facets. This is how the facet looks like.

1230,23
340,21
...

I'd like it to be like the following.

From 10 to 100
From 100 to 200
...

It seems that there is existing code for handling ranges, but not decimal ranges.

Did I miss something?

commerce_search_api sounds like exactly like what you're looking for.  Be aware of the commerce >= 1.4 dependency as of this writing.

The module includes a product display index (configurable at admin/config/search/search_api/index/product_display):

  Auto-generated search index that includes all product display node    types* and related product data.
  Auto-generated facets for all node type categories and product attributes.

I've used the price facet filters, with and without the search_api_ranges widget, with great success.


Will memcache work in this configuration? I've got a Drupal site running with

1 x Load balancer in front
2 x web servers running Apache, PHP and Drupal, traffic coming from load balancer, and
1 x Generic server hosting MySQL (MariaDB) Drupal database and sites/default/files accessed by the above 2 servers over the network.

If I wish to use memcached, would it work if I install memcached on the 2 web servers and configure Drupal to connect localhost using the memcache module?

Edit: are there any special consideration in order to make this work? I think I have read somewhere about session stored.

Short answer is yes, that's a fairly common configuration.
You might also want to consider using Nginx instead of Apache.

For user session support, it's possible to use Memcache.
However, memcache data is more transient and you may prefer the more persistent storage, for longer and more durable user sessions, that the database engine provides.

For cache_form you should use a more persistent cache, such as the database, to avoid form cache validation errors.

e.g: $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

It's recommended to use Memcache for the lock API layer as it's quick read/write and short cache lifetime is suitable.

e.g: $conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';

For Memcache integration with Drupal, you can use https://www.drupal.org/project/memcache or https://www.drupal.org/project/memcache_storage


How to create data types via module I am writing a module that will create the data types for my site.  I am using hook_node_info to create the type itself, then I am using  field_create_field and field_create_instance to add fields.  field_create_field and field_create_instance are functions, so I am wondering which hook they should go into.  My two best guesses at this point are either hook_node_info or hook_install.  The api seems to indicate hook_install, but I find this confusing.   hook_install happens before hook_node_info, so how can you add fields to a content type that does not exist yet?  Also hook_node_info happens every page load, but hook_install only happens once (at the time that the module is installed.)  Am I creating my content type correctly or am I missing something?

Instead of attempting to create your datatype module from scratch, use the Features module to store your content type settings in a feature generated module.  This is faster, but may not cover all of the options that you need (field order, field groups or autotitle.)


Two Factor Authentication for admin/OAuth2 for REST API I am building a "headless" Drupal application.  The front-end is in AngularJS using OAuth2 to authenticate to the REST API that I have built.  A client did a security audit and wanted additional security on the Drupal administration interface.  I implemented the TFA module using Google Authenticator and Twilio SMS.  All is good.

Except, calls to the API are requiring TFA completion/validation. This is noted in the documentation. It states to develop a custom plugin that will handle web services connections.

I don't have a problem doing this, but I was wondering if anybody has run into this issue and has the plugin ready for sharing.  I have exhausted plenty of time searching to no avail.

There's no public plugin for this as far as I'm aware of (note, I'm author of the drupal.org TFA module).

I do think it's a quick write, depending somewhat on how your REST API is authenticating the request and particularly whether you create a Drupal session and invoke the user login process.

You can allow a REST call to skip the TFA process very similar to how the TfaTrustedBrowser works. The loginAllowed() method on this plugin (implementing TfaLoginPluginInterface) will be invoked and you can check the request headers/global scope (user UID) and return TRUE to tell TFA to not block the login action.


How to create different Panels for Add and Edit node? There is a default "add/edit node" panel inside the Pages content.

When I use it, it utilize the its variant for both add and edit forms.

I would need to differentiate between both of these two instead of having a common panel for both of them.

Do you have any solutions?

(My Drupal version is 7.x)

On the node/edit panel, create two variants, "add" and "edit."

Make sure the add variant is first.  Then add a selection rule for the add variant:

String: URL path  node/add/*

All paths not meeting this condition will be sent to the edit variant, which should
give you the effect you want.


Cant get the site out of maintence mode I am using Drupal 7.
I just started creating a new drupal site. Instead of downloading all of the necessary contributed modules, I copied them from a different test site I had made recently. There were a few modules which needed to be updated, so I put the site in maintenance mode, deleted those module folders, pasted in the new ones, ran the update script and now I have no errors. However, now it still says "Operating in Maintenance mode - Go Online", and clicking "Go Online" brings me back to the maintenance configuration page, but I remain in Maintenance Mode! I cleared all caches and nothing helped!
I could just restart everything from scratch, but I would like to understand this issue.

I'm not sure if this make a difference, but originally when I installed the drupal database, I used a previously created database which had only one table (non-drupal) which I deleted before installing the drupal database tables. Should this have effected anything?

If your description of what you do is accurate, the problem is simple to solve.

Clicking "Go online" is only the first step required to take your site out of maintenance mode.  You also need to remove the tick from the box to the left of "Put site into maintenance mode", and then click "Save configuration".

However, if you go through all these steps, and it still fails, you need to update your question to accurately descibe what you do, and we'll take it from there.


Add product image to drupal commerce cart form Is there a way of hooking into the commerce cart form and adding a custom field which so happens to be the product image that I want to display?

I've tried via the view itself but I have no idea on how to when there is only the Order or Order Item objects available in the commerce cart form itself.

I've also tried the following hooks:

theme_views_pre_render
theme_preprocess_views_view
theme_views_data_alter
theme_commerce_cart_form_views_pre_render
theme_form_alter

But i've had no luck.

Can anyone suggest a solution, it's only temporary as I should imagine it will eventually be entwined with the drupal commerce module.

Thanks in advance.

This can be accomplished from the front end by simply editing your commerce_cart_form view and using relationships to "relate" your way backwards from the order item to the product display.
Edit your cart form view and click Advanced on the right side of the screen. Then under Relationships click "Add" then add and apply the following relationships in this order.

Product variation - Order item - "The purchased product variation."
This will give access to add any of the fields under the Product Variation you are relating. it will also give you access to add the product type relationship in step 2.

Product - Product variation - "The parent product." This will give access to add any of the fields that you have in the Product Type you are relating, (including the image field from your product display). This will also give you access to add a content relationship as seen in step 3.

Once you have added those relationships, you will be able to access and add any of the fields you want from both the product variation, and the product type under Fields.
If you are displaying with nodes and/or need fields that are in content types that have product references, you will also need to add the following relationship:

Content using field_YOUR_PRODUCT_REFERENCE - Product - "Relate each Content with a field_YOUR_PRODUCT_REFERENCE set to the product." This will bring in all the fields for the display node.
No custom code required. :)


prevent redirect after form submit? I'm using drupal's form API as part of a block in my module.

When the form is submitted, I want to change the content of the block to something else, let's say "Thanks". I do not want the page to redirect, as is default behaviour.

(Admittedly the default behaviour has the benefit of removing the POSTed page from the browser History, so you don't get questioned on hitting Back.)

If not clear, please let me know and I'll post a code sample.

Set $form_state['redirect'] = false in the submit handler.


Section for logged-in users I've been asked to create a member's area in the site I am currently constructing.

This area should be accessible via a menu section that should only appear to logged in users.

Furthermore, if the user's role is a specific one, the menu should have one extra entry in which the user (let's say he is a baker, and the site is about a pastry shop), can see his earnings in a calendar like mode, assuming each of the cakes sold give's him a percentage.

So all in all, we have very conditional menu items.

Furthermore, the /user page, if the user is logged in (if it's not it's just a themed version of the original Drupal /user page), should be a view, or Panel, or collection of View blocks, that should depict a summary of the 4 links that follow.

At the moment my /user page shows the default "History" and some other stuff some modules have added. How can this page be styled?

The other menu items are: Your Account, Your Cart, Wish List, Order History, pretty much self explanatory, and more or less accessible using Menu Tokens.

The menu's structure is something like this

  -You (if user is logged in should change to his first name)
  |-Your Account (should lead to a form just like user/register (already themed) where the user can edit his information)
  |-Your Cart (commerce cart - kinda easy)
  |-Wish List (commerce wishlist - easy too)
  |-Order History (commerce orders - easy too)
  |-Earnings (for 'Baker' role only)

So the /user page should show (in a different fashion of course) all this information condensed.

So, to recap, the difficulties I am facing are:

Conditional name of the "You" item
Conditional appearing of the 4 sub-items
Conditional appearing ofthe 5th sub-item according to role
Theming of the /user page (when logged-in) (fixed using panel with UID as argument)

Any help for any of those would be highly appreciated.

You should check out Context module, can solve your needs listed above.

One way you can do is to create different menus for different roles.

For example, you create a menu called 'menu for anonymous' , add links for anonymous in the menu; create another menu called 'menu for member', add particular links in the menu. and so forth.

With Context module, you can set 'menu for anonymous' to display for anonymous user; set 'menu for member' to display only for user has whatever role.

For changing 'You' to username, I am thinking that you can use hook_block_view_alter, loop to all menu items in the menu block, replace 'you' to user's name.

Again, with context module, you can add a section variable to the theme for the context of user logged in.

then you can customize your template in page--user.tpl.php

if (!empty($section_title)):
        ... theming for logged in user  ...
else:
    ... theming for general ...
endif;

Hope my answer make sense.


Show content dependent on user choice For a car selling website, there is need that the user choose his car and depending on his choice, another list should appear with the available models.

I search to do this on a conditional system, but also a list with hidden submenus would be acceptable.

If you want  when user select a Car and then according to select car another select list showed with that car model I can suggest you use simple hierarchical select  module ( I know it hasn't stable version yet),

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

  This module has been inspired by Hierarchical select but is much
  simpler (hence the name ;) ).

Also conditional fields is very good module to achieve field show and hide based on another field but it is not suitable for your case.


form_comment_form_alter modify comment body I am using hook_form_comment_form_alter to add values to the textboxes in the commenting form. But in the comment body I can seem to add a default value
and can't seem to find a value that I can change. Does anyone have any ideas?

function mytheme_form_comment_form_alter(&$form, &$form_state, $form_id) {
  dpm(get_defined_vars());
  $form['author']['name']['#title'] = "";
  $form['author']['name']['#default_value'] = "Name";
  $form['author']['name']['#title'] = "";
  $form['author']['mail']['#default_value'] = "Email";
  $form['author']['mail']['#title'] = "";
  $form['author']['homepage']['#default_value'] = "Website";
  $form['author']['homepage']['#title'] = "";
  $form['author']['subject']['#default_value'] = "Subject";
  //$form['comment_body']['need default value']= 'I need to add a value';
}

To add default value to your comment form body use the following snippet,

 $form['comment_body'][LANGUAGE_NONE][0]['#default_value'] = "Your default value";


views attachment title I am using a view page with some attachments.
For each attachment, I need to display the title : it's right in the preview, I can see the attachment's title, but not in the rendered page.
How can I fix this please?

zorglub

As a pretty easy workaround, you could set up a views-view.tpl.php on your own sites that prints $view->get_title() for the title on the attachments.


Hide a view tab if it has no results I have a view which has 5 menu tabs. I want to hide the tab if it doesn't have any results. Can anyone please help me with the suggestions.

Can be done with Jquery
Check for the class "view-empty", if this div has inner div, then that means it has some content, if not hide that parent tab div.


Drupal 8 page manager and panels contextual filters for views_block I'm working with Drupal 8(first project with 8) and trying to build page (via page manager) with taxonomy tid argument.

As a display variant I use panels and inside of panel I put block, generated by views and this views_block have contextual filter.

I haven't found the way for how to attach my contextual filter to views_block plugin from panel or associate context to anywhere.

From debug session I know what panels have my argument as a context.
But how to pass it to views_block plugin inside of panel?

Thank you for any help and information. I'm ready to digg inside of code(and contribute also, if needed) to solve this.

Alternative, you can use Views to pick up the tax term id's

If your node has multiple tax terms, you need to allow multiple values for your contextual filter


Remove login confirmation message programmatically I have the login form displayed in the CTools modal dialog. When users log in, they see the confirmation message and a Rules action redirect them to the home page.
How can I remove the confirmation message without using the disable_messages module?

You can add a custom module hook to alter the login process and unset the messages. If you look at core's user.module you can see the various points where you can hook into the login functions.

This is one option (I think there are several and you may need to adjust based on your site's settings) You should be able to do something along these lines:

function YOURMODULE_user_login(&$edit, $account) {
  if ($account->uid) {
     if (isset($_SESSION['messages']['status'])) {
       unset($_SESSION['messages']['status']);
     }
  }
}


how to add mysqli driver to drupal 8? $databases['default']['default'] = array (
  'database' => 'baba',
  'username' => 'abab',
  'password' => 'abcbc@',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['abcb']['default'] = array (
  'database' => 'ababc',
  'username' => 'abcb',
  'password' => 'Sabbs',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysqli',
);

We have mysql, pgsql and sqlite driver but I wanted to integrate a mysqli driver in drupal ?
How can I achieve it or fetch table from mysqli database in mysql database ?

Drupal 8 uses PDO, so I think mysqli is not supported.

From the documentation:

  Drupal's database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon PHP's PDO (PHP Data Objects) database API, and inherits much of its syntax and semantics.


Attaching a system js library using #attached property (D7) When defining a form using the form api I can attach my own css and js like this:

$form['#attached']['css'] = array(
    drupal_get_path('module', 'my_module') . '/my_css_file.css',
);
$form['#attached']['js'] = array(
    drupal_get_path('module', 'my_module') . '/my_js_file.js',
);

This page on Drupal.org suggests that we can attach system libraries the same way and gives this example:

$form['#attached']['library'][] = array('system', 'jquery.cookie');

However when I add this line to my form:

$form['#attached']['library'][] = array('ui.droppable');

Then the library does not get added.

If I go with the old method of:

drupal_add_library('system', 'ui.droppable');

Then is does get added.

What am I doing wrong?

Going from the working example, I imagine this is what you need:

$form['#attached']['library'][] = array('system', 'ui.droppable');

Without the module name Drupal won't know where to find the library hooks.

But if you want to add a custom library from sites/all/libraries/myAwesomeLibrary this is the right way:

$form['#attached']['libraries_load'][] = array('myAwesomeLibrary');


How do I include a CSS library in my custom module? I want to include the YAMM!3 CSS library in my Drupal 8 site. To that end, I wrote a custom module following the instructions in this answer. Although that answer is in regards to a php library, I thought it would also work for a CSS library.

This is the composer.json from my custom module:

{
  "name": "drupal/my_yamm3",
  "type": "drupal-module",
  "require": {
    "geedmo/yamm3": "*"
  }
}

In the composer.json in the root of my Drupal codebase, I have this:

"extra": {
    ...
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/custom/my_yamm3/composer.json"
        ],
    ...

I updated my codebase with this commands:

$ composer update
$ composer dumpauto

And I noticed this line in composer's output:

> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Installing geedmo/yamm3 (1.1.0): Loading from cache

Which is confirmed by an examination of the filesystem:

$ ls vendor/geedmo/yamm3/
bower.json  composer.json  demo/  gulpfile.js  index.html  LICENSE.txt  package.json  README.md  yamm/

I've enabled the my_yamm3 module on my site, and under admin/config/development/performance, I've disabled css aggregation.

However, when I load the page, I do not see the yamm libraries being loaded in the network tab in my browser.

Am I using the correct method to load a third-party css library? What am I doing wrong?

EDIT osman asked for some confirmation of the state of my environment. In my drupal project root, while I do have /composer.json and the directories /drush/ and /vendor/, I don't have /scripts/ nor /web/. I guess that means I am not using the drupal-composer/drupal-project project.

Regarding his recommended additions to composer.json, this is what I had:

"extra": {
    "installer-paths": {
        "core": ["type:drupal-core"],
        "modules/contrib/{$name}": ["type:drupal-module"],
        "profiles/contrib/{$name}": ["type:drupal-profile"],
        "themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "modules/custom/{$name}": ["type:drupal-custom-module"],
        "themes/custom/{$name}": ["type:drupal-custom-theme"]
    }
},

So again it looks like I don't have the composer project?

Fundamentals

To bind a CSS library into your Drupal installation, it should be defined and exposed via a *.libraries.yaml file.

For example (taken from core's classy theme):

book-navigation:
  version: VERSION
  css:
    component:
      css/components/book-navigation.css: {}

defines that there is a library called book-navigation that when included in a page will deliver the css/components/book-navigation.css css file.

Using composer with 3rd-party CSS libraries

Composer works easily and reliably for PHP dependencies, using the merge-plugin in the way you started working in the OP. But, CSS and Javascript libraries, especially when some preprocessing or building step is required, are a different story.
This is an open and unsolved (to my knowledge and to the date) problem, you can read this issue to get an idea of what problems arise:

https://www.drupal.org/project/drupal/issues/2873160

The main problem is, that when you import the library as a composer dependency, as you did, the library is installed inside the vendor directory wherever that is located. So, you cannot assume much inside your *libraries.yaml file about the file path to the CSS/JS file(s) you want to use.

Alternative (A) without composer: using CDN / externally hosted libraries definitions

For you case, and taken that you want to include this file:

https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css

you could define it inside your *libraries.yaml file as an externally hosted library (see #external):

my_module.yamm3:
  remote:  https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css
  version: VERSION
  license:
    name: MIT
    url: https://github.com/geedmo/yamm3/blob/master/LICENSE.txt
    gpl-compatible: true
  css:
    theme:
      https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css : { type: external }

N.B.: This approach should always deliver the latest yamm.css version.

Alternative (B) without composer: keeping a local copy in your own module's folder

If you place the CSS file inside your module's folder, e.g. css/yamm.css, you will be able to use the following yaml definition in your *.libraries.yaml file in order to be able to use it:

my_module.yamm3:
  version: VERSION
  css:
    theme:
      css/yamm.css : {}

Attaching a library to page(s)

Finally, after you are done defining your library, you can start using it.

This is documented extensively here (https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module) and I would recommend reading that if you haven't already.

Good luck!


Cannot get dompdf to work I have extracted the dompdf libraries folder to /sites/all/libraries

Re: 2. Edit dompdf_config.inc.php to fit your installation.

What exact changes do I need to make to this file???

Also, I am getting this warning in the drupal admin:

  Warning: in_array() expects parameter 2 to be array, integer given in print_pdf_settings() (line 22 of /home/mysite/public_html/sites/all/modules/print/print_pdf/print_pdf.admin.inc).

Print module works best when you copy the library dompdf (or tcpdf) to the module folder directly. In this was you don't need to edit the file, and the print module will detect the library automatically.

Extract the dompdf directory into sites/all/modules/print so that you have dompdf_config.inc at sites/all/modules/print/dompdf/dompdf_config.inc.
Ensure that you have write access to PUBLIC/print_pdf/dompdf/fonts directory.
Your print module should now show the detection of the library at admin/config/user-interface/print/pdf.

You should now be able to export the nodes to PDF :)


How to add contextual links to the main content block? The main content block has no contextual links. I believe this is related to _block_get_renderable_array but I'm not really sure. I'm using Custom Contextual Links module to add contextual links to blocks, but of course it doesn't work with system-main (the main content block).

Contextual module (core) will preprocess the block renderable array and turn $block->content['#contextual_links'] into the block template $title_suffix using the contextual_links element type (see contextual_element_info). See contextual_preprocess for the implementation of this behavior.

While block module relies on _block_get_renderable_array for performance reasons, contextual links example module (from the examples package) shows an example of setting #contextual_links on hook_block_view.

As for CCL, it relies on hook_contextual_links_view_alter which will only alter or add links if there is already a #contextual_links element in the renderable array. The main content block doesn't get the default 'Configure block' contextual link (see _block_get_renderable_array), and therefore CCL doesn't affect it by default. Let's just add the default contextual link:

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function MYMODULE_block_view_system_main_alter(&$data, $block) {
  if (user_access('access contextual links')) {
    $data['content']['#contextual_links']['block'] = array(
      'admin/structure/block/manage',
      array('system', 'main'),
    );
  }
}


How can I add a link to show/hide threaded comments? I've enabled threaded comments in the comment settings on my Drupal 7 site. Now, on every comment that has threaded comments beneath it, I'd like to add a link (in the same place as the reply/edit/delete links) that enables users to toggle the display of the threaded comments beneath it -- a show/hide replies link.

You can do something like this:

In your theme's template.php file:

/**
 * Override or insert variables into the comment wrapper templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("comment" in this case.)
 */
function THEMENAME_preprocess_comment_wrapper(&$variables, $hook) {
  // Add jQuery UI accordian to hide the comments in.
  // It is already added in preprocess node but it is safer to also have it here
  // and doens't add much overhead as drupal will only add it once.
  drupal_add_library('system', 'ui.accordion');
  // Add some custom js to collapse comments.
  drupal_add_js(path_to_theme() . '/js/collapsi-comments.js');
}

In collapsi-comments.js (in this case it is in a folder called "js" in your theme.

(function($){
  Drupal.behaviors.collapsiComments = {
    attach: function(context, settings) {
      $('.comment-form-wrapper.accordion').accordion({
        collapsible: true,
        autoHeight: false,
        active: false,
        header: 'h2.title.comment-form'
      });
    }
  };
}(jQuery));

In your comment-wrapper.tpl.php in your theme wrap the comment form in a wrapper div like this (if your theme doesn't have one and you have a base theme that does, copy it from the base theme  and modify it, otherwise copy from the comment module and modify it):

<?php if ($comment_form): ?>

<?php print t('Add new comment'); ?>

    <?php print $comment_form; ?>

<?php endif; ?>


Drush, Omega 4 - Does not seem to recognize Drupal site I've installed Drupal 7, Drush 7.0 and the Omega 4 theme. I'm using MAMP. Drush does not seem to recognize the /Applications/MAMP/htdocs/newsite/ as a Drupal folder (which it is). I'm attempting to create an Omega subtheme with the command line.:

drush omega-wizard

I then receive the following error:

And then this when I debug:

Thoughts? Help!!!

-Logan

Not sure what has caused this but the solution is:

1) Enable the Omega theme (drush en omega) and set as default (drush vset theme_default omega)

2) Run drush omega-wizard


Views List tag filtering, add a tag to a view for filtering purposes On the Views list admin/structure/views, I can filter my list of views by the tags on the View.

I can search for the tags, but how do I add my own tags to the views so that I can easily filter them?

Open (edit) your view
Click on edit view name/description

Add to/change tags under View tag and click Apply


How can I use hook_views_query_alter()? How can I implement hook_views_query_alter() in Drupal 8?

In Drupal 7, I could use the following code.

$args = arg;
$node = menu_get_object();

if ($args[0] === 'my_view') {
  $query->orderBy('node_field_data_created','ASC');
  if (!empty($node) && $node->type == 'category') {
        $filters = $query->getFilters();
        $first_filter = $filters[0];
        if ($first_filter['#value'] == "(category) AND node_field_data.status:(1)") {
            $query->condition('field_category', $node->nid, '=');
        }

In Drupal 8, this code doesn't work.

Can anyone help me out?

According to the documentation page for hook_views_query_alter(), this hook works in Drupal 8, but (as you can see in comments for the referenced article) you should place it in mymodule.views_execution.inc, not in mymodule.module.


Exporting image styles in Drupal 7? I know that there is a hook to programmatically define image styles in code but I can't find anyway to export ones that already exist in the database to code?

The best way to do this is almost always by using the features module.

That being said if you do not want to use feature this is how you can do it.

In your module you're going to want to define a hook_image_default_styles().

If you already have a style on the database that you would like to define in this hook the best way to accomplish this is by doing something like

$style_name = "name_of_your_style";
$style = image_style_load($style_name);
//$style now has everything you need for your hook_image_default_styles definition.

It does has some extra stuff in there that can be removed such as the isid, ieid, and storage keys. You should remove those keys when using hook_image_default_styles.

If you want to find out how other items are exported out the best bet would be to look at the feature module. In there there's a directory call includes. There's going to be a file in there for everything that can be exported out in core. So you can use that for examples on how to export out styles, filters, field, etc.

Hope this answers your question.


Multiple domains with a language each We've setup that english language points to an english domain, and for spanish we have a language.

The spanish one is simply a symlink to the english code base. When translating nodes, I am being redirected to the Spanish domain when changing a spanish node, and have to login on that domain to be able to work.

How can I make sure; that either I'm logged in, or that I can stay on the same domain when editing content?

You can't stay logged in on a different domain except you'd use some kind of single-sign-on system between your domains.

Cookies are assigned to a specific domain, the browser has no idea that he is still on the same website.

You might be able to configure separate content and interface negotation, so you stay always on your own language, or you could use the admin language feature so a certain user always stays in his language when he's on the site. But not sure if that works 100% for editing translations in Drupal 8, havent tried it yet.