Why doesn't core get updated to 8.5? I am trying to update via Composer following what reported in Update core via Composer, but when I do composer update drupal/core --with-dependencies, I get the following output.

  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update
  Generating autoload files

I checked /admin/report/updates, and I can see that Drupal 8.5 is available. The content of composer.json is the following.

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

Why isn't Composer updating core?

A few things to try if composer update drupal/core --with-dependencies doesn't work

If you're composer.json contains these lines, remove them (where XX equals anything)

"replace": {
    "drupal/core": "~8.XX"
},

Then run composer require drupal/core:~8.5.1 (even if your composer.json did not contain the above lines)

If that fails, try my last ditch method:

Remove the core & vendor folder (we will then re-add)

sudo rm -rf core vendor

Clear Composer cache

composer clearcache

Then again

composer require drupal/core:~8.5.1

Don't forget to make a backup first if you haven't already!


form_alter correct coding question function MYMODULE_form_views_exposed_form_alter(&$form, $form_state) {
 if ($form['#id'] == 'views-exposed-form-search-page-1') {
 $form['submit']['#value'] = 'Go';
 $form['text']['#size'] = '100';
  }
}

In the code above, which is the correct way:

   $form['submit']['#value'] = 'Go';

Or

   $form['submit']['#value'] = t('Go');

And:

  $form['text']['#size'] = '100';

Or

  $form['text']['#size'] = 100;

Always wrap all strings in t() so that it can be translated. And always use english for strings in the source code because Drupal assumes that it is english. Even if your site is in a different language (You can translate it afterwards through the UI or create .po files).

The other one doesn't matter. Technically, it's an integer, so without quotes but it will be converted to a string when displayed anyway.


How should I change the permissions PRIVATEMSG for users in order them to have the access? Good day,
I've marked read, write and delete the privatemsg for the authenticated users but they don't still have access to the pages such as user/user-id/messages. The access is only granted with "read all" permission.
I use privatemsg 6.x-1.5
Thanks.

The normal user interface is at /messages, user/uid/messages is only meant to read messages of other users and is not a full replacement.

6.x-2.x has a feature that allows to move it around but it's relatively complex and I wouldn't necessarly recommend using.


Page Manager and Panels settings — where do they live? I'm continuing my quest to make every piece of common site architecture into something that can be displayed in a View. Right now I'm on Panels panes and Page Manager pages.

I have a site that is most assuredly making use of Panels panes and Page Manager pages on the node display, node edit form, and a few other places. However, when I inspect page_manager_pages, or any other table in the DB that begins with page_manager_ or panels_, the table appears to be completely empty. (I'm using PHPMyAdmin, and it gives me that red cursor with an 'x' in it.)

I haven't been able to find an API call that lists all Panels panes, Page Manager pages, or other relevant data either. And when I have looked through the sites I own to see ones that do have something in the page_manager_pages or panel_panes tables, it seems to be much less than I would expect. (E.g. a large site that is heavily themed with Page Manager and Panels shows up in the db with just two entries in the page_manager_pages table.)

I've even combed through the SQL queries that Drupal does when I click "enable" on a disabled Page Manager page (e.g. the node edit form, the node display), but haven't found anything that looks meaningful.

This ended up requiring API calls, since Panels and Page Manager definitions can live in code or in the database.

First I got the tasks with page_manager_get_tasks().

This gave me a list of tasks, which appear to be high-level Page Manager stuff. My Workbench, Node add/edit form, Node template, User template, User edit form, and Custom Page were the tasks.

Custom Page had subtasks that included all my custom pages, so I did page_manager_get_task_subtasks() on each tasks that had subtasks, and then page_manager_load_task_handlers() on each subtask. Within the handlers, there is information about the Panels and other objects that go on that page.


Are entity IDs assigned per entity or across the board? I'm building an electronic parts database in D7 and want to create a custom "part" entity with bundles for resistors, capacitors, etc.

I also need to autocreate an atomic serial part number common to all bundles, i.e no separate part numbering system per bundle.  I was going to use the Serial module but it only works with nodes.  In D6 I did everything in nodes for a similar application and just used the NID, but this parts DB really wants a cleaner solution using entities. I'd like to use the entity ID as the serial part number but only if it's unique per custom entity type.

Question is: Does each custom entity type I create have its own set of entity IDs or is it like in D6 with nodes where NIDs apply across all content types?

Each entity type has it's own ID sequence. For example a user may have the uid of 1 while a node may also have an nid of 1. Similarly a taxonomy term may have a tid of 1. In all those cases the "entity_id" is 1.

Regarding the serial module, as it provides a field via the Field API, presumably that field could be attached to any entity bundle.

In regards to linking your entities, you could probably use the entityreference module to create reference links between your entities.


How do I uninstall Drush? There is a method of installing Drush via Composer.
composer global require drush/drush:dev-master

How do I uninstall it using Composer?

It seems there is no single remove command, so you need to:

Edit your composer.json file, e.g.

vim ~/.composer/composer.json

and remove line containing drush. Save the file.
Update Composer PHP packages by:

composer global update

It will remove a globally installed drush.

If you don't have composer command in your PATH, try php composer.phar instead.

See: How to remove a package from composer?.


template.php check user and profile I created a custom tpl file for one of my content types and I would like to check the users profile as well if they were the publisher and if it all checked out then proceed to the tpl file.

Here is an example

if(publisher and profile){
   proceed to tpl file
}else{
   You are not authorized to view this page.
}

If someone can point me in the right direction that would be great, thanks.

This is not something that should be done in the theme layer. I would look at solutions like ACL or Content Access.

If you really need to code your own solution for some reason, create a custom module and use the necessary hooks, such as hook_permission.


How to resolve this fatal error '2006 MYSQL server has gone away'? I'm trying to send 750 emails through cron job.
After it sends nearly 40 emails, like after a few minutes it throws this error,

  Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /public_html/ehs/includes/database/database.inc:2171 Stack trace: #0 /public_html/ehs/includes/database/database.inc(2171): PDOStatement->execute(Array) #1 /public_html/ehs/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array) #2 /public_html/ehs/includes/database/database.inc(2350): DatabaseConnection->query('select name, d...', Array, Array) #3 /public_html/ehs/sites/all/modules/elysia_cron/elysia_cron.module(424): db_query('select name, d...', Array) #4 /public_html/ehs/sites/all/modules/elysia_cron/elysia_cron.module(632): elysia_cron_get('rules_cron', false, 'running', 0, false) #5 /public_html/ehs/sites/all/modules/elysia_cron/elysia_cron.admin.inc(753): elysia_cron_is_job_running('rules_cron') #6 [internal function]: elysia_cron_execute_page_cleanup() #7 {main} in /public_html/ehs/includes/database/database.inc on line 2171

I have tried upgrading max_allowed_packet to 500M under [mysqld] in my.ini and also php_memory_limit to 1024M, but still it didn't improve anything.
Is there any other possible thing I could do to resolve it?

FYI, I'm sending a view in emails to all the users using Insert view. The views are generated per user basis, and that involves aggregation operations and computed fields.

A few minutes to send 40 emails indicates that this cron job is computationally expensive. You are probably hitting against MySQL's wait_timeout limit.

I wouldn't necessarily suggest changing your MySQL configuration. Drupal's cron runs aren't meant to take more than a few minutes at a time. Instead, this may be better suited to a cron queue.

In a cron queue, each individual email to send would be a job in this particular queue. During each cron run, as many of those jobs in each queue are processed until some set time limit has passed, and the remaining jobs are deferred for the next cron run.


How to export private images from Drupal I want to export private images from Drupal to an external client. How to I authenticate an external client to access private files from Drupal DB?

You can use file_create_url($uri) to create an externally accessible url for the file.

If used with private file mode files, you will need to implement hook_file_download

You might also be interested in the Services module, to expose an API for the files, which can provide authentication methods such as Drupal session and OAuth authentication.


How do I disable tooltips for field help text in Bootstrap? On the user registration page, my help text for fields is displayed as pop-up text when I use the Bootstrap theme, but this doesn't work well on mobile devices, and most of my users are visiting through their phones.  How do I get rid of the tooltips?

There is a setting for this.

admin/appearance/settings/bootstrap
Javascript -> Uncheck Enable Bootstrap Tooltips


Module similar to module filter to filter content and users? I use Module filter module to filter the long list of modules. It comes very handy to find a module rather than using CTRL+F always. I was wondering if there is a module which can filter the content (at admin/content) and/or users (at admin/people) as well.

Contentment (along with VBO) looks like a winning combination.


Drupal Sub Sites with or without Aegir We're currently using Aegir to manage sites, essentially, domains and sub domains. However, we have a need for sub sites. For e.g., domain.com would the parent, and the children sites would be domain.com/division1, domain.com/division2 and so. The databases could be the shared or not; themes could have a parent-child relationship or not. Looks like this is not in Aegir yet (although the university crowds are asking for it)

What options exists to create and manage sub sites using Drupal? How do folks typically do this? I looked at the subsite module, while looks like it is still in dev for D7.

Many thanks!

Drupal sites in subdirectories are now fully supported in Aegir 2.x since version 2.0


How do I in Drupal 7 hook into the status message update area after saving a node and it says "updated node" to be a link to that node In Drupal 7, after saving a node it redirects you back to the page of the node with the message status saying "blog 'title of blog' has been updated".

How do I turn that status message into the link of that node? I need to do this since I have rules setup where I have it redirect to another part of my site, and it just shows the status message of that node being updated. I just need that clickable. im assuming it would be a hook somewhere hook node save?

You can use hook_node_update() that responds to node updates. There you can add the link in drupal_set_message().

However you may get two status messages, a default status message and another the custom message you just created. For removing the default message you can use Disable Messages module.


Is there a way to add clauses like accept = 'image/*' to input items via forms API? I'd like to add "accept" attributes to some of the input fields for my site's content types -- to end up with something like <input type="file" id="edit-field-whatever-und-0-upload" name="files[field_whatever_und_0]" size="22" class="form-file" accept="image/*">, so that (most) browsers will limit the selectable items to .jpg, .png, etc.  I've tried doing this by adding an #attributes clause to a form's hook_form_alter handler, but haven't been able to find the right way to write the clause -- I can't get the accept clause to show up in the html.

In place of this, I'm currently adding it through some jQuery that runs on document.ready, but it would feel cleaner if I could do it through the forms api. Is this possible? Any hints out there?  Thanks!

You can override theme_file to achieve above if you would like to alter file input element in template.php ..

function YOURTHEMENAME_file($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'file';
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-file'));

  return '<input' . drupal_attributes($element['#attributes']) . ' accept="image/*" />';
}

below code works for me

function seven_file($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'file';
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-file'));

  return '<input' . drupal_attributes($element['#attributes']) . ' accept="image/*" />';
}


Custom module search ranking not working + ranking admin settings not showing properly I'm using a custom module, with custom content type and custom search implementations and ranking. To rank the results I'm using the votes cast for the posts. But the voting system is custom too, i.e. it uses a custom table and not a standard drupal table. Now the problem is that:

The ranking doesn't work at all. I have set an influence value(content ranking factor) of 1 in the search settings for the ranking.
You know the ranking factors I mentioned above, in the search settings? It will only list my ranking factor, if and only if I enable the node module in the Active Search Modules section. As you might have figured I have my custom module in the Active Search Modules enabled.

Maybe problem #2 is the cause of #1?

The code for the hook_ranking() implementation is as follows:

function knowledge_ranking() {
    return array(
        'post_rating' => array(
            'title' => t('Post Rating'),
            'join' => array(
                'type' => 'LEFT',
                'table' => TABLE_POST_VOTES,
                'alias' => TABLE_POST_VOTES,
                'on' => TABLE_POST_VOTES . '.pid = i.sid',
            ),
            'score' => 'vote.average / CAST(:max_rating AS DECIMAL)',
            //I also did the following:
            //'score' => 'AVG(vote) / CAST(:max_rating AS DECIMAL)',
            'arguments' => array(':max_rating' => 5),
        ),
    );
}

It's worth mentioning that I have cleared cache, rerun cron and re-indexed the site several times.

Any help or tips are appreciated, thanks :-)

Update 1:

Solved #2

You need to implement yourmodule_search_admin() and from there return that part  of the form.

Update 2:

I'm pretty sure that problem #1 lies within this line:

'score' => 'vote.average / CAST(:max_rating AS DECIMAL)',

So now I guess I have to put the average rating for each post in a field in the posts table. But there are gonna be a lot of more factors. So now the question is can't we use such complex scores at all?

Finally I cracked this frigging case!
As it turns out, there was no way for anyone to be able to answer this question since my given information was incomplete. Although in my defence if I knew that I should've given that info, I would've solved the problem long ago(two days) :-D.

Solving problem #1:

Dead simple! In my case I had commented out the following line inside hook_search_execute():

_node_ranking($query);

this functions adds the rankings to the results.

Solving problem #2:

As for this problem, the influence choosing form doesn't show up automatically. The node module, if active in the Active search modules, lists all the factors for all Search active modules. But for a module to list its own factors, it must implement the hook_search_admin() function like this:

function hook_search_admin() {
  // Output form for defining rank factor weights.
  $form['post_ranking'] = array(
    '#type' => 'fieldset',
    '#title' => t('Post ranking'),
  );
  $form['post_ranking']['#theme'] = 'node_search_admin';
  $form['post_ranking']['info'] = array(
    '#markup' => '
' . t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '
'
  );

  // Note: reversed to reflect that higher number = higher ranking.
  $options = drupal_map_assoc(range(0, 10));
  foreach (knowledge_ranking() as $var => $values) {
    $form['post_ranking']['factors']['node_rank_' . $var] = array(
      '#title' => $values['title'],
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => variable_get('node_rank_' . $var, 0),
    );
  }
  return $form;
}


How to render an entire page from external php page? I'm creating a custom .php page that is outside my drupal installation and it should render a custom page of the installation. The "entire" page, also with theme and everything else.

I'm using this code, works but is not loading the theme:

    <?php

    /**
     * Root directory of Drupal installation.
     */
    define('DRUPAL_ROOT', '/home/quickstart/websites/custom.dev');

    include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

    drupal_deliver_html_page('user');
    ?>

Where am I wrong?

drupal_deliver_html_page() is never called directly; you should eventually call drupal_deliver_page(). It also seem you are calling the function with the wrong argument, since drupal_deliver_html_page() doesn't get a path as argument, but the result obtained by a page callback.

The correct code would be the following one.

define('DRUPAL_ROOT', '/home/quickstart/websites/custom.dev');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler('user');

Since that is just the index.php code just slightly modified, I don't see any reason not to use http://example.com/user directly. A custom PHP file like that should be used to perform specific tasks, like in the case of cron.php.

define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  drupal_cron_run();
}

Normally, you don't need to use a similar file, and you should handle it through a normal menu callback; this even more true when you need to just shown a specific page as you are doing.

Keep in mind that Drupal 8 doesn't use anymore the cron.php file; cron tasks are handled through a menu callback too.


how to add my custom template of heatbeat d7+heratbeat version = "7.x-1.1"

I have a module named "love.module"
in love.module

/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'love' && $api == 'love') {
    return array('version' => 1);
  }
}

and I have a file name love.heartbeat.inc,

    <?php
/**
 * Implements hook_heartbeat_template_info().
 */
function love_heartbeat_template_info() {
  watchdog('-call', 'message', array(), WATCHDOG_NOTICE, 'link');
$heartbeatmessagetemplate = new HeartbeatMessageTemplate();
$heartbeatmessagetemplate->disabled = FALSE; /* Edit this to true to make a default heartbeatmessagetemplate disabled initially */
$heartbeatmessagetemplate->api_version = 1;
$heartbeatmessagetemplate->message_id = 'heartbeat_add_comment2';
$heartbeatmessagetemplate->description = 'user replied on some content';
$heartbeatmessagetemplate->message = '!username replied on !title:

!comment

';
$heartbeatmessagetemplate->message_concat = '%username% replied on !title.';
$heartbeatmessagetemplate->perms = 2;
$heartbeatmessagetemplate->group_type = 'summary';
$heartbeatmessagetemplate->concat_args = array(
  'group_by' => 'node',
  'group_target' => 'username',
  'group_by_target' => 'title',
  'group_num_max' => '5',
  'merge_separator' => ', ',
  'merge_end_separator' => ' and ',
  'roles' => array(
    1 => 0,
    2 => 0,
    3 => 0,
    4 => 0,
    5 => 0,
  ),
);
$heartbeatmessagetemplate->variables = array(
  '!username' => '',
  '!title' => '',
  '!comment' => '',
);
$heartbeatmessagetemplate->attachments = array(
  'buttons' => array(
    'weight' => array(
      'activitycomments' => '-9',
      'flagattachment:like' => '0',
    ),
    'settings' => array(
      'activitycomments' => array(
        'activitycomments_node' => 0,
      ),
    ),
    'enabled' => array(
      'activitycomments' => 0,
      'flagattachment:like' => 0,
    ),
  ),
  'content' => array(
    'weight' => array(
      'activitycomments' => '-9',
      'flagattachment:like' => '0',
    ),
    'enabled' => array(
      'activitycomments' => 0,
      'flagattachment:like' => 0,
    ),
  ),
);

  return $heartbeatmessagetemplate;
}

but the hook didn't called.who can help me?
did I miss somthing?

I had the same problem and what you should do is replace

/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'love' && $api == 'love') {
    return array('version' => 1);
  }
}

by

/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'heartbeat' && $api == 'heartbeat') {
    return array('version' => 1);
  }
}

and after a cache flush, it should appear in heartbeat templates


Drupal 7 Rules - Grant access to node - pick username from node field I have in D7 Content access and Rules -modules. I have content type which Content access settings are limited to only admin.

In that content type I have User Reference field.

I need to have rule which picks username from that User Reference field and grants content view access to the user, so user can view that node.

So after rule has applied user from node User Reference field has view access to that content - ohter users can't see that node.

I have tryed multiple rules settings but have not got it right yet so help would be appreciated. Thanks!

Take a look at the Node access user reference module which is meant for this sort of thing (giving access permissions based on a user reference value in the content).

  Gives content access permissions to users for content that references the users with User reference or Entity reference.

  This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.


GMap Activation Error I have run into an odd error with my gmap module where I allow users to use the map to choose the location (rather than enter coordinates, they are allowed to enter an address too of course) but back to the map.

What's off is that the map 'works' it's just that it starts off greyed out, but if you double click the map it pops up as normal (Google Streets). Has anyone run across this error before?

----- Edit-----

It appears that if you open up the page and the map is greyed out, if you adjust the size of the browser window even the slightest, the map will appear as normal. So where could this problem be originating from?

This is a classic GMap problem. It usually occurs when the map doesn't know it's dimensions initially. For example: when the dimensions are set in a stylesheet (.gmap {width: x; height: y;}).

You could try setting them inline on the wrapper div (<div class="gmap" style="width: x; height: y;">) or trigger a resize after the page has loaded, as explained here: How do I resize a Google Map with JavaScript after it has loaded?

If you are using the gmap or geolocation module, you can set the dimensions in the widget properties.


Include theme stylesheets after base theme stylesheets I'm using Tao as a base theme in Drupal 6. However, The base theme stylesheets are being included after the sub theme ones which is causing the base theme to override the the sub theme. As a result Tao's reset.css is coming after my theme stylesheets. Is this correct Drupal 6 behaviour?

My subtheme.info file looks like:-

core = 6.x
engine = phptemplate
name = Sub theme
base theme = tao

stylesheets[all][] = css/common.css

In Tao's issue queue you will find more info. See Issue #1013440: TAO stylesheet loads last and overrides sub theme styles..

In the readme file:

  Tao does not use the all key for any of its stylesheets and expects
  that you will not either. Be specific - if the stylesheet is for the
  screen, or for print, say so. Any stylesheet overrides your subtheme
  provides should use the same media key as the one in tao.info for
  the stylesheet that is being overridden.


floating an image above a specific taxonomy termed node I have to create a website that allows for a "new" tag to be floated above certain pictures that have the specific taxonomy term of "new".  I created a view for the "new" where I added an empty div below the image and then floated it above the image and added the actual "new" image with CSS.  This is what it looks like
For the "new" node.tpl.php the code looks like this:
<article class="node-<?php print $node->nid; ?>
<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

<?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);
?>

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

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

The id="new-intro" is the code that adds the background image to the empty div and places it above the product image.  So what I need is a code that automatically adds the id="new-intro" based on whether the product has the taxonomy term of "new"
I've found quite a few PHP samples but my knowledge is fairly limited and so I'm not sure that I'm editing them properly.
Can any one point me in the right direction??
Thanks so much!!
Edit:
So using the code below my code looks like this:
template.php:
function hayfield_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['new_introduction'] = FALSE;
  if ($terms = field_get_items('node', $node, $field_new_introduction)) {
    foreach ($terms as $term) {
      if ($term['tid'] == 'new') {
        $vars['new_introduction'] = t('!published' == TRUE');
      }
    }
  }
}

and the node code looks like this:
<article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <div <?php if ($new_introduction): ?> <?php print 'class="new-intro"' ?> <?php endif; ?>><?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

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

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

But it's throwing major errors :
Warning: Unexpected character in input: ''' (ASCII=39) state=1 in /Users/Candace Morgan 2/Sites/hayfield/sites/all/themes/hayfield/template.php on line 33
(it doesn't like my argument in the last line of the template.php)
Fatal error: Cannot access empty property in /Users/Candace Morgan 2/Sites/hayfield/modules/field/field.module on line 936
the Content type is product_display, the field in the content type is field_new_introduction, the taxonomy vocabulary name is new and the taxonomy term name I want to reference is New Introduction.
I'm yanking my hair out on this one!!  Thank you for any help you can give me!!

Put this into your themes:

function THEMENAME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['new'] = FALSE;
  if ($terms = field_get_items('node', $node, $FIELD_NAME_OF_YOUR_TERM_FIELD_IN_NODE)) {
    foreach ($terms as $term) {
      if ($term['tid'] == THE_TERM_ID_OF_THE_NEW_TERM) {
        $vars['new'] = t('Maybe you can add something new text or simple set it TRUE');
      }
    }
  }
}

Then empty the theme_registry (clear caches) and change the
 to:

  <?php if ($new): ?>
    <?php print $new ?>
  <?php endif; ?>

Using the same ID in one page is not valid. Then you can target using CSS styles.


How can I find certain queries? I have logged a bunch of slow queries. Now I am wondering how should I find them in Drupal. Any ideas?

If it is related to database queries you can use Devel module.  You can configure this module http://www.example.com/admin/config/development/devel this will show you a list of slowest queries.


There aren't any releases for module "commerce_tax" I am using drupal-vm and drupal console, and following the instructions for installing drupal commerce on an existing site (drupal-vm made me a drupal 8 site) here:
http://docs.drupalcommerce.org/v2/install.html
specifically, the command was:
drupal module:install commerce_product commerce_checkout commerce_cart commerce_tax

I received the error in the Title, here's the whole output:

drupal module:install commerce_product commerce_checkout commerce_cart commerce_tax
 One or more modules "commerce_tax" are not available, running download process to get those modules
 Getting releases for module "commerce_tax"

[ERROR] There aren't any releases for module "commerce_tax"

[ERROR] Invalid module name: commerce_tax

Installing module(s) "commerce_product, commerce_checkout, commerce_cart"

[OK] The following module(s) were installed successfully: "commerce_product,
      commerce_checkout, commerce_cart"

// cache:rebuild

Rebuilding cache(s), wait a moment please.

[OK] Done clearing cache(s).

You're getting the error because commerce_tax is not included in Commerce 8.x-2.x branch, because of which Drupal Console is not able to find the module.


Adding RewriteCode in https does not work for links other than base url RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com*
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

With this I swap from http:// to https://www in one single redirect step.

Unfortunately this does not work for sub-pages. So http://example.com/categorypage will get redirected to https://example.com.

How do I fix it? What should be added in .htaccess to fix the redirection from http to https for sub-pages?

Adding these lines to the default .htaceess file worked for me

# Force HTTPS across the Drupal site
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>

Also enable clean URLs for that site


Change part of theme according to time of day In Drupal 8, I'm trying to change part of a twig template according to time of day.

For instance, if in one of my twig templates I have:

Where and what do I need to change to have it produce

according to server time?

I was thinking of doing it passing a variable to my twig template and then something like:

{{ if (variable == 'day') }}

{{ else }}

{{ endif }}

But I don't know how to pass a $variable to the template. Also, if I were to do this in a module, what hook would I have to alter to achieve this?

The idea would be to use PHP's date object to find out the current time to then change the value of a certain $variable in a hook, and said variable would be available to work in twig with in the above pseudo-syntax.

Can anyone share some pointers on where to begin?

You can define new variables in the array $variables in preprocess.

Assuming this is the page template:

modules/mymodule/mymodule.module:

function mymodule_preprocess_page(&$variables) {
  if ( ... ) {
    $variables['daynight'] = 'day';
  }
  else {
    $variables['daynight'] = 'night';
  }
}

Then use the variable in your twig code:

{{ if (daynight == 'day') }}

{{ else }}

{{ endif }}

Or shorter:

You will get some problems with caching. In drupal and in proxies and browsers. So this is probably not a server but a client side solution.


Config for using PUT with Services Module I'm integrating DrupalGap with Drupal 7 and Services module. Issue I'm running into is that all PUT requests are returned as 405 Method Not Allowed.

For example: GET http://example.com/?q=drupalgap/user/1.json works just fine.
After I update the json and try PUT http://example.com/?q=drupalgap/user/1.json gives me the 405.

This is happening locally and on the hosted server, hosting is with Pantheon, they use nginx if that's relevant.

I also tried doing the PUT using the Poster browser extension, same result, which makes me think it's a config setting that's incorrect.

There is no configuration needed in drupal to accept put requests the web server may be refusing PUT requests and requires some configuration see why-does-my-web-server-software-disallow-put-and-delete-requests for more information about this issue.

Try curl and see response example below

  curl -X PUT  the request

The advanced rest client s chrome extension I prefer to use over others.


Drush pm-update needs a module? When trying to run `Drush pm-update' in a site i get the error

Command pm-update needs the following modules installed/enabled to run: update.                              [error]
The drush command 'pm-update' could not be executed.

Oddly this command was recently working (on other sites in the same core installation), and further more I have no idea where to find or what is this 'update' module. Can anyone point me in the right direction?

It's in <drupal_root>/modules/update. If not, it means you damaged your core.

Try drush en update - it should re-enable it for you. After performing updates you are allowed to disable it again.


How to apply header and footer or layout to all pages in a panel enabled website? I have decided to use the Panels module and the Precision theme to implement my website. I have designed a front page (using a Panel page) and it has a nice header and footer.

I have also created a user for testing purposes, but when I click on the link in the email to reset the password, I get something like this:

I have some editors (i.e., with a specific user profile) who must be able to create node instances (i.e., tip articles), but without proper layout for standard Drupal pages, the screens are ugly and not functional.

The Precision theme does not come with much CSS and layout. How can I implement some minimum layout on all standard Drupal pages and eventually move the header and footer to those pages too? The header and footer are implemented as mini-panels.

I am still new to Drupal. What is the proper strategy here? Thanks.

There are lots of answers to your question. Here is mine :)

I usually define 3 areas. The Header and the Footer are "static" blocks that are shown in every site pages. The content is in the middle and is defined with Pages and Panels. That's it!


How to include PHP code in welcome email? I need PHP (for some logic) inside the welcome email, the welcome email structure is defined in admin/config/people/accounts (in the text box)

How can I place PHP code there? I tried to put some PHP but I only get a blank email. Or if I can`t execute PHP code inside the email box what module can I use to do this?

Updated :

Use PHP mailer module to send the email in the format of php


How to use variable value in twig file? I have below code in:

{% set img_url = item.image.url ? item.image.url : {{ base_path ~ directory }}'/images/default.png' %}

Twig file. How to make it work so it will take full default image path?

To get the base_url (path) you will need this in your THEMENAME.theme file

function THEMENAME_preprocess_page(&$variables) {
  global $base_url;
  $variables['base_path'] = $base_url;
}

Then it will be available in your twig template

But most of the times you will not need the full path to display an image

You can try the following

{% set img_url = item.image.url ? item.image.url : '/'{{ directory }}'/images/default.png' %}


User Relationships view showing the right number of users, but showing my profile link, not theirs I'm not very good with Views and Panes, but I've almost completely managed to get what I want working.

I have User Relationships configured to have non-reciprocal relationships (so like Twitter, where "A follows B" does not necessarily imply that "B follows A"). I have a Pane that displays users followed by $current_user and I have cloned it to a new Pane displaying users following $current_user.

The Panel is almost working perfectly, with one exception — it is showing me the right number of profile links, but they're all links to $current_user's profile with $current_user's avatar, rather than links to $following_users' profiles with their avatars.

I changed the Fields section in the Pane definition to point to the requestee User profile picture and the requestee UID, but this doesn't seem to have fixed it. It's not the database query coming out wrong, I'm just displaying the wrong values for each relationship in this Pane.

I'm sure this is really very obvious, I just can't spot the setting I need to change from requestee to requester in the Views Pane interface.

Anyone able to point me to where I'm missing the obvious bit of configuration?

Edit: I've taken a screenshot of the configuration interface (linked, rather than embedded, as you'll want to look at it in a bigger scale than embedding allows). The Custom text in the Fields reads [field_user_image]. In the Contextual filters, I've set the Requester user filter to Exclude. The Argument input reads as follows:

Edit 2: Looking in the Custom text ([field_user_image]), I have Replacement patterns available:

[field_user_image] == User: My profile picture
[uid] == User: Uid
[nothing] == Global: Custom text
%1 == User relationships: Requester user title
!1 == User relationships: Requester user input
%2 == User relationships: Requestee user title
!2 == User relationships: Requestee user input

But I can't work out how to make use of %1 or !1 in order to get the requester's [uid] or [field_user_image], rather than that of the currently-logged-in user.

Fixed it. I was using the requestee fields when I should have been using the requester fields. What was:

Should have been:

Problem solved.


The view is not filtering the duplicate nodes i have a view which is not filtering the duplicated nodes and i tried couple of solutions but it looks like they are not working.

The code I am using is the following.

function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'basicnews') {
    $unique_nids = $new_results = array();

    // Loop through results and filter out duplicate results.
    foreach ($view->result as $index => $result) {
      if (!in_array($result->nid, $unique_nids)) {
        $unique_nids[] = $result->nid;
        $new_results[] = $result;
      }

      // Replace $view->result with new array. Apparently views requires sequentially keyed
      // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
      // unset the duplicates.
      $view->result = $new_results;
    }
  }
}

Is there any patch or work-around for this issue?

You can handle most duplicate node issues using Views Aggregation options.

Go to advanced in the view and select "Use Aggregation"

Then in the fields area, set the aggregation settings.  Generally, you just want the group together option with Entity ID as the group column.  Sometimes you have to play around with other settings as well.


Accessing Leaflet maps from custom module Trying to add to Leaflet map marker from the custom module. Leaflet map created with IP Geolocation Views & Maps module. I try to connect to the map as described here http://dripl.nl/blog/taming-leaflet-maps-drupal
The message alert appears with the coordinates, but the map does not increase the zoom. What could be the reason?

I also tried to replace the string myMap = lMap; with var myMap = Drupal.settings.leaflet [0] .lMap; not help.

test_module.module

function test_module_form_article_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo']['#element_validate'][] = 'test_module_validate_function';
}

function test_module_validate_function($element, &$form, &$form_state){
    $marker = [49.055688666667,34.338167222222];
    test_module_add_marker($marker);

}

function test_module_add_marker($marker) {
    drupal_add_js(drupal_get_path('module', 'test_module').'/test_module.js');
    drupal_add_js(array('test_module' => array('marker' => $marker)), array('type' => 'setting'));
}

test_module.js

(function($) {
  $(document).bind('leaflet.map', function(e, map, lMap){
    myMap = lMap;
  });

    Drupal.behaviors.test_module = {
        attach: function (context, settings) {
            latlon = settings.test_module.marker;
            alert(latlon);
            myMap.setView(latlon, 14);
        }
    };

})(jQuery);

I managed to solve the problem in the following way, I hope it save someone time:

(function($) {

var lMap = Drupal.settings.leaflet[0].lMap;

    Drupal.behaviors.test_module = {
        attach: function (context, settings) {
            latlon = settings.test_module.marker;
            //alert(latlon);
            lMap.setView(latlon, 14);
        }
    };

})(jQuery);


Users have access to add Commerce Products into the Store and publish it. How to display to user only allowed firms in the product addition form? My webshop has lot of users with role Seller. They can add SKU and publish goods. Product display content type has field "Firm" that is taxonomy term reference.

Now every Seller can see all the firms (all the terms) when he add a product and he can check anyone. This is very uncomfortable because Seller work with only a few firms and he want to see only his firms to check one of it.

I want to display only user referenced firms in this field when user add a product.

How do I do this?

I've added to user profile field "Seller Firms" that is the term reference to the Firms. Using module Field Permissions I've made this field accessible to edit only by administrator.
I've checked for each user his firms that he can have access to publish goods of these firms (seller will can to check only those firms that I've checked in profile)
So how to alter product addition form to show only user allowed firms? I have few product displays machine names: product, product_with_attributes

I think this will be hook_alter_form or Rule that will limit the selection to only a few firms that are allowed.

I've made the first part this way:
1. I add Entity Reference field "Seller" to taxonomy Firms that link to users profiles.
2. I'd fill this field for all terms with users that must have access
3. I start to write my module that will display only user referenced terms in node add form. I do not know how to write this. The field name in node Product Display: field_firm. Field Entity Reference in terms: field_seller. Help me to finish my module:

function user_referenced_taxonomy_terms_form_node_form_alter(&$form, &$form_state, $form_id) {
  //$form ['field_firm']
}

It is possible using hook_alter_form but hook_form_FORM_ID_alter would be better so you only target the correct form.

You will need code to retrieve only the firms the user has from their profile field and then using array_diff to remove the others from the select options.


Programmatically save image together with its ALT I am not sure what is the benefit of using system_retrieve_file mentioned on Save image from URL to a field from a custom module, so I just use the following simple code to save image programmatically:

    $file = file_save_data(file_get_contents($url), file_default_scheme().'://field/image/'.basename($url));
    $file->status = 1;
    $node->field_image['und'][0] = (array)$file;
    node_save($node);

Works fine, so now I am trying to figure out how to save the enabled alt value which is stored in $alt variable.

When I output what the $file array contains with dsm(print_r($file,true)); it shows only:

stdClass Object
(
[fid] => 9
[uri] => public://field/image/150304192032_monalisa_624x351_afp_0.jpg
[filename] => 150304192032_monalisa_624x351_afp.jpg
[filemime] => image/jpeg
[uid] => 1
[status] => 1
[timestamp] => 1425596902
[filesize] => 28642
)

Unfortunately, it doesn't contain neither title or alt. Could anyone help me to get this sorted out? Thanks!

As far as Drupal 8 is concerned, there is another solution :

//    $file : my File Entity
//    $node : my (Node) Entity having an Image File field associated
$node->field_my_image_field[] = [
 'target_id' => $file->id(),
 'alt' => 'Alt. text',
];
$node->save();

Well, I think that 'width', 'height' and 'title' are also available in the setting array (but target_id seems required).
cf: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldType%21ImageItem.php/class/ImageItem/8.2.x
(look at the source code, generateSampleValue() method).


Template page--node--.tpl.php not working I've created a page node for an about page. I've checked the node id of the node which is 11.
I've created a file named page--node--11.tpl.php in my theme directory containing some test html but it's not overriding the standard page.tpl.php file.
I've also tried using the following file names:
page-node-11.tpl.php
page-node--11.tpl.php

I've cleared the cache but still no luck.

What am I missing?

According to Drupal 7 Template (Theme Hook) Suggestions it should be page--node--11.tpl.php (note the double dashes):

  page--[front|internal/path].tpl.php
      base template: page.tpl.php
  The suggestions are numerous. The one that takes precedence is for the front page. The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for. Keep in mind that the commonly-used Pathauto module uses path aliases.

  The front page can be set at "Administration > Configuration > System > Site information." In Drupal 6, at "Administrator > Site configuration > Site information." Anything set there will trigger the suggestion of "page--front.tpl.php" for it.

  The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:

  page--node--edit.tpl.php
  page--node--1.tpl.php
  page--node.tpl.php
  page.tpl.php

  Also see page.tpl.php in the Drupal API documentation for more information.


Advice on how to fix Workbench Moderation error messages (n00b drupal person)

I seem to be suffering the problems described in https://drupal.org/node/1966908 and https://drupal.org/node/1966920.

Basically I have installed the following:

drupal-7.26.tar.gz
media-7.x-1.4.tar.gz
views-7.x-3.7.tar.gz
ctools-7.x-1.3.tar.gz
workbench-7.x-1.2.tar.gz
workbench_access-7.x-1.2.tar.gz
workbench_media-7.x-1.1.tar.gz
workbench_moderation-7.x-1.3.tar.gz

It all seems to be configured OK, but when I switch to My Workbench -> Create Content I get the following warning/error message:

  Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

  Warning: Invalid argument supplied for foreach() in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

  Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

  Warning: Invalid argument supplied for foreach() in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

  Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

  Warning: Invalid argument supplied for foreach() in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

Would very much appreciate some help with:

Confirmation I've got the right bugs
Some advice on fixing it... should really be using git patch rather than installing the updated modules to fix ?

OK, so I found a workaround, which is good enough for the timebeing... enable Views UI modules - https://drupal.org/comment/6971496#comment-6971496


Rules governing views-based free text search I have a search feature that uses Views. There is a search box 'filter' that's just a text box which enables users to input text to search the database. Pretty standard stuff.

I'm curious to know however if there are any rules governing how this search functions?

(Ie. if I enter one word, fine it searches on that term. However if I enter two terms I notice it returns no results, even if I know both terms are in a node and in that exact order!). But if I put two or (more?) words in double quotes " " it seems to return items that have both of those words, although not in that sequence necessarily.

Anyway, I'm just wondering if anyone knows if there is a list of rules governing a Views-based search text? thanks.

Note: my search filter is based off 'search: search terms'.

The rules controlling exposed text field filters are various SQL operators. To give you a good indication of what's happening, navigate to admin/structure/views/settings and enable Show the SQL query option for the Views UI then preview various views with different operators. As you enter different text, you can see the SQL keywords used to filter the view.

For Search: Search terms filter its based off the core Search index. The search module crawls node content, breaks it into text tokens, weights the score according to your settings (see admin/config/search/settings), and builds an index for terms to content.

In terms of fuzzy search technology Drupal's is pretty basic, but it works most of the time. If you're looking for more robust search options there are more advanced solutions out there (Google CSE, Apache Solr, etc.).


Why does deleting a node ALSO invoke hook_node_update? I need to respond to an update event and regenerate a file, but when the node is deleted, the file should also be deleted. However, the problem is, everytime a node is deleted, the hook_node_update is ALSO called, which regenerates the file.

How can I differentiate between a node being updated (NOT deleted) and a node being deleted?

Thanks for your answers, much appreciated!

I finally managed to find the cause. The "problem" is caused by the module https://www.drupal.org/project/field_collection. My node has a field that is a field_collection, and apparently, when deleting a node, the field_collection items are first deleted from the node, which is then saved (which causes the update hook to fire), and only then the node itself is actually deleted.

It's pretty easy to workaround this issue once you actually KNOW what is causing it, in my case I modified the update hook to check for field_collection items in the node, if there were none it means the node is about to be deleted...


Display Users emails with views I want to display the users emails with views, but it doesn't show for the users, only the administrators can see them.

How can i display them to the users with views, and i have a warning: Email address for a given user. This field is normally not shown to users, so be cautious when using it.

I found a way to do it by using user_presave, i created a field_profile_email field using this answer : https://drupal.stackexchange.com/a/205308/65949


What is the difference between drupal/drupal and drupal-composer/drupal-project packages? I want to use composer with my future Drupal projects. I installed Composer on my machine and I noticed two packages (drupal/drupal and drupal-composer/drupal-project). When I install the second package, I get a warning message telling that there is no stable version.

What are the difference between those two package?
Is it composer enough for Drupal, or should I use Drush with it?

drupal/drupal

This is the main repository for the Drupal project and is used to generate the tarball which is available for download on Drupal.org. This package is not used (directly) if you are using Composer to manage your codebase.

drupal/core

This is a subtree split of drupal/drupal repository which contains everything in the parent repo's /core directory. This is the package that is used if you are using Composer to manage your codebase.

drupal-composer/drupal-project

This is a "scaffold" project and serves as a starting point for your root composer.json file. This package isn't maintained by the Drupal Association, but it has become the de facto standard for assembling a Drupal codebase with Composer. It does a few things:

It brings in the drupal/core package and couple other requirements needed to assemble and run a Drupal site (composer/installers, cweagans/composer-patches) and a few nice-to-haves (drupal/console, webflo/drupal-finder, ...).
In addition to the packages listed above, it requires the drupal-composer/drupal-scaffold package which is responsible for assembling all the stuff normally provided as part of the tarball that's needed to run a Drupal site that lives outside of the /core directory (index.php, update.php, etc).
Contains instructions for composer/installers that tells Composer where to put stuff like modules and profiles.
Defines the Drupal-specific packagist repository.

Typically, you don't require or clone scaffold projects. They are intended to be used as starting points for projects of your own. You would use the create-project command instead:

composer create-project drupal-composer/drupal-project

There are other scaffold projects out there with more opinions or different focuses (BLT, Drupal CI) and most D8 Distributions provide a scaffold project (Open Social, Lightning, Thunder, etc)


maintenance mode after error occurs while running update Error occurs While I'm running update for my drupal site.  And it stuck in maintenance mode.
I can't log in to it using /user/login.

I changed $update_free_access = TRUE in settings.php and run update.php.
And I see this screen.

It says ctools module is missing.
How can I re-install module when I can't login as administrator?

[Edit]
In the hope of getting the module back, I restored the database with my backup sql-dump via phpmyadmin.
After that, it came to 500 internal server error.

I don't know what was wrong?
Is there any way I can restore my site back on?

Thanks in advanced!

Most housekeeping tasks like these can be done using Drush, a Drupal command line managing tool. For example, you can reinstall the module using

drush pm-disable modulename
drush pm-uninstall modulename
drush pm-enable modulename

the database can be updated by issuing

drush updatedb

And code is easily updated with

drush pm-update

To use drush you need a shell access to a server your site runs on. No authorization as Drupal user is needed.


Display a block on some pages according to the fields content of that page I created a content type called people, where I create personal pages using that type. One of the fields is 'area'.

Then, I created a view of block called 'software people', where I list all the people who work in software area. I want to show this block only on the pages where the person's area is Software. How can I achieve this?

Thanks

Simplest way is to conditionally output region in node.tpl.php
But there is no $page in node.tpl.php. So you need to make it happen. In your template.php add function

mytheme_preprocess_node(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

Then in node.tpl.php use:

print render($region['region_name']);

to output your region. Of course wrap it in if, case or any other logic you fancy.


Adding a form to a product drupal commerce I just want to add a form to a product and after I check the services in that form the amount increases. image of the page in the Picture the product price is 7$ but when I add the service it added 10$ then the amount become 17$. any solution for this?

Your looking for product variations. Here are the official docs.

  Product attributes are the descriptors we use to define kinds of
  products. For example, we could describe a tshirt by the color and
  size. These attributes mean that in the real physical world your store
  may only carry one red shirt, but you have three sizes or three
  "variations." Commerce software must deal with product variations in a
  flexible way. Here's how Drupal Commerce abstracts it:

  Product Types. A product type is a specific bundle based on a custom
  product entity. Each bundle can have fields attached to it, including
  pictures and other kinds of information.<

  Product "Informational"
  Fields. Any field on a product can be a simple "informational" field.
  Typical informational fields include an image of that specific
  configuration of a product. For example, if you sell a tshirt with a
  cool print in multiple colors, each product with a different color
  could have an image field that, when displayed on the product display
  node, will change when you select different attributes (like color).

  Product "Attribute" Fields. Any field on a product type with a defined
  list of options (list of text options, list of taxonomy terms, list of
  colors). The attribute fields are special because of the way they turn
  into selection widgets on a product display. Often you will pair an
  attribute field (like a color dropdown) with an information field
  (like an image field) to let the user "select" the blue tshirt and the
  Drupal Commerce system will quickly load the picture associated with
  the blue product.

  Product Displays. If needed at all, these are
  groupings of products. You can reference any type and number of
  products on a product display. In order to make use of product
  displays, we recommend only showing one type of product per product
  display. The product display is where you typically see the product
  with drop downs to "configure" or "order" the right kind of product.

For the different pricing of the variations refeer here: Automatic product variations pricing.


Which external frameworks does Drupal use, if any? I'm looking for ways to prepare and ease a transition to Drupal.

My department is planning on completely rebuilding our custom CMS in Drupal. There are 4 members on the team, two programmers. I've been researching ways to ease the learning process, as only our manager is familiar with it and he's not a developer.

My question is this: Is it possible to integrate any of the specific technologies or practices that Drupal uses in generic PHP-based websites? For instance, Drupal 8 will use Twig.

Are there other technologies or plugin components that we can learn and use before we start the process of moving to Drupal?

Theme-wise there are a couple of very good base themes that make use of SASS/Compass (and therefore Ruby) such as

Omega, and
Zen

(I prefer Omega, having just discovered its power).

There are some good integration modules such as LDAP for single sign on, and loads of third party service integrations from paid services such as MailChimp.

But, when it comes to handling the database and rendering pages, the core system really shines.  I'd really recommend learning Drupal's database API because it does an excellent job of defusing potentially unsafe queries and is quite easy to use once you get the hang of it.

[edit] Another resource I keep going back to time and again is the form API.


Prevent certain user roles from showing up in results I have a special role (role A) that I have to have set with view user profiles permission. I then have another role (role B) as well as the administrator role that I don't want for that roles users to show up in a views exposed filter and/or for the users with role A to be able to view their profiles. Is there:

a. a way to stop users from certain roles showing up in the exposed filters.

b. a generic way (or module) that stops certain roles being able to view other certain roles.

UPDATE:

I solved b with this module which works well:

http://drupal.org/project/view_profiles_perms

So just need to come up with a way of preventing certain roles from showing in a views exposed filter

For A.

Set up another filter in your view for "User: Roles". Choose the Operator "Is none of" and then, choose in the options the role you dont want seen. You can use the roles filter after the exposed one.

Attached is a pic of the user:roles filter section. The options are cutoff to the right (taken from a working site..want to leave the role names private)

You can also expose the role filter and, limit it to the selections you choose in the options pane.


How do I send an email when users update their email address? If users update their email address, an email should be sent to the old and new email addresses to confirm the transaction.

How can I achieve this in Drupal 8?

You could add a HOOK_user_presave method in your custom module.

Example:

function mymodule_user_presave(\Drupal\user\UserInterface $user) {
    if ( !($user->isNew()) ) {
        //check if the value in the db is different to the value in $user
        if ($user->original->getEmail() == $user->getEmail()) {
            // send email
        }
    }
}


How to make the date field of authoring information in Create Article page a date field? In the page to create new article, at the bottom in the authored on tab, how do I make the date textbox to a date field with date picker? I mean, I want it to be easy for the publisher to choose custom date.

Use Date Popup Authored module.

  Date Popup Authored provides a jQuery UI datepicker for the Authored
  on date field found on node submission forms.

  This allows content editors to pick a human-understandable date and
  not have to type the exact date format of the default Authored on
  field.


Event Specific Webform Submissions I have a bunch of events that users should be allowed to register to. But I am trying to use one basic form that asks for the following fields:

First Name
Last Name
Phone Number
Email
Gender

I was wondering if there is a way to connect that form to a specific event. Is it possible to have a submissions field that is hidden from the user that auto populates with the node ID or something similar to that approach?

Any help would be much appreciated! Thank you!

I suggest you to use entityforms instead of webforms.

And then, you should enable entity tokens and Field default token modules.

Now you can add a text field to your entityform, which contains URL of the current page as the default value.

After that, you may hide that field by CSS.


Update to Commerce shipping 2.x breaks site with WSOD Implementing shipping 2 is becoming a bit more troublesome than i had anticipated.

Right now, I am getting the following error on a White Screen of Death when I install commerce shipping 7.x-2.0-beta1

Fatal error: Call to undefined function commerce_shipping_services() in /var/www/html/nidadev/sites/all/modules/contrib/commerce_shipping/commerce_shipping.rules_defaults.inc on line 44

I am not sure what to make of this Is there something obvious that I am missing?

Is there some sort of update to rules I need to perform?

The problem goes away when I go back down to Shipping 1

This issue is standing in our way of working with Tim Rohaly on the Fed Ex Commerce module, so the quicker we fix this, the quicker he can get his code out to the community.

Thanks for any help

The 7.x-2 branch of Commerce Shipping is only in beta, it's not ready for production use yet (but you probably already know that).

The release notes for the branch warn you not to install this on a site that currently uses v1.x of the shipping module:

  Note: If you are currently using Shipping 1.x on a live site, do not attempt an update on your live site. See the roadmap below for more information.

(emphasis theirs, not mine!)

I would heed that warning if I were you :)


How do I automatically generate image styles? How do I automatically generate different image styles in Drupal 8, for existing images?

For example, I have about 10K images in field_image field. I would like to generate thumbnails using my thumbnail image style for those images.

Image derivatives will be automatically generated once requested and not-yet existing.

But if you are asking how to programmatically create image derivatives checkout ImageStyle::createDerivative.

Here's a sample snippet were I did exactly that:

$field_name = 'field_my_image';
$image_style_name = 'my_image_style';
$image = [];

// Get the original image URI.
$original_image = $node->{$field_name}->entity->getFileUri();

// Load the image style.
$style = \Drupal::entityTypeManager()
  ->getStorage('image_style')
  ->load($image_style_name);

// Get the styled image derivative.
$destination = $style->buildUri($original_image);

// If the derivative doesn't exist yet (as the image style may have been
// added post launch), create it.
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}

// Do whatever else you need to do.
$image['url'] = file_url_transform_relative($style->buildUrl($original_image));
$properties = $node->{$field_name}->first()->getValue();
$image['alt'] = $properties['alt'];
$image['title'] = $properties['title'];


Can I rename index.php? I am going to replace the front page of a Drupal 6 site with a new index.php. How can I rename the Drupal 6 index.php (say, to drupal.php) and keep the Drupal site functions working? For example, I'd like to have all the URL aliases work as before.

Is changing:

RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

to:

RewriteRule ^(.*)$ drupal.php?q=$1 [L,QSA]

in .htaccess all what I need?

I need Drupal to co-exist with another site (which should be load by default) in the same http doc directory, and to keep existing Drupal functions (a few webforms).

Others have advised you not to do this. I too remain in that idea, but to answer your question:

Can Drupal even run without index.php? Can it be a different file name?

Technically it's possible for Drupal to run on any different directory index file name. But you need to configure your web server for that first. Unfortunately you will need to hack core as well, which is considered without-doubt a bad idea.

.htaccess changes

Assuming you are using Apache, and because it can automatically detect http://example.com?q=node and http://example.com/drupal.php?q=node if the DirectoryIndex drupal.php, you will only need to change the .htaccess file.

if your web server is not Apache and if you can't configure it to above URL patterns, you have to modify line 1518 in common.inc as well (Drupal 6.31).
Things will get much complex in Drupal 7.x. You will have to make several hacks which you will find difficult to maintain patches for.

In your .htaccess, change these (using "drupal.php" as the new file name).

ErrorDocument 404 /index.php to ErrorDocument 404 /drupal.php
DirectoryIndex index.php to DirectoryIndex drupal.php
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] to RewriteRule ^(.*)$ drupal.php?q=$1 [L,QSA]

You will probably need to modify your unit tests and shell scripts as well.


How to scan a directory to list all sub folders not files I have a folder (root folder) with thousands of sub folders and *.json files inside sub folders. How can I get list of sub folder names inside folder (root folder) using file_scan_directory?

If file_scan_directory usually returns directories then perhaps you can use the regex mask to search for names that don't have a dot (.) in them.

There are very few files in a Drupal installation that don't have an extension, and I imagine there will be none in your folder structure if all it contains is .json files...

file_scan_directory($your_root_folder, '/^[^\.]+$/');

The above should match all items in the directory structure that don't contain a dot, thanks to this answer.


How to fix Openlayers "Unable to load CTools exportable" errors So, Openlayers 3.1 and 3.x Dev both have this issue. I've looked and this issue has been reported as fixed in the Drupal Openlayers issues list.

The issue is that everyone of my added layers, components, and sources each triggers these errors:

Unable to load CTools exportable Component (ol_users_geojson).
Unable to load CTools exportable Component (ol_geojson_chapter).
Unable to load CTools exportable Component (ol_geojson_reg_gr).
Unable to load CTools exportable Component (ol_geojson_alum).
Unable to load CTools exportable Component (google_base_layer).
Unable to load CTools exportable Component (users_popup).

Most of these components works in my map, except the popup, but that's a different issue. Part of the issue, is that this error is displayed prominently on my map page, even to regular users. What confuses me, is that for each of those components I'm following the OL examples, so I don't know why my custom implementations don't work. I speculate that this might have to do with the fact that the openlayers examples are all defined in code in the module, while my custom implementations are saved to the database and there might be an issue in how they are written there. There was an issue in the 2.x that some of the style component settings were getting mis-written to the db, but I haven't been able to find where in the db these are written to. From what I can tell, when I export my custom components they match those of the examples, so I'm not sure what's going on.

So, my question, which isn't obvious from the issue queue, is: is there anything I can do to fix this (patch, etc)?

I just got an answer from the Openlayers issues cues. The unable to load CTools errors exist when the module is looking for a missing or deleted component of a map.

In my case, I had to re-install my OL module and reconstruct the map with just the components I needed. It took some trial and error to get there.


How to Display children on the Taxonomy term page? I think my problem is quite simple but I don't manage to find the solution on the internet (I found solution for Drupal 7, but they don’t apply to Drupal 8).

I have a taxonomy like :

  Fruits

       Red fruits

             Strawberry
             Raspberry

       Black fruits

  Vegetables

Using Views in Drupal 8, with the preconfigured Taxonomy term, I'd like that when I click on a parent, it displays all the children terms and the nodes within these children terms. (eg. when I click on Fruits, it display all nodes in Fruits, Red Fruits, Strawberry, Raspberry and Black fruits ; and when I click on Red fruits, it displays all nodes within Redfruits, Strawberry and Raspberry).

Indeed, by default, when you click on a parent term, it only shows nodes within this parent term, but not those who belong to children. (eg. when I click on Red fruits, it only display nodes within Red fruits, but not those in Strawberry or Raspberry)

I finally found the solution. My Drupal is in french, I tried to translate, but my translation may not match the exact words :)

Go to View and edit the default Taxonomy term (content) page.
In Contextual filters :

select "possède l’identifiant de terme de taxonomie (avec profondeur)" and configure like this :

depth : choose the depth you want
check Allow multiples values
check Provide a default value and choose Taxonomy term (ID) from URL
select Filter by elements that share all terms
check Override title and write {{arguments.tid}} in the field
check Specify selection criterion and choose Taxonomy term (ID)

select "possède l’identifiant de terme de taxonomie avec modification de profondeur"

Now, if you have a complex taxonomies, go on a taxonomy term page may display the same result several times. To prevent this, in your View, go to Other section (under Contextual filters) and click on Query parameters. Then check Distinct.

Enjoy !


D7 Field template syntax My D7 content type has a field for an MP3 file. I want the field to display as an image which the user can then right click to download the file ie like this. My field template file looks like this:

<?php
$link = 'http://www.desertcow.co.uk/pirates.mp4'; // url link?>
<a href="<?php print $link;?>">

<a href="<?php print render($items); ?>">

<a href="<?php print render($items); ?>

The result is here and you can see that the syntax for the pink and red boxes is not correct.

Can anyone please tell me the correct syntax or is there some reason that this approach is not going to work?

Thanks...

This is because you're rendering the full item when all you want is the url as a string, if you add this line of code in the template you will be able to see where the url is held in the $items array.

<?php var_dump($items); ?>

then you can find the part of the array where the url string is so your final markup would be something like this.

<a href="<?php echo $items['url']; ?>">


Configure Menu Access Visibility and permission I have a question for Menu Visibility.  I have an entire live site in production. I am trying to build editorial workflow for my editors, other editors and approvers. I am using Workbench Access and Node Access module.

I wanted to set access permission for menu. Currently, when user create a content, he can chooses menu item from entire "Main Menu section". I don't want them to add any new page in main menu(Home page) as it will ruin my design.

Currently, my menu structure is:

- Main Menu (Home)

About (Parent 1)

Child item
Child Item

Admissions (Parent 2)

Child Item
Child Item

(Parent 3)

Child Item
Child Item

(Parent 4)

Child Item
Child Item

I don't want user to add any content directly in main menu(home page). I want them to just see parent menu items when they create new content and can add them in menu in any parent item or child item. but NOT in Main menu(Home).

I also found two modules but not sure if these are right choice or not.

1) Menu Item Visibility

2) Menu Admin per Role

Thanks!

If you edit the content type's menu settings, you can see the menus allowed, you can also set the default parent item.  You could set up multiple content types with each one representing one parent, then remove the permission to change menu settings.  That way each content type will pick the appropriate parent automatically.


Extending the Year range in Popup Calendar I am trying to extend a year range of a popup calendar in drupal 7 but have been unable to see where I can do this.

After doing more research, I discovered that I can change it through the 'More settings & values' option in the field settings which I have seen in other people's screen shots except that I don't seem to have this option at all when I go into my field settings.

I am using the date field and having it display as a popup calendar but cant find the year range setting anywhere - is there something else I need to enable to find this or has anybody else had a similar issue?

I'd be happy to even change some code in one of the files, but I havent been able to find the right one.

Many Thanks

Step 1 :
   Edit the file date_year_range.js located in this path : sites\all\modules\date\date_api\
Step 2 :
   Locate this line : Line 67 start = Math.min(this.getOriginal('int'), -n) n is the number you specified in your Drupal
Step 3 :
   Replace n with the value you want, for example for the field date of birth i want 60 years besfore today
Step 4 :
   Go back to your web site, edit the content type, then manage fields and change more settings and values of your date field.


Clear (not reset) Views Exposed Filter Values I know i'm looking at this wrong and am running into a wall over and over again on this.

I have a view with an exposed filter in a block.  I am looking to clear / reset the values in the block without reseting the view, so the default reset button in views doesn't cut it.  Any Opinions?

I'm pretty sure that the better exposed filters module has an option for a reset button, but it may reset the view too.

You could also add some javascript that listens for the click event on the button and resets the fields you want.


How do I attach views to nodes? I have created a page called 'Page1' of Content type 'Article' - I have created a  View1 in Views and would like to know how to add that view to my page.

Does Views replace the needs of the 'add content' button on my admin page?

Create a view with 'Block' display. After it is created, make it display on the page you want.

How:

Go you sitename/admin/structure/views/add
Unchecked create a page option
Check Create a block
Give the Block title and select your desired display format
Click Continue & edit
Setup your view as per you wish
Click Save
Go to sitename/admin/structure/block
Look for your new view block "search for block name you give early while creating the view"
Click configure
if you don't want your block title replace your Block title with
Select in which region you would like to have your view
Go to end of the page, under Show block on specific pages select "only the listed pages"
enter the url of page you want your view to be available, for example if your page url is www.your_site/page1. Than add page1 in the box.

Please note you can add as many pages as you want and you can also use content type of specify in which node type you want your view to be visible.


Boolean single on/off field - how to make it NOT render the off option? I'm having some issues with boolean field. I want to have few fields that can be turned on/off, which will be used to show if something is available in the content.

So I thought single on/off checkbox is the way to go. Well, apparently not because even if I don't select the checkboxes, they're still rendered in the code. And I need them to NOT render.

Checkboxes/radio buttons works in this way, but it creates 3 selectable options (on, off, not available) whether I would like to have only one checkbox.

I also tried using List (text) for my needs, but here I'm limited by the fact I can't add individual CSS id/classes to every item in the list.

My target is using these lists/checkboxes, hidding them in CSS and replacing with icons. I did something like this few months ago but now I can't remember how exactly I achieved what I needed.

You can hide them either through CSS or you can unset them using the form_alter if you are using forms. Look at the code below
In this code, I am unsetting the author on the comment form.

function Mymodulename_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    if($form_id == 'comment_form) {
      unset($form['author']);
    }
  }
}

If you've added the field to some node then you can unset them using this code.

unset($node->field);


Conditional fields on block add form I have a custom block type created through the UI and I used the configuration files to export it to a module.
My custom block type has two fields and I want users to be able to fill out one or the other, but not both.

Is there way to implement that logic through the UI?
If not, how can I create the custom block type in code and add this logic?

i just found this module that is supposed to do that
https://www.drupal.org/project/conditional_fields
I believe a form alter function on a module should do the trick however i haven't implemented anything like it.
Good luck.


Ajax: how to prepend my callbacks? I have an e-commerce based on Drupal + Commerce module.

My add to cart form use Ajax to reload itself when the user make a choice (item attributes, like color, size, etc..); Everythings works just fine but i need to add an overlay that hide the form just before the Ajax request is sent to prevent the user to click another option before the request has completed (and the form reloaded).

Basically, I need to add my own callbacks in the beforeSend and success events, but I have no idea on how tell Drupal to invoke them for (and only for) this specific form.

edit: I need to add a Javascript Callback, not php.

Any help?

Edit
Mathankumar's solution indeed works, something like:

$(document).ajaxSend(function(event, request, object){
    request.onloadstart = function(){
        $("form.commerce-add-to-cart").css({'opacity':0.5});
        $("form.commerce-add-to-cart input").attr("disabled", "disabled");
    };

    request.onloadend = function(){
        $("form.commerce-add-to-cart").css({'opacity':1});
        $("form.commerce-add-to-cart input").removeAttr("disabled");
    };
});

works BUT i dont like this thing to be run for every ajax call.

I digged the event, request, object parameters of ajaxSend, but i was not able to find nothing about the form_id or something to tell the add_to_cart_form requests from others, any help is appreciated!

You can use the following snippet,

jQuery('body').ajaxSend(function((evt, request, settings)){
  if (settings.url == "<something>") {
    // Perform your operations
  }
});

However this function will be called for all the ajax requests, so you need to have perfect condition to determine the right URL.


Using comment view modes I can use the UI to create a new view mode for a comment type in Drupal 8, without problems, but I don't see how to use that view mode.

For example, I just want to have a teaser that shows only the first few lines of each comment, and not the comments on this comment.

How do I specify a particular view mode should be used for the comments on a particular content type?

Does this require Display Suite?

There isn't a way to do this without writing your own formatters. However, could you open a feature request in the core issue queue as this is a worthy configuration option for the existing formatter.


Adjusting Height of Panel Columns using CSS I am using panel-2col-brick to make a 2 x 2 information block. The HTML structure of the page is as follows

Now i need to change height of the second occurrence of panel-col-first and panel col-second. I have tried

.panel-2col-bricks .center-wrapper .panel-col-first:first-of-type,
.panel-2col-bricks .center-wrapper .panel-col-last:first-of-type{
       height:80px;
       overflow:hidden;
}

However this changes  the height of both top-first and bottom-first columns. Is there any way i can adjust height of both rows separately ?

to achieve this you need make use of CSS pseudo selectors and apply them in the correct element, a good approach can be this:

.panel-2col-bricks > .panel-panel:nth-child(2) .center-wrapper .panel-col-first,
.panel-2col-bricks > .panel-panel:nth-child(2) .center-wrapper .panel-col-last

You can see this in action in the link below:
https://codepen.io/anon/pen/xBZGGb


How to redirect the checkout complete page? In my Drupal Commerce site, I redirect to a local payment API with a custom module after the user selected the local payment gateway in the review order page. The users enter username and password in the local payment website; if the user is authenticated successfully, the payment gateway server redirects back to my localhost at http://localhost/commerce/sites/all/modules/paymentgateway/CheckoutComplete.php.

In that page, the pay button exists; the user has to click the pay button to finish the payment transaction. After finishing payment, I want the server to redirect to Drupal Commerce's checkout complete page, e.g. http://localhost/commerce/checkout/93/complete.

How do I redirect to this link? Do I have to implement a hook?

In this payment structure with local payment gateway, I have to pass product item lists, return url and cancel url to local payment gateway through drupal commerce’s Local Payment Module. If detail information of this payment is returned, in that page I redirect to the this link http://localhost/checkoutComplete/completeCheckout .

Checkout_complete.admin.inc

function checkout_complete_loadAllrecord()
{
    //current orderId
    $paraorder = variable_get("order", "");
    $order = commerce_order_status_update($paraorder, 'checkout_complete');

    //assign order status to checkout_complete
    $order->status = "checkout_complete";

   //calling this method order status will be changed to "Checkout_complete", this method will fire commerce_checkout_rule()
   //In commerce_checkout_rule(), we can send email to client to notify checkout is complete.
    commerce_checkout_complete($order);

    //redirect to order completed page
    drupal_goto(commerce_checkout_order_uri($order));

}

Thanks


How can I make or render a website with wiki features(for e.g wikipedia) with Drupal? The question is can I render wiki features in my website which is to be made with Drupal.For e.g if I make a website with tons of features how can Wiki feature be made functional with Drupal.If no should I make new themes.

To allow contributors to easily link between multiple pages, check out the Freelinking module.

To enable simple plain-text formatting, check out the Markdown module.

To allow editing subsections of text individually, check out the Edit Section module.

To automatically generate a Table of Contents for each node, check out the Table of Contents module.

To move comments to a separate page (similar to the Wikipedia "Talk" pages), check out the Talk module.


How to set the comment body field to be required? I have created a comment section in my node. But it is not displaying the required option. if the comment is posted no validation occurs.

For What ever content type you are giving comments options, you need to go to

structure >> Content types >> Edit the particular content type >> there will be comments fields tab >> over there  will be list of comments field, in that    comment_body(machine name) wil be required by default.

If not, make it required by editing that field.


How to create user input dependent form elements? I have created a form and it has multiple elements. Is there a way to show specific form elements depend on a slelect box selected value.
For an example my select box has 2 options. if i select option 1, form will show a text box after the select box. if the selected option is 2, form will show a another select box
after the first select box.

Yes it is possible and quite easy. Read up on the #states value in the drupal form api documentation. I am assuming this is for Drupal 7...


Restrict Menu options when building Nodes Drupal 7, when creating a basic page I want the users to be able to add a menu item as a sub item only under local menu items, not under items that link off site. How can I restrict the list of menu Parent item to only ones that point to node/# and not display any that are absolute urls?

What I ended up doing was using TEMPLATE_form_node_alter() and creating my own duplicated versions of menu_parent_options(), _menu_get_options() and _menu_parents_recurse() so I could call them instead of the default drupal functions to build my menu. And in _menu_parents_recurse() you can access the link information like link_path, and just set the menu links I wanted to exclude.

function _my_menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
  foreach ($tree as $data) {
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }
    // Exclude menus that are absolute/external
    if (stripos($data['link']['link_path'], 'http') !== false) {
        $data['link']['mlid'] = $exclude;
    }
    if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
      $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
      if ($data['link']['hidden']) {
        $title .= ' (' . t('disabled') . ')';
      }
      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
      if ($data['below']) {
        _my_menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
      }
    }
  }
}

I was hoping for a more "correct" method (hook_preprocess_link maybe, but it doesn't exist in D7, only 6 and 8) but this one works.


"fwrite(): supplied argument is not a valid stream resource" drush throws an error

  "Notice:  Use of undefined constant STDERR - assumed 'STDERR'
  in /kunden/192766_10587/bin/drush/includes/drush.inc on line
  1668  Warning:  fwrite(): supplied argument
  is not a valid stream resource in
  /kunden/192766_10587/bin/drush/includes/output.inc on line
  34

What I did is the following. (I followed the instruction from the README.)

Cloned drush

git clone --branch 7.x-5.x http://git.drupal.org/project/drush.git

Wrote into the ~/.bashrc

export PATH="$PATH:~/bin/drush:/usr/local/bin"
alias drush=~/bin/drush/drush.php

Refreshed the bashrc

source ~/.bashrc

Set the 'drush' command executable:

 chmod u+x /path/to/drush/drush

Drush is working but it shows errors every time.

What did I do wrong?

You should not run drush.php directly.  It is preferable to define DRUSH_PHP, like this:

export DRUSH_PHP='/usr/local/bin/php'

Then you may continue to use the drush script as usual.  This is documented in the README.


PHP based node access control Is there any way that I can use a custom PHP code to control the visibility (proper Drupal access) of a node?

Something similar to content access module, but instead of access control by role, I'd like to have access by PHP code so if it returns true, users can access that node, if not, the node will be access denied?

You might be able to do that by using the HOOK_NODE_VIEW(). In my experience I have had great success using the ACL and content access modules as you can control the view, edit and delete function of the nodes by roles, but also a the node level you can specify what user(s) can have access and what type of access.


hook_library not getting called I am trying to implement hook_library in my custom module.  To help narrow down the problem, I wrote a dummy module with just the following two functions:  hook_views_api and hook_library.  I put a dsm statement in each of the hooks, to test whether the hook was getting executed.  The hook_views_api hook is getting executed but not the hook_library hook.  Anyone see what I am doing wrong?

I have tried clearing the cache.
I have tried uninstalling and reinstalling the module.

Here is the code:

// hook_views_api
function mymodule_views_api() {
  $path = drupal_get_path('module', 'mymodule') . '/views';
  dsm ("inside mymodule_views_api");
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'mymodule') . '/views',
  );
}

// hook_library
function mymodule_library(){
  dsm ("inside mymodule_library");
  return array();
}

The only function that invokes hook_library() is drupal_get_library(), which is then called by drupal_add_library(), the function that modules call to add a library during a page request. Until one of those functions is not called, hook_library() is not invoked.


How to implement a taxonomy view? I would like to show a list of taxonomy terms and include:

number of nodes that are linked to this term
datestamp of latest node with author and title that is linked to this term

Can this be done in a view, or do I need a custom query?
From a performance standpoint, wouldn't it be better to save that info in taxonomy fields?

Try to create a View using grouping.

Set Format to Table
Go to Settings > Grouping field = "Tags" (your taxonomy term field)

Field "Tag" should have this setting:

Exclude from display [X]

There are some modules I didn't try that could help you with adding summary field to your Views:

Views PHP (D6 + D7) or Views Custom Field (D6)
Views Calc (D6) or Computed Field (D7)
Views Group By (D6)
Views Summarize (D6)
Views Hacks (D6) (including Views Taxonomy Summary)
Views Taxonomy Edge + Taxonomy Edge (D6 + D7)
Better Exposed Filters (D6 + D7)
Taxonomy Views Integrator (D6 + D7)


How to implement upgrade for fields I wrote a module that defines its own node type, adds the appropriate fields, etc.  How do I write an upgrade function if I wanted to change, remove, or add a field to the type?

You should be aware that once there is data In the tables created for your fields, it's limited what changes you can make.

Anyways want you need to do, is to use hook_update_N in your module's install file. The number N should consist of 4 numbers

Major release of the module (the drupal version)
Minor release of your module.
Number
Number

3-4 is just a combined number that should increment for each time you need to use the hook.

The field module provides a host of functions to add, change and remove fields. You can use those to do what you need.


In view, add a sample no global "link" field foreach row I created a view from the user interface. This view shows some content of a type of node.
For each node displayed, I want add a field "mylink custom" in this view for show a generated link.

I generate the link from a custom module, I want change the link according to the node displayed by the (row) view and some current user parameters.

How can I do that ?

I add a "Global : Custom text" default field in the user interface, but this field is global ! When I want get his value from a prerender hook view, I get only the global value for all nodes displayed in my view. But I want set a different value of my "custom link field" for each row of my view.

I didn't add a new field in my node structure because I want just display a generated text when the user go to the view page. I don't want save this value in each node because this text change each time an user go to the view page.

Thanks for help =)

I find how do with this usefull guide

I created a custom field and I added it to my view. The content of my field is defined in the render method of the FieldPluginBase Class.

In addition, we can quicly and properly generate a FieldPluginBase Class and views.inc with drupal console (command 'drupal gpcf')


Add a vocabulary and a term-reference field or just add a select field? I have various content types which have sub-types in my Drupal 7 site. e.g. "downloadable resources" content type, and within this there may be reports, presentations.

Is there any reason not to add this to a select field with a list of value=>label pairs?

Should I create a separate vocabulary for these options and add a new field referencing that terms? I have a couple of other content types similarly modeled, so I would end up with a load of very small (2-3 terms) vocabularies.

Taxonomy seems to be favoured but instinctively it seems overkill?

Edit: or is it better to have very granular content types (report, presentation...), even though the fields are the same between them?

As @reptilex mentioned, the answer to this question is going to vary depending upon your very specific situation.  There are a lot of helpful documentation resources and blog posts floating about with good advice about making this decision.

drupal.org Guidelines for Taxonomy Design
blog - How to Decide Between Taxonomy and CCK to Classify Content
blog - Drupal Taxonomy vs. Content Type Field


How can I load a custom twig template depending on a view mode? Currently I have the following code in my module file:
function mymodule_theme_suggestions_credit_report(array $variables) {
  return [
    'pdf_report__' . $variables['elements']['#view_mode']
  ];
}

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'pdf_report' => [
      'render element' => 'elements'
    ]
  ];
}

And I have inside /mymodule/templates/ 2 twig files

pdf-report.html.twig (just added the code from entity-html.twig)
pdf-report--new-style.html.twig

And I have a view mode in my pdf-report called new_style.
I've read documentation and it looks like this should work, but it doesn't.
I tried doing the following:
function mymodule_theme_suggestions_credit_report(array $variables) {
  return [
    'pdf_report__' . $variables['elements']['#view_mode']
  ];
}

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'pdf_report' => [
      'render element' => 'elements',
      'template'  => 'pdf-report--orcutt-style',
      'base hook' => 'pdf_report',
    ]
  ];
}

But this replaces all of the view modes, not just the one I want.

Now the new theme hook is the same as the base hook. You need to declare the more specific theme suggestion as hook:
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'pdf_report__new_style' => [
      'base hook' => 'pdf_report',
    ],
  ];
}


How can I change the author of a node before it is saved with hook_entity_presave()? I have added code in a node presave hook before cloning a node as below to change it to the current user id

 $entity->setRevisionAuthorId($current_user);

and then I check with $entity->getRevisionAuthor and it has been changed in that presave function, however upon saving the author reverts back to the author of the original node that was cloned.

What is happening ? thanks

I added $entity->setOwnerId($current_user)  and that worked


Anonymous Flag with boost module enabled I have a node type which allow anonymous to use flag (Non global flag).

The problem is with Boost enabled, all anonymous users have the same flag status at the cached page.

For eg, anonymous A Bookmarked a node and the page get cached, when anonymous B visited the page she has the Bookmarked status as well which is undesirable.

How should i update the flag status by user?

Any suggestions are welcome!!

I'm not too sure, but you'd need to look into how Flag is handling the anonymous user session cookies. You may have to hack the code to add your own user-id and add it to the cookie...