The Imagefield Crop module allows a user to crop the image after upload.
Here is a quote about it (from the module's project page):

When the user uploads an image, the image is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking 'preview' or 'submit', the image is cropped and the result is saved instead of the original image.
Features:

Seamless, intuitive cropping, almost like using a desktop photo editing app
All major browsers supported
Dynamic preview - you see how your crop will look like, in real time!
Original image is saved for recropping.
No matter what resolution the cropping area is, the original image is used for cropping (for highest quality)
The sizes of the cropping area, cropping box and resulting image can be controlled by the administrator


Not able to add new CCK field to custom content type

Most likely either JavaSript or AJAX failure is giving you problems. Check your browser Javascript error messages with a tool like Firebug, and check your server log.

Alternatively you can disable the javascipt enabled interface entirely.


how to add the value of a (list text) field as a class

For view field, please implements template_preprocess_views_view_fields()

Reference: https://www.drupal.org/node/1407442#comment-6509858

Code Example

// assume the field name is 'field_text' and
// view name is 'text and view display id is 'page'
function mymodule_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'test' && $view->current_display == 'page') {
    foreach ($variables['fields'] as $id => $object) {
      if ($id == 'field_text') {
        $field_output = $view->style_plugin->get_field($view->row_index, $id);

        if (!empty($field_output)) {
          if ($object->element_type) {
            $class = '';
            if ($object->handler->options['element_default_classes']) {
              $class = 'field-content';
            }

            if ($classes = $object->handler->element_classes($view->row_index)) {
              if ($class) {
                $class .= ' ';
              }
              $class .=  $classes;
            }

            $class .=  ' ' . drupal_html_class("value-$field_output");

            $pre = '<' . $object->element_type;
            if ($class) {
              $pre .= ' class="' . $class . '"';
            }
            $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
          }
        }
        $variables['fields'][$id]->content = $field_output;
      }
    }
  }
}

For node field, please implements template_preprocess_field()

Code Example

// Assume the field name is 'field_text'
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];
  if ($element['#field_name'] === 'field_text') {
    $value = $element['#items'][0]['value'];
    $variables['classes_array'][] = drupal_html_class("value-$value");
  }
}

Note 1: I would recommend using lower case for class name.
Note 2: view_field_name is different from node_field_name


How can I setup multiple database connections?

This is done in the same way as in Drupal 7: You can add the database credentials in your settings.php file.
$databases['default']['default'] = array(
  'database' => 'drupal8',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['external']['default'] = array(
  'database' => 'external',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

You will now have two connection options, default and external. You can tell Drupal to use the external connection using \Drupal\Core\Database\Database::setActiveConnection('external') and switch back to the default one with \Drupal\Core\Database\Database::setActiveConnection() once you don't need anymore the external connection.


Problem adding button to custom content type form

Ok found the problem with implementing the hook, I copy pasted the code from some post and it was passing $form variable by value. The correct signature of the alter_form should be

modulename_form_alter(&$form, &$form_state, $form_id)


including new field to views_nivo_slider

The issue here is that the views_nivo_slider only accepts three values: an image, a link and a title, and therefore doesn't have anything inside it to display another field/description.

Now, if instead what you are saying is that the title isn't showing up with the image, then you need to go into Views' Row Style: Views Nivo Slider configuration and tell it what field you want to use for the title.  You do that by clicking on the wheel/gear widget thing to the right of that and then select from the menu.


How to check if page exists using page alias in D7?

If you look at the code for drupal_valid_path() it passes the alias through url_is_external(), which considers paths with a http:// prefix to be external. The function defaults to allow access to these sorts of paths and simply returns that fact; it does not check whether the 'external' url exists.

Since you're adding $GLOBALS['base_url'] to the alias it will appear to be external; you just need to pass the alias into the function without the base URL attached:

if(drupal_valid_path('weird_alias')) {
  // This code is never run
  print_r('Exists!');

}


Basically Drupal does not change that kind of attribute on an image.
But I thinkg you can check this way :
1- Make a very large image with Photoshop ;
2- Save it without making it progressive ;
3- Upoad it on the website and try displaying it.

NB : Very large image because for this test you want to make sure the image will display slowly.

4- save your image again with Photoshop, making it progressive this time. And then :
5- Upload the new one ;
6- Try to display it in a new tab and compare.
Certainly you will see if there is a difference.

That's what I would do....


How can I create a relation between a number of related pages and a main event?

Method 1.

I would create a content type to act as a parent node for each event.

Then for each other content type, add an Entity Reference field, with only that parent content type available. (If you need to restrict the available parent nodes to certain users, you can use a view to get the results of the entity reference field and only allow the node author to select that node).

You can then start adding views to that parent content type for things like "Child nodes" with a reverse relationship to act as an automatically generated menu.

Method 2.

Everything goes into one content type, but use the Field Group menu to create horizontal tabs, and place those fields in those tabs. This will make editing the pages easier as they are all in one place, but depending on the amount of content in each of these mini sites, might have a slow load. There could be a good SEO argument for this method, as your content count would be good for each mini site all on one page.

I would probably choose method 1, unless the "mini site" is small enough to manage with field groups. The benefit of Method 1, is that you can use Rules to automatically add the other pages, and fill in the Entity Reference fields once the initial "parent" node is created.


Trigger custom code on existing Webform Submissions

Just install devel php run your code and then uninstall it.
https://www.drupal.org/project/devel_php  As it is great for quick adhock tasks.

but yep keep back up of your database ect.


How to insert html inside form element div

Assuming you don't need the input wrapper. Just remove it:

$form['pass'] = array(
        '#type'             => 'password',
        '#title_display'    => 'none',
        '#maxlength'        => 128,
        '#size'             => 60,
        '#required'         => TRUE,
        '#theme_wrappers'   => array(), // remove the wrapper
        '#prefix'           => '',
        '#suffix'           => '',
        '#attributes'       => array(
                                'placeholder'   => t('Password')
                            ),
        );

the icon will be placed after the input:

<input type="password" maxlength="128" size="60" name="pass" id="edit-pass" placeholder="Password" class="inputbox form-text required">

But if you need that div wrapper, you can just rearrange his position:

$form['pass'] = array(
        '#type'             => 'password',
        '#title_display'    => 'none',
        '#maxlength'        => 128,
        '#size'             => 60,
        '#required'         => TRUE,
        '#theme_wrappers'   => array(), // remove the wrapper
        '#prefix'           => '
',
        '#suffix'           => '
',
        '#attributes'       => array(
                                'placeholder'   => t('Password')
                            ),
        );

Now the output will be exactly as you wrote:

    <input type="password" maxlength="128" size="60" name="pass" id="edit-pass" placeholder="Password" class="form-text required">


Composer, git and update core and modules

Is it correct that "composer install" does install the versions as defined in composer.lock which gets created after "composer install" is run the first time?

The composer.json file describes which versions can be installed, while the composer.lock module contains the version of the installed libraries.

For example, the composer.json file could contain the following, which would say that is only acceptable to install any version that is greater or equal to 1.0 but lower than 1.1.

"require": {
    "monolog/monolog": "1.0.*"
}

The composer.lock file could contain a "monolog/monolog": "1.0.2" line, since that is the higher version available of the Monolog library that respect the restrictions of the composer.json file.

So, simplifying:

The composer.json file is used from composer install
Both the composer.json and the composer.lock files are used from composer update

  When I start composer install locally earlier as my colleague he/she might get a newer version of Drupal which may lead to different behaviors of our working copies (although it should not with regards to versioning rules - I know).

Yes, that can happen, but it is not a problem, since you just need to run composer update to get the same versions your colleague has. That is, if both of you have the same composer.json file, and neither of you installed other libraries that could cause any conflict.


D6: Create a new template for a specific url of node type page

What you're looking for are template suggestions. If you want to change the page layout (regions, general html) use template suggestions for page.tpl.php. OTOH, if you want to change the node layout (the .node div and whatever is within), use template suggestion for node.tpl.php.


Add query parameter from url to all links on the page

You can do it easily in a custom module, implementing hook_url_outbound_alter().

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  $param = $_GET['q'];
  $path = 'build-path-as-desired.';
}

That should do it for you. The hook serves, basically, to alter outbound urls. You can look at the documentation for it in the system.api.php file, and I suggest you do that, as there are a couple of things to take into account when altering urls through it, but it's definitely an easy way of doing what you want to do.

EDIT: Online documentation for the hook - https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_url_outbound_alter/7

EDIT 2: Additional functions to work with the path being requested:
drupal_get_query_parameters() and drupal_get_path_alias($path).


How to change Contact Form sendto from admin dynamically

The core contact form is pretty limited in functionality. If you need more features, I recommend building your own form using the Webform module.


Limit views exposed filter options to terms with associated nodes of content type X

$query = \Drupal::database()->select('taxonomy_index', 'ti');
  $query->condition('ti.tid', $key);
  $query->join('node', 'n', 'n.nid = ti.nid'); // join node table
  $query->condition('n.type', 'x'); // filter by type
  $query->fields('n', ['nid']); // add filtered nids
  $nodes = $query->execute()->fetchAssoc();


how to show date filter by next 5 months via expose filter in drupal?

What you're wanting is Grouped Filters. It will let you set pre-defined discrete filters for your date.

Under the Views UI for your exposed data filter set Filter type to expose to Grouped Filters. You can set your arbitrary label, set your operator to is between, and Value type to An offset from the current time... in the date fields, you can use a relative PHP strtotime() format to specify a filter between the current date ("now") and 5 months into the future ("+5 month").


Failed attempt at moving Drupal 8 to a clean installation of my OS.

Okay so i went inside of /etc/apache2.conf and changed

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride none
    Require all granted
</Directory>

to

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted
    </Directory>

that worked :)


How to check when a user last updated password

Drupal out of the box does not keep track of password changes.  However, there are modules that do:

Drupal 7: The module Force Password Change keeps track of it. The data is in its schema ($schema['force_password_change_users']), in the field last_password_change (shown below):

'last_password_change' => array (
  'description' => t('A UNIX timestamp referring to the date that the user last changed their password'),
  'type' => 'int',
  'unsigned' => TRUE,
  'length' => 10,
  'default' => NULL,
),

Drupal 6: The module Password Expire keeps track of it. The data is in its schema ($schema['password_expire']), in the field timestamp (shown below):

'timestamp' => array(
  'type' => 'int',
   'not null' => 1,
   'unsigned' => TRUE,
   'default' => 0,
   'disp-width' => '11',
   'description' => 'Date user last updated password',
 ),

You could install one of these modules (depending upon what Drupal version you're using), and just query its table to extract this information as a UNIX timestamp from the field.

It would also be quite trivial to add this by means of a custom module:

You should be able to use hook_form_FORM_ID_alter (where FORM_ID is password_change) to intercept any password changes and record the timestamp for the event along with the uid in a table in the database.


How to prevent recursion when setting a data value for a user in rules?

Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

  some other module code is calling a user_save on hook_user_update triggering the rules event a second time.

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):


How to make a numeric textField in Drupal WebForm?

You can use the Webform validation module to create such validation.


Probably iframe is filtered in #markup. Use an inline_template instead:

  'example one' => [
    '#type' => 'inline_template',
    '#template' => '<iframe src="{{ url }}"></iframe>',
    '#context' => [
      'url' => 'www.google.com',
    ],
  ],


First thing I would check is the .htaccess is indeed working...maybe your getting a cached version of:

http://v6.dev/admin/config/search/clean-urls

What happens when you enter a URI which you know has never existed (and been cached) such as:

http://v6.dev/xxx-237347-3iu33

Does it 404? Does drupal handle it and say "page cannot be found"?

I had a similar issue a few days back...I had to manually disable "clean uri's" in the database...flush all cache tables...re-enable mod_rewrite...log in and enable clean URI's

Let me know how you turn out. :)


Display main menu expanded in footer, drop down in header

We use the menu_block module for this - it lets you create unlimited menu blocks and control menu depth and other options.

This module provides configurable blocks of menu links with advanced features not available in Drupal 8 core.
Drupal 8 core allows you to display blocks of menu links starting with any desired level of a menu and limited to any desired depth.
And this Menu Block module provides additional configuration so you can choose to expand all menu links with children or to root the menu tree to a specific menu item.
The Drupal 7 version of this module provides all of these features since Drupal 7 core does not have any of this functionality.

So I just noticed you're already using menu_block. You can add multiple_menu blocks - you should simply be able to add a new menu_block for the main-menu on your site and use that one in the footer.


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 get site url with twig in Views custom text?

The documentation could be out of date. Check your router table for the name of the route. In my Drupal 8 site it is view.frontpage.page_1.


EntityFieldQuery - ordering by multiplication of two fields

If you don't have to pull in a whole bunch of linked entity stuff, just run a regular db_query() joining your "importance" field table to your node table.

$query = "SELECT nid, (created * field_importance_value) AS weight
FROM node n
JOIN field_data_field_importance f ON f.entity_id = n.nid
WHERE type = 'news'
AND status = 1
ORDER BY weight DESC";
$result = db_query($query);
// Add foreach loop here...

I'm just guessing the importance table name and field name from your OP.


Converting db_query from Drupal 6 to Drupal 7: Invalid parameter number: number of bound variables does not match number of tokens

You've quoted one of the parameters when you shouldn't have.

PDO interprets this:

':source_swe'

as a string, and it (correctly) doesn't try to change it.

What you're looking for is simply

:source_swe

So that parameter replacement can occur. As in,

db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), :source_swe, 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));


Colorbox Node creates a new display mode for each content type - that's where you can change the fields shown.

Structure -> Content Types -> 'manage display' on the content typ ein question - in the top right, select the 'Colorbox' display mode and adjust what shows and doesn't show as needed.


Is it possible to redirect user to another form depending on values entered in the first form

Finally I Manage to redirect user to anther form base on entered values.

Install Rules module and Webform Rules
Create new rule
From React on event select After a submission draft has been submitted
Add a new condition, select Webform has name, Select form_id from Data selector, and select the form name from Weforms value
Add a new condition select Execute custom PHP code
Add the custom code

if ($data['components']['1_are_you_aged_18_to_50_years_of_age_']['value'][0]=='Yes')  {
return TRUE;
} else {
return FALSE;
}

Change the field name 1_are_you_aged_18_to_50_years_of_age_' and Yes value to your own field name and value
 7. Add an action, select Page redirect and add the URL.

Click save, And click save again.
Go to /people/permissions
Allow all the user type to Execute PHP code "Please note allowing users to execute PHP code is not recommended due to security risk".


There appears to be a module for this Module browser but it doesn't seem to be up to date at all unfortunately.


Customize "view modes" and "form modes" based on role

Nothing in core uses form modes - it's an API waiting for contrib to make use of.
This, and the question of when to manipulate form fields and when form modes, is discussed at:
https://www.drupal.org/node/2530086.

There Berdir says "Showing/Hiding fields but keep them otherwise the same is IMHO a perfect use case for hook_entity_field_access() not switching out the form display. I'd only try to do something like [switching form  mode] when you want to show different widgets based on the user roles."

In general, managing display differently for different roles is easy, managing forms differently is more difficult.

Alternatives to the field permissions module for managing display (NOT forms):

The classic answer might be that this is a job for the Panels family, but it's mostly not quite ready for D8.  Page manager is however quite usable and does much of what you want. For specifically created pages, it can control the content based on role. What it won't do is take over the rendering of all nodes of a certain content type.

Display suite is D8 ready, and allows you to show fields based on permissions by using token fields. See https://swsblog.stanford.edu/blog/using-display-suite-provide-field-level-permissions for a description of the procedure in D7, which is only cosmetically changed for D8.


The 'numeric' type classes handle both integers and floats/decimals:

Field handler: views_handler_field_numeric
Filter handler: views_handler_filter_numeric
Argument handler: views_handler_argument_numeric
Validation plugin: views_plugin_argument_validate_numeric

It's not that obvious at face value, but if you look at the comments for views_handler_field_numeric:

Definition terms:

float: If true this field contains a decimal value. If unset this field will be assumed to be integer.

So setting 'float' => TRUE on your field definition, and using the numeric handlers, is all you need to do. e.g
$data['some_table']['msrp'] = array(
  'title' => t('MSRP'),
  'help' => t('MSRP of the product.'),
  'field' => array(
    'handler' => 'views_handler_field_numeric',
    'click sortable' => TRUE,
    'float' => TRUE,
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_numeric',
  ),
  'sort' => array(
    'handler' => 'views_handler_sort',
  ),
);


How to print the value of an array instead of the key?

The form submission process will only actually keep hold of the array key (which is the value for the select element), so it won't be available to you in $params.

The usual method to handle this sort of thing is to provide a function to return the options:

function MYMODULE_colour_options() {
  return array(
    0 => t('Blue'),
    1 => t('Yellow'),
  );
}

Then in your form function you would use:

$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => MYMODULE_colour_options()
);

And in the message hook:

$colour_options = MYMODULE_colour_options();

$colour_string = 'Unknown';
if (isset($colour_options[$params['color']])) {
  $colour_string = $colour_options[$params['color']];
}

$message['subject'] = 'Selected color is: ' . $colour_string;


Node teasers in node object filled with full node body if teaser is not defined

You can check summary text in node obj.

if (empty($node->body['und'][0]['summary'])) {
//do something
}


How can I invoke Drush command inside hook_cron?

You should not call drush from inside a Drupal module.  Instead, factor out the functionality of your Drush commands into separate functions that can be called from module code and drush commandfiles alike.  Your module code should do all user access / permissions checks before calling the API functions (usually via the access checks provided by Drupal's menu system); the Drush commands should call the API functions directly, without access checks.


Display several user blog entries at once

you can create a "view" to display a list of blogs. In Views you can specify how to layout those blogs, how many to show, in what order, etc.
NoneOne has a great screencast about learning views


Conditional field on checkbox is not woking

Please try this code ... It works !!

$form['field_type'] = array(
  '#type'    => 'checkbox',
  '#default_value' => 0,
  '#title'   => t('Choose entry type.')
);

$form['text'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Enter the text'),
  '#states'        => array(
     'visible'      => array(
       ':input[name="field_type"]' => array('checked' => TRUE),
     ),
   ),
);


How to get all the field and value of node as an array?

You can use the built-in Entity::toArray():

$node = \Drupal\node\Entity\Node::load(1);
print_r($node->toArray());


How can I add a field to a content type which will accept a price value in the format of a currency?

UPDATED ANSWER:

using Views field rewrite:

on the field in the view setup, in the "rewrite results" section of the editing modal select the checkbox "Rewrite the output of this field" then scroll down and open the fieldset "REPLACEMENT PATTERNS" and use the pattern there to rewrite your field in the above textarea. as an example to put a "$" in front of the users uid I used $[uid]

CCK field prefix:

You may just want to use a field that is for currency but doesn't actually include the currency symbol, so it can be saved as a number, which allows for better sorting. Then using views you can set a prefix to a displayed field of the desired currency symbol. This may only work with CCK fields.


You can use a CCK "node-reference" field. This way you can "link" one mission page on all person pages. After you did this you can easily make a view that gets all persons that are in the mission node...

Maybe you can take a look at:
http://drupal.org/project/Relation


It turns out all I needed to do was to use hook_field_prepare_view() to add an extra, empty elements to the $items array

/**
 * Implements hook_field_prepare_view().
 */
function threejs_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items)
{
    $items[1]['footer'] = array( );
}


View Module : How to display list of Taxonomy terms with record count

Drupal 7

With View 7.x-3, you first remove the "Content: Title" contextual filter, and then you add the "Content: Has taxonomy term ID" one.

In the dialog for the settings that appear once you select the context filter, you set the options as in the following screenshot. There are two displays: "Page," and "Attachment"; the first screenshot is for "Page."

The result is the following view; the first screenshot show the output when none of the links have been clicked on.

Drupal 6

In Views 6.x-3, the used terminology and the user interface change, but the steps to follow are similar.

Also in this case, there are two displays, which have the same name used in Views 7.x-3; differently from Views 7.x-3, the display to change are the default one, and "Attachment."

You first remove the "Node title" argument, and add the "Taxonomy: Term ID" argument; the first image is for the default display.

In the latter display, the argument will be displayed as list by default; I didn't change it.

Important: There are two similar contextual filters/arguments, where in one appears the word "depth"; the difference is that this last contextual filter/argument shows all the node where the taxonomy term is the select one, or one of its children. You should use this one, if the vocabulary is organized hierarchical, and for example, the taxonomy terms are "Porsche," "Porsche >> Carrera," and "Porsche >> Cayenne"; in this case, selecting "Porsche" will show also the nodes using  "Porsche >> Carrera" and "Porsche >> Cayenne."


How do I remove container div from a specific view?

I was only able to solve this after much hair-pulling regarding Drupal not picking up my suggested template. Where I was hung up was that the template suggestion must start with container__ otherwise Drupal will ignore the file and use the next template in the suggestion list (likely the default container.twig.html).

Here is my code:

/**
* Implements hook_theme_suggestions_user_alter().
*/
function myTheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  // A list of view names in which to exclude the container markup.
  $exclude_views = [
    'someView',
  ];

  if (in_array($variables['element']['#name'], $exclude_views)) {
    $suggestions[] = 'container__no_wrapper';
  }
}

I then added container.html and container__no_wrapper to my theme at templates/container/.


You can override a library using the filename as key.

libraries-override:
  system/base:
    css:
      component:
        css/components/align.module.css: false

But if your asset was already overwritten by another module (e.g. classy theme overriding a core system asset), you have to use the full path instead, example:

libraries-override:
  system/base:
    css:
      component:
        /core/themes/stable/css/system/components/ajax-progress.module.css: false

Also see this issue.


field_view_field returns a renderable array for the field value. So you should use render() function:

<?php
  $node = node_load(52);
  $field = field_view_field('node', $node, 'myfield');
  print render($field);
?>


How to translate a view and keep contextual filters?

I decided to "patch" the code, by adding the paramaters using Javascript.

 if($('.language-link').length > 0 && location.search != ""){
        $('.language-link').each(function(){
            var href = this.href;
            if (href.indexOf('?') != -1) {
                href = href + location.search;
              }
              else {
                href = href + location.search;
              }
              $(this).attr('href', href);
        });
    }


Drupal 7 - Get pages created from custom modules listed under Entity reference field

why don't you serve regular nodes of a new content-type in your hook_menu callback ? so you could easily reference them !

$html = node_view(node_load(948));


How to split Commerce Order: Shipping Address and/or Billing Address into different lines in Views

Thanks to this question, and Stan Ascher's answer, I was able to find the correct tokens to use with Rules. I thought I would share it here:

[commerce-order:commerce-customer-billing:commerce-customer-address:name_line]
[commerce-order:commerce-customer-billing:commerce-customer-address:thoroughfare]
[commerce-order:commerce-customer-billing:commerce-customer-address:locality], [commerce-order:commerce-customer-billing:commerce-customer-address:administrative_area] [commerce-order:commerce-customer-billing:commerce-customer-address:postal_code]


slideshow_view: how to rewrite the output?

Method : 1

  Place the link above the image field in the views.
  Exclude it from display
  Now rewrite the results of the image
  a href="[field_link]" image field
  This will create the link to the image, so when clicking it will lead the page.

Method :2

  Place the link above the image field in the views.
  Exclude it from display
  Select "output this field as link"
  Click the replacement pattern here, and use the link in the text field
  This will create the link to the image, so when clicking it will lead the
  page.


Is it better to create a taxonomy term using the 'create' method of the base Entity class or the entity storage manager?

In procedural code it doesn't matter, because both do the same. The static create() is a shortcut for the second example. (The different result is because the first saves the term and the second does not, if you want the term as result then save in a separate step)

In OOP code a better way is dependency injection. The second example points in the right direction. Inject the entity type manager, store it in a class property and use it:

$term = $this->entityTypeManager->getStorage('taxonomy_term')->create($term);

How to inject a service depends on which class you want to use it in.

A lot of base classes include services already and if you are lucky such a common service like this is one of them. Sometimes, for example in a controller, there is a method to retrieve the service. Then add to the code above parentheses:

$term = $this->entityTypeManager()->getStorage('taxonomy_term')->create($term);

See ControllerBase::entityTypeManager().


How do I use Bootstrap theme's modal.jquery.ui.bridge's mapped events?

The technical reason it's not doing anything is that the value is retrieved as a string and not as a Function object.

You shouldn't pass anonymous functions in data attributes.

This would require whatever implements the callback (jQuery UI/Bootstrap) property to use eval() or some other sort of method to evaluate the callback.

This, of course, has major security implications and why it doesn't work.

All callbacks should be added via JavaScript.

If you don't have control over specific implementation, you can always set a global listening event and then use some sort of unique identifier on the modal to trigger a custom callback.

Example:

(function ($){
  var $document = $(document);

  // Create a custom beforeClose handler.
  var customBeforeCloseHandler = function (e) {
    console.log('closed');

    // Optionally, you should be able to stop it from closing
    // if that is the desired outcome by using the following:
    // e.preventDefault();
  };

  // jQuery UI Dialog Events.
  // @see http://api.jqueryui.com/dialog/#events
  $document.on('dialogbeforeclose', '.ui-dialog', function(e) {
    var $dialog = $(e.target);

    // Check if this dialog is ours.
    if ($dialog.is('.modal-content--special-class')) {
      // Proxy this event to our custom handler.
      customBeforeCloseHandler(e, ui);
    }
  });

  // Bootstrap Modal Events.
  // @see https://getbootstrap.com/docs/3.4/javascript/#modals-events
  $document.on('hide.bs.modal', '.modal', function (e) {
    var $modal = $(e.target);

    // Check if this modal is ours.
    if ($modal.find('.modal-content').is('.modal-content--special-class')) {
      // Proxy this event to our custom handler.
      customBeforeCloseHandler(e);
    }
  });

})(jQuery);

Given that the Drupal Bootstrap base theme has the jQuery UI Dialog bridge, I would recommend binding using jQuery UI Dialog events so it will work even without Bootstrap. That being said, if you can't seem to get that to work... using Bootstrap's events should work just as well.

However, don't use both as that would likely trigger your custom handler for both events.


Print Drupal Statistics in node template?

The statistics module provides that data through statistics_get(), which returns

An associative array containing:

totalcount: Integer for the total number of times the node has been viewed.
daycount: Integer for the total number of times the node has been viewed "today". For the daycount to be reset, cron must be enabled.
timestamp: Integer for the timestamp of when the node was last viewed.

e.g.
$stats = statistics_get($nid);
$total_count = $stats['totalcount'];
$day_count = $stats['daycount'];

To get it into a node template, implement hook_preprocess_node(), hook_node_view_alter(), or hook_node_view() (the latter will need to be in a custom module, the other 2 can go in a theme or module).
hook_preproces_node() example:
function MYTHEME_preprocess_node(&$vars) {
  $stats = statistics_get($vars['node']->nid);
  $vars['stats_total_count'] = $stats['totalcount'];
}

And in the template
<?php echo $stats_total_count; ?>

You'll need to clear Drupal's cache after adding the hook so the theme registry picks it up.


How can I add 'text/jsx' type to a script tag via libraries.yml?

I took a wild guess because I couldn't find absolutely nothing. Apparently this works:

my-libary:
  version: 1.x
  js:
    js/node.js: { attributes: {type: text/babel} }


Drupal 8 add javascript and pass data in a hook with custom module

You can add variables into the scope without generating a Javascript file and then use a hook like preprocess_html to add them in:

$variables['#attached']['drupalSettings']['mymodule']['config']['color'] = $config->get('mymodule.color');

These value(s) are then available in the drupalSettings scope, which you can read out in your module Javascript file in order to do things. Just pass drupalSettings into it.


You can check the element's value in $form_state['values']. Add the full parameter list ($form, &$form_state) to the form builder function.

For example:
function mymodule_something_form($form, &$form_state) {


Need help with rules for shipping in drupal commerce

If you're taking the pure rules route, you'll need a single rule per rate. So if you have two (2) zones and three (3) weight tiers, you'll need six (6) total rules. For example:

Northeast
Rest of the US

And

0-5 lbs
6-10 lbs
11+ lbs

Will be 6 total rules:

Northeast (0-5 lbs)
Northeast (6-10 lbs)
Northeast (11+ lbs)
Rest of the US (0-5 lbs)
Rest of the US (6-10 lbs)
Rest of the US (11+ lbs)

You may also find it worth your time to review Commerce Shipping Postal Code Weight and Commerce Shipping Weight Tariff.


How can I preprocess pager links for a view display?

For the mini pager, the Views module uses its own theme function, theme_views_mini_pager(), which uses the more generic theme functions for the previous, next, and current links. There isn't a template file for that theme function, as the theme function itself is returning the markup.
With hook_preprocess_views_pager(), you could change the values contained in $vars['tags'][1] and $vars['tags'][3], which by default are the '‹‹' and '››', but those are passed to a theme function, which means you are someway limited in what you can do.
$li_previous = theme('pager_previous', array(
  'text' => isset($tags[1]) ? $tags[1] : t('‹‹'),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
));
if (empty($li_previous)) {
  $li_previous = "&nbsp;";
}
$li_next = theme('pager_next', array(
  'text' => isset($tags[3]) ? $tags[3] : t('››'),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
));
if (empty($li_next)) {
  $li_next = "&nbsp;";
}
$items[] = array(
  'class' => array(
    'pager-previous',
  ),
  'data' => $li_previous,
);
$items[] = array(
  'class' => array(
    'pager-current',
  ),
  'data' => t('@current of @max', array(
    '@current' => $pager_current,
    '@max' => $pager_max,
  )),
);
$items[] = array(
  'class' => array(
    'pager-next',
  ),
  'data' => $li_next,
);

You can implement hook_theme_registry_alter() to replace that theme function with your own. In this case, you have complete control over the output; you could even tell Drupal to use a template file.
Keep in mind that theme_views_mini_pager() is used for mini pager of every view. For what I can see, there isn't any value passed in $vars that makes understand for which view the mini pager is output.
Given the lack of documentation on the values passed in $vars, I would check what is passed in $vars. It may be that one of those values is the view ID, or machine name.
The values documented in the theme functions for the previous, next, and current links are the following.

element: An optional integer to distinguish between multiple pagers on one page
interval: The number of pages to move backward when the link is clicked
parameters: An associative array of query string parameters to append to the pager links


Bootstrap CDN over-rides my custom CSS files

Your custom css needs to be more targeted to override the default boostrap css. On line 38 replace ".navbar-nav" with the following:

.navbar-default .navbar-nav>li>a


Set URL Fragment based on which Vertical Tab clicked?

You could use JavaScript to change the URL fragment each time a tab is opened (click listener on the tab changes the fragment to that tab's ID). But that would only allow the user to go back and have whatever the last tab they opened before following a link remain open.

If you want to save the state of many opened/closed vertical tabs I can't think of a solution that doesn't involve reading/writing constantly to a DB. Maybe you could get away with using cookies instead? Either way its gonna be messy.


Programmatically create a Custom Content type on saving a form

A content type is a config entity, you can create one like any other config entity (*):

$content_type = \Drupal\node\Entity\NodeType::create([
  'type' => $machine_name,
  'label' => $label,
]);
$content_type->save();


How to display current pages the media entity is referenced during deletion?

Additionally to the comment, here's the snippet we used based on the entity_usage module in a hook_form_alter():

  $object = $form_state->getFormObject();
  if ($object instanceof ContentEntityDeleteForm) {
    $entity = $object->getEntity();
    $usage_data = \Drupal::service('entity_usage.usage')->listSources($entity);

    if (!empty($usage_data)) {
      $count = 0;

      foreach ($usage_data as $usage) {
        $count += count($usage);
      }

      $form['usage_warning_message'] = [
        '#type' => 'container',
        '#markup' => t('This content is used in @count places.', [
          '@usage_url' => Url::fromRoute('entity_usage.usage_list', [
            'entity_type' => $entity->getEntityTypeId(),
            'entity_id' => $entity->id(),
          ])->toString(),
          '@count' => $count,
        ]),
        '#attributes' => [
          'class' => ['messages', 'messages--warning'],
        ],
        '#weight' => -100,
      ];
    }
  }


The correct way to set a page using Panels (I'm assuming Panels 3) in Drupal would be to go to the Panels interface and click "Add custom page". You can give that page any path you want such as /home - the path doesn't actually matter. Then, from the admin options: Administer -> Site Configuration -> Site information you can change your default front page. Input the path that you used when creating your new panel.

This will give you a new custom panels page that will show up as the default front page at www.yoursite.com

This video will walk you through the process step by step.


When a module has a composer dependency, should it be automatically installed when the module is installed?

If you install the module with composer, yes, dependencies will be fetched. If you download the tar and put it in the site, it will not.


Make almost duplicate copy of node when submitting

Drupal core doesn't provide hook after a node has been saved, but you can use hook_node_presave() like

<?php
function mymodule_node_presave() {
  $var = $node->original->field_my_field['und'][0]['value'];
  // field_my_field could be the checkbox value, if both rooms should be booked
  if ($var == true) { make_a_copy_but_change_a_value(); }
}
?>

Using this hook, you can look for your extra checkbox value (if the second room should be booked, too) and create a copy of the node object. But beware, at this point (hook_node_presave) the original node is not yet fully written to the database. However, the cool thing is that it fires both on node save and node update, so if you need to do something both on the creation and the updating of a node (e.g. if a booking of both rooms changes).

To actually use a hook after node insertion, you may want to try the Hook Post Action module as it provides special hooks. Drupal core does not provide such hooks, hook_node_insert and hook_node_update are both fired after the sql query for insertion is scheduled for execution but due to the transactional system the data is not yet in the database.


Disable Drush backend messages by default

Uninstall cleanly that version of drush as 5.0 is very old now. Uninstall using pear if you installed that way, using Composer, or manually checking which drush and remove symlinks, drush folder, backup and then remove ~/.drush.

Look at the Drush install page to see what drush version you need for Drupal version you are working with. Then install drush using Composer which is the recommended way.

This message should be gone then. Good luck!


EntityFieldQuery select entity if at least one tid is in the array?

All you need is:

$query->fieldCondition('field_tags', 'tid', $tid_array);

From EntityFieldQuery::addFieldCondition():
"The operator can be omitted, and will default to 'IN' if the value is an array, or to '=' otherwise."


You can manually DELETE FROM the cache tables, though doing this with cache_form can result in wonky behavior with people in the middle of form submissions.

However, I suspect the problem isn't with clearing the cache, rather with all of the activity involved in rebuilding everything that gets cached.

Long term, you would be safest to

Disable modules you don't need
Bump up memory_limit for PHP

64M is likely on the low end if you have a lot of modules enabled.  You should really download  the Performance module, enable Summary Logging, run your site for a while, and see where you land on memory stats.  Also note where these go when you clear caches and perform other admin functions.


In general, you don't access templates directly as an API, you build render arrays. To get the render array of a field, each field item and item list class has a view method. That method accepts either the name of a view mode and uses that configuration or you can also directly pass in the configuration you want to use (Basically the array that you have in view display config entities for each component).

You can try calling that from twig directly, e.g. {{ item.view('teaser') }} or prepare it in preprocess of your template.


If I understand you correctly, you'd like to get a hold of the data before it gets inserted in the database so you can do something else with it?

If this is the case, hook_webform_submission_presave is your friend.
The $submission object will hold the submission data. This lets you change it before it's inserted in the database or, as in your case, just do something else with it.

Here's a list of all the webform hooks for D7 (with a link to D6 hooks as well if that's what you're using).


Access to $content['links'] from page.tpl.php in D7

Well it looks like it can be pulled off with (in the page.tpl.php files):

$links = node_view($node);
print render($links['links']);

Anyone know if there is a better approach?


Image field in content type not displaying the image

You need to convert that public://myname.jpg to an actual URI to pass to an img tag

Try image_style_url

Replace your code with this

    <?php
    $nid=11;
    $node = node_load($nid);
    $imgcount = count($node->field_img['und']);
    for ($i = 0; $i < $imgcount; $i++) {
//$image_uri = $node->field_img['und'][$i]['uri'];
      $yourimagestylename = 'MY_IMG_STYLE';
      $image_uri = image_style_url($yourimagestylename,$node->field_img['und'][$i]['uri']);
// url
      $masthead_raw = image_style_url('gallery-thumb', $image_uri);
      ?>
      <img src="<?php print $masthead_raw; ?>">

      <?php } ?>


How to prevent dynamic library definition from being cached?

You could trigger Drupal::service('library.discovery')->clearCachedDefinitions() every time, but that seems like a painful workaround performance-wise. All library definitions for a particular theme seem to be stored in a single cache entry library_info:$activeTheme, which doesn't allow any more finely grained invalidation.

Would the range of values of "callback" allow you to loop through them and define a separate library for each one you use, and then attach the specific one you need? The JS gets loaded on demand, so only the attached library would appear on each page.

foreach (static::CALLBACKS as $name) {
  $libraries['sample.my-lib.' . $name] = [
    //...
  ];
}

Or maybe it would be possible to call the appropriate callback from a single main function (possibly setting the callback via a drupalSettings attachment), allowing you to put a fixed value in the Google Maps API URL?


Resolve CORS issue without changing services.yml file

Can I achieve w/o enabling cors config?

No. Without CORS configured, the server and browser will correctly conspire to reject the request.

You could implement it yourself, rather than using services.yml, but something needs to set the headers. And at the point where all you need to do is make a few simple edits to a configuration file, I'd question why you would want to write all that extra code yourself.


How to get the standard text format widget for a custom field type?

You are looking for '#type' => 'text_format'. Usage example:

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

You will get the text in $form_state['values']['text']['value'] and the format in $form_state['values']['text']['format'].


It turns out, this can be done with a combination of hook_preprocess_html  and function views_get_page_view to get a true <body> class for a given view and display (see the API page).

So wrapping it up within the hook_preprocess_html context, it would look something like this:

/**
 * Implements template_preprocess_html().
 *
 * Misc page preprocess functions.
 */
function mytheme_preprocess_html(&$vars) {

// Query the view and add a class
$view = views_get_page_view();
 if (
  isset($view) &&
  $view->name == 'actions' &&
  $view->current_display == "page"
) {
    $vars['classes_array'][] = 'views-actions-page';
  }
}

So above, I query the view name and display and the key is $view = views_get_page_view();. This works great for custom Views body classes per view and display.

The rendered HTML result is something like this:

<body class="html not-front logged-in no-sidebars
page-actions section-actions page-views flush-header views-actions-page">

** views-actions-page is the class that we added with the function above.

It should be noted that the advantage of this vs. using views generated classes are that if the URL of the page changes, your custom Views class will not whereas page-actions section-actions would change based on the URL. So using those classes could be unreliable if they are used for theming as it would have a negative ripple effect.


How to redirect a user to a visited sub-domain on his next visit to main domain

This implementation of hook_init() should be present on your subdomains but not on your main domain:

function YOUR_MODULE_NAME_init() {
  if(!isset($_COOKIE['your_cookie_name'])) {
    /*Your need to set cookie for your main domain, as well as for all your subdomains otherwise once a user visits another subdomain by typing the url directly in the address bar the cookie would be overwritten*/
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site1.example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site2.example.com');
    ...
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site5.example.com');
  }
  else {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

Your main domain should have a module with the following code:

function YOUR_MODULE_NAME_init() {
  if(isset($_COOKIE['your_cookie_name'])) {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

I didn't test this code, but I am positive it should work, or at the very least it illustrates the approach.


Create a drop down list of notifications with an unread item count that resets or hides on click

Your question consist of (at least) 3 questions. You should really split them in separate ones. Read on for an answer to your bullet "3." ...

Have a look at my answer to "How to allow users to manage their own Message Stack messages?", which IMO is pretty close to the question here. It can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user'.
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module).

Bonus: by using the suggestion as in item "5.", you probably also solved your bullet "2." (combined with "A.")

Note: no custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).


#ajax elements added in hook_form_alter miss after first ajax call

The problem was relying on the IDs created by drupal_html_id() to match after ajax rebuild of the form. I fixed it by having jQuery find the dummy select elements by 'name' attribute.

  $.fn.oldAddOption = $.fn.addOption;
  $.fn.addOption = function(arguments) {
    this.oldAddOption(arguments);

    // find the tag that holds the id of the ajax multiselect element
    var tag_with_name = $(this).parent().parent().find('.multiselect-element-name-holder');
    // find the id of the ajax multiselect element
    var ajax_element_name = tag_with_name.data('ajax-multiselect-element-name');

    $('select[name="'+ajax_element_name+'"]').trigger('change');
  }

This code now sets unique element names instead of trying to set unique ids:

$ajax_element_name = drupal_html_id('ajax-multiselect-element');

// tell jquery where to find the id of the dummy select
$element['#attributes']['class'][] = 'multiselect-element-name-holder';
// transmit the id of the dummy select to jquery
$element['#attributes']['data-ajax-multiselect-element-name'] = $ajax_element_name;

$form[$ajax_element_name] = array(
  '#type' => 'select',
  '#ajax' => $element['#ajax'],
  '#options' => array(0,1),
);


Node access-control modules for members-only pages

Obviously there are a lot of factors that you should consider before deciding whether a module has a "bright" future or not. A very good blog post that describes all the factors that should be considered can be found here (it's based on the old theme of drupal.org but you can still get the point).

The final decision that you'll take is kind of a "feeling" that you'll get after you 've spent a lot of hours testing modules and banging your head against the wall, only to realize that the module that you picked is not the correct one. However, I will give you the results of a small script that I have and I run in such cases. It gives you the usage count of the modules that you provide as an input, and here they are:

content_access: 24939 users
node_access: 1295 users
simple_access: 1623 users
node_privacy_byrole: 3399 users
taxonomy_access: 6037 users
tac_lite: 3397 users

Note that these results are just information pulled from the drupal.org website and you should not use them to compare the modules. They are just indications that tell you how other users "feel" about those modules that you are examining.

So, to answer your question, I would go for content access module since it supports the per-role access that you mentioned, there are tons of sites that are using it (meaning that it is highly unlikely to be discontinued), its author is someone that has done remarkable work for drupal and the D7 version was updated -relatively- recently.

P.S: if you want the script, lemme know. It's proven very handy in many cases.


Here is some possible ways to do it:

1. using no extra modules

Click ADD next to header or footer area and look for GLOBAL: Rendered entity - Block.  The configuration asks for view mode and block id

2.  using  Views block area module

You can use Views block area module that will allow you to insert a block as a field or in header or footer area.

3.  using preprocess / twig

if you want to add the block using your twig template in your THEMENAME.theme file using a preprocess function

function THEMENAME_preprocess_XXX (&$variables) {
    $block = \Drupal\block\Entity\Block::load('id_block');
    $variables['myBlock'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
}

and then inside your twig file use this

{{ myBlock }}

To find appropriate preprocess function look in your twig file comments.

For example if you want to use views-view--unformatted.html.twig you can see in the comments

* @see template_preprocess_views_view_unformatted()

which means include in your .theme file THEMENAME_preprocess_views_view_unformatted() function


You can actually just leave the base URL and Secure URL blank to not have it redirect to an inappropriate subdomain than you're on currently.

To restate my problem, I had multiple subdomains sharing one database where the Secure Pages module was implemented. If I put down a base and secure URL using one subdomain, I would get redirected to that instance from other subdomains not listed there when https was needed for that subdomain.

This is an undocumented solution as far as I'm aware, so I hope it helps someone else out.


Advice: change the name of the author by his role in a comment

Module VS preprocess function - modules can use preprocess functions as well. I guess that the question in your case is whether or not to do the changes in a custom module or theme. It's up to you, but generally speaking, keep the specific UI improvements in the theme and let the module do the hard work you will need in any case (if you change the theme for example). Also, it's better to pack the things you might need somewhere else in a module as it's easier to drop it to another site.
You can load the user object with user_load($uid);. This will also load all roles with role IDs and names. I suggest installing Devel and calling dpm($user); to have a better understanding of what you get in the user object.
If by request you mean database request - yes, it's alright, if there's not a way to do so already. As I mentioned in 2. you can use user_load function - this will reduce the code and also load the user object from cache. I think that Drupal already called user_load for rendering the comments, so calling it again will just get everything from cache and won't impact performance.

Hope this helps.


custom module page -- i need it to use a predefined panels page layout

I made a custom block and put that into a standard layout instead.


How can I use Rules to publish nodes depending on changing the value in a Field?

Set the rule to fire on the event Before saving content so you will have both values of the field available.

Set the conditions as follows:

Node is of type and select your content type.
AND Entity is new. Your data selector should be Node and negate the condition (NOT new)
AND Entity has field, Again your data selector should be Node and select your field_dyzury from the drop-down list to make the field available to the rule.
AND Data comparision and using data selectors for both values choose [node-unchanged:field-dyzury] and [node:field-dyzury]. Select the Equals operator and negate the condition (NOT equal)

It is important to detect that the node is not new, or there will be no existing data value for the comparison.

Then set the Action to Promote content to front page. Again, data selector should be Node.

This rule will detect any change in field_dyzury, and will promote the content to the front page when a change is detected.

Edit:

The conditions should look like:

+ Content is of Type
+ AND
    + NOT Entity is new
+ AND
    + Entity has field
+ AND
    + NOT Data comparison

The AND's force the rule to require ALL of the conditions to evaluate to true before the actions are performed.


Correct way to add custom column to user table?

It seems that I was missing hook_schema_alter(). This fixed my issues with drupal_write_record() and views.  Thank you @Clive for your comment here.

Overview of what you need to do:

In hook_install() you need to call db_add_field() to add a field.
In hook_schema_alter() you modify the schema so that other modules can
interact with your changes.
In hook_uninstall() you need to call db_drop_field() to clean up/remove your added field.

Actual Code:

Here is how I accomplished this.  The code below belongs in your module.install file.

function hook_install() {
  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
  $index = array(
      'indexes' => array(
          'updated' => array('updated')
      ),
  );
  db_add_field('users', 'updated', $field, $index);
}
function hook_schema_alter(&$schema) {
  $schema['users']['fields']['updated'] = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
}

function hook_uninstall() {
  db_drop_field('users', 'updated');
}


Entity Registration module: Enable registration by default or programmatically

/**
* Implements hook_entity_insert().
*/
function registration_entity_insert($entity, $entity_type) {
  $registration_type = registration_get_entity_registration_type($entity_type, $entity);
  if ($registration_type !== FALSE) {
list($entity_id) = entity_extract_ids($entity_type, $entity);

$settings2 = array(
  'multiple_registrations' => 0,
  'from address' => variable_get('site_mail', ini_get('sendmail_from')),
);

$settings = array(
  'status' => 1,
  'capacity' => 0,
  'send_reminder' => 0,
  'settings' => serialize($settings2),
);

registration_update_entity_settings($entity_type, $entity_id, $settings);
//registration_entity_set_default_settings($entity_type, $entity);
 }
}

References:

http://drupal.org/node/1430870

http://drupal.org/node/1357280


DB Query exclude duplicates, returning only the newest

You can use range() to limit your results

$query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->orderBy('date', 'DESC')->range(0,1);
$query = $query->execute();
return $query;


How to hide the filename in drupal 7 files and add link to icon?

Ran across your question looking for the same answer... This is what I found. I'm at best a novice with Drupal, so I need easy solutions.

There is this module: https://www.drupal.org/project/file_field_icons

There are also some more options/notes here using CSS: How to change File field icons (without changing core)?


Hide Content Type Default Pages from Search Results

You can use Custom Search module.

  This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box, this module is for you. D8.x notes

  The module adds options to select:

which content type(s) to search,
which specific module search to use (node, help, user or any module that implements search),
which input type to use (with Elements),
advanced criteria

  For all these choices, there are options to switch between a select
  box, checkboxes or radio buttons, and also customize the selector
  label and the default - Any - text. Advanced options

  There are also options to:

change the default search box label,
add a default text in the search box,
add advanced search criteria,
change the default submit button text,
use an image instead of the submit button,
change the order of all the elements,
include some elements in a popup block,
add a filter to the results page,
show/hide basic and/or advanced search in the results page,
show/hide meta data in the results page,
multiple search paths


I've seen modules use attach load as well, which is what you need to get it on the actual entity.

It also depends on your data structure if the base entity has a reference to the additional data entity, you could simply use the entity wrapper along with entity properties. You wouldn't actually have the data on the entity, but have it accessible via the wrapper. The advantage is that you only run extra queries (loading the entity) as required.

In code you would then do

 $entity = load_entity_function($foo);
 $enity_wrapper = entity_metadata_wrapper('entity_type', $entity);
 $additional = $enity_wrapper->addition->value();
 $additional_id = $enity_wrapper->addition->id->value();

In order to have the wrapper do this, you tell it about the additional entity in a hook:

/**
 * Implements hook_entity_property_info().
 */
function module_entity_property_info() {
  $info = array();

  $properties = array();
  $properties['additional'] = array(
    'label' => t('Label'),
    'type' => 'entity_type',
    'description' => t('description.'),
    'getter callback' => 'function_get_entity_id',
    'setter callback' => 'function_set_entity_id',
    'clear' => array('id_of_additional'),
    'schema field' => 'schema_of_additional',
  );

  $info['base_entity']['properties'] = $properties;

  return $info;
}

You need a function that will get or set the id from the entity. Depending on your naming convention entity modules come with some that you can use.


Yes. The thing is, I need different content in this block depending on
  the current view. So I'd need to create 20+ different blocks for each
  of my views which seems redundant. I'm sure there must be more elegant
  solution.

Create a block and use template_preprocess_block to alter the content based on the path. In your theme's template.php add:

mytheme_preprocess_block(&$vars) {
  if ($vars['block']->bid === 'target_block_id') {
    $path = current_path(); // gets the current page path.

    switch($path) {
      case path1:
         $vars['content'] = "Hello World";
         break;
      case path2:
         $vars['content'] = "Hello Kitty";
         break;
       // ... and so on and so forth.
    }

  }
}

Note: replace mytheme with your actual theme name, same for 'target_block_id'.

Another possible option, would be to add a header to your views, and then just use CSS with absolute position to move it, this would mean you'll need to add some padding-top: or padding-bottom on some other div to create a space for it.


There are a couple of layers here...

Any code that calls user_save can technically affect what ID is assigned. If the account object has a uid property, that is used, otherwise it comes from the database:

// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($account->uid)) {
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

So if an ID is provided, great, if not (which is the norm), it gets more complicated.

The users table doesn't have an auto-increment column (probably because an ID of 0 is used for the anonymous user, and there's no way to support that across all DB platforms). If you were to just get the last inserted user ID + 1, you're open to race conditions when other requests get the same ID returned before the first script has had a chance to insert the record into users.

Because of that, the Sequence API is used. The sequences table has a single, auto-incremented primary key column. When a new, unique, identifier is required, a record is inserted into that table, and the auto-assigned ID is returned to Drupal. That ensures it's not susceptible to race conditions, as the operation has already completed and any other requests would be guaranteed a new ID.

If you just need to hack around the problem you mentioned, and you're not worried about or prepared to take the risk of race conditions, add this to a custom module:

function MYMODULE_user_presave(&$edit, $account, $category) {
  if (!empty($account->is_new)) {
    $account->uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField() + 1;
  }
}


Using modules "not covered by Drupal’s security advisory policy"

According to the Security advisory process and permissions policy, modules that have an alpha, beta, or rc (relase candidate) status are not covered by this policy, and security advisories will not be reported for these projects. At the time of writing, Conditional Fields has recommended releases for Drupal 7 and 8 that are both in "alpha" stage. Even without security advisories, you can still choose to be notified when the module is updated.

Since module releases and their status are arbitrarily assigned by project maintainers, only you can judge whether you should use a module marked as not being covered by Drupal’s security advisory policy. One maintainer's "alpha" module, would be a "1.0" version to another maintainer.

You should examine the maintainer's credibility, history on Drupal.org, the project's popularity, and the speed at which issues are resolved or responded to. Many popular and public sites do make use of "beta" or other modules.

Coding your own module to duplicate the functionality of a module that already exists seems more likely to introduce security vulnerabilities that can potentially only be diagnosed or fixed by one person: you. Using an "alpha" module with a competent maintainer and an active community of users seems far more advisable.


For those of you interested: the bottleneck is in the taxonomy_term_save() function.

Following the trail, it led me to the field_sql_storage module (in core) which deletes an existing row and then inserts it. It should really use the built in DB Driver functionality and UPSERT instead of deleting and then inserting.

Working issues (for D8 only):

https://www.drupal.org/node/1800286#comment-9356897
https://www.drupal.org/node/2239071

As of writing this, no patches have been applied yet. Updating large sets of taxonomy terms will lock up your DB.


Is it safe to delete all revisions of a deleted node?

I hope you are doing your tests on a test server. In that case, yes, they are safe to be emptied, even if it would be better to let Drupal and any third-party module to remove any entity data they have in their tables.

Rather than worrying to empty tables, I would find a quicker way to create a test server that is then destroyed when the test is done.


View, Nodes categorized by field with counter just right to Category name

Amend your view as follows:

Add the category term as a field to the view, either straight as a field from the node, or as a relationship. Make sure to exclude this category field from display.

Choose your format for the view, and for the format settings, select the hidden category field you just added as 'Grouping Field Nr. 1'.

Your view should now categorise the content with the category as the headings for each group.

Now to add the count.

In the Advanced part of the view, click on Theme: Information.

This open this window:

Now copy the name of a view override from the row 'Style Output' (underlined in red in screenshot'. The names to the left are to override the view in a very general way, and more the right it will target the view more specifically. Make it specific so that only this view is targeted.

Create a new file in your theme's templates folder with the name you just copied.

Paste this code in your file (it comes from clicking on the blue 'Style output' link in the view's theme information window, with a slight adaption).

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title . ' (' . count($rows) . ' ' . format_plural(count($rows), 'document', 'documents') . ')'; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

The last thing to do is to clear your cache.


How can I render an URL path from a custom route?

Twig

You can use the route name in the twig function url():

{{ 'View my module content'|t }}

Controller

Or you can do the same in a controller:

use Drupal\Core\Url;

  $url = Url::fromRoute('module_new', [], ['absolute' => TRUE]);

  // get the path as string (not recommended)
  $path = $url->toString;

  // better put the complete url object in a render array and let the template render it
  $build['link'] = [
   '#title' => $this->t('My module content'),
   '#type' => 'link',
   '#url' => $url,
  ];

  return $build;


CCK to Fields: content_migrate says missing widgets (image, matrix), but modules enabled

I can ignore the warning, it does not influence display or upload of images.


Set a cookie whenever front page is viewed

You could do this in hook_preprocess_page() and instead of setting a variable, you could do something like this:

function pref_preprocess_page(&$vars) {
  global $user;

  // whatever other preprocess stuff you want to do here

  if ($user->uid && drupal_is_front_page()) {
    $auth  = md5(join('_', array($user->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
  }

}


In your screen shot, there is HEADER and FOOTER section. Click add in one of them and add a Global: Text Area, and put your HTML there, for text filter use FULL HTML.


Limit number of event registrations per month

Action to halt registration

Use "Page redirect", with a value for "URL" that could be either one of these:

some special node that you want to display to inform the user that the maximum number of events was reached.
the same URL that the user uses to add the event, combined with "Show a message on the site" whereas the message content provides appropriate information to the user that the maximum number of events was reached.

If that doesn't help/work, then you may want to try a variation of my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle? (that question was about "Node is 'going' to be viewed, while yours is about something like "entity is 'going' to be created").

Reset registration counter

Similar to the "Registration Count" field that you added, add another field like "Count start date". And each time a user tries to create a new event, just use that "Count start date" to compare it with the "current date": if then the time span between those 2 dates is longer then that "certain interval", then reset the "Registration Count" to zero.


node_view not picking up view mode, always printing full

I think you have a misplace parenthesis.  You have

$form[...] = drupal_render(node_view($eventInfo['event']), 'teaser');

The view mode should be a parameter to node_view() and not drupal_render():

$form[...] = drupal_render(node_view($eventInfo['event'], 'teaser'));

As a side note, I don't think you need to explicity render the node and stuff it into a #markup.  node_view() returns a render array with a #theme already defined, so you should be able to do:

$form['commerce_fieldgroup_pane__group_event_information']['field_event_information'][LANGUAGE_NONE][0] = node_view($eventInfo['event'], 'teaser');


There was extra space before the <?php in index.php. Not sure how I missed it with all my searching before.


What is a "fluid" column in Display Suite?

In Display Suite, the "fluid" refers to the templates ability to expand the column width if one (or more) columns are empty.

For a 2 column layout, the CSS is:

.ds-2col > .group-left {
  float: left; /* LTR */
  width: 50%;
}

.ds-2col > .group-right {
  float: left; /* LTR */
  width: 50%;
}

So even if there is no content in .group-right, the .group-left element will still take up only 50% of the available width.

For the fluid 2col layout, the CSS is:

.ds-2col-fluid > .group-left {
  float: left; /* LTR */
  width: 50%;
}

.ds-2col-fluid > .group-right {
  float: right; /* LTR */
  width: 50%;
}

.ds-2col-fluid.group-one-column > .group-left,
.ds-2col-fluid.group-one-column > .group-right {
  width: 100%;
  float: none;
}

The last ruleset (the one with '.group-one-column') means that if either of the columns contains no content then the other column will expand to 100% of the available width. You can see the little piece of PHP logic that adds the extra CSS class to the template here: http://drupalcode.org/project/ds.git/blob/refs/heads/7.x-2.x:/layouts/ds_2col_fluid/ds-2col-fluid.tpl.php

For your case, either is fine, but to get the 25% / 75% split, you'll need to override the DS CSS code in your own theme's stylesheet.

You could use something like

body .ds-2col .group-left {
    width: 25%;
}
body .ds-2col .group-right {
    width: 75%;
}


Custom html.tpl.php file is not getting picked up

You have to add a theme hook suggestion (example from here):

function THEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
}

Use this in code in your template.php file in the theme directory and, obviously, change it :)


Drupal by default comes with robots.txt file. You can find the file in Drupal Root.

Yes, you can go ahead and change. Below code also should work.

Disallow: /fr/

But, if you use

Disallow: /fr/*

As per wikipedia

  Universal * match The Robot Exclusion Standard does not mention
  anything about the * character in the Disallow: statement. Some
  crawlers like Googlebot and Slurp recognize strings containing *,
  while MSNbot and Teoma interpret it in different ways.


How to enable comments on drupal default user profile page?

To stay in Drupal language: The problem is that User account pages are not "nodes" (no normal content type like you may expect) nor full "entities" (bundles of fields grouped as type in Drupal 7 world). This missing is a big left over from earlier days of Drupal and not really wanted as-is in the Drupal community since it is against the field-able framework idea behind Drupal. Plus that comments are sadly sticky to nodes (not usable elsewhere).

There are many efforts to change this and (from what I know) solved in D8. And the user accounts are fieldable now in D7 already, but still not really "known" everywhere in the system and that's why the system provided "comments" bundle can't be activated here. User pages are not nodes. The concept of "Entities" is another one of the efforts to have fieldable bundles everywhere, one of these steps away from the inconsistency and to get a more general reusable logic of field-able "groups of elements" everywhere, not only on nodes or user pages. Comments are already entities but not known by user pages. And so on and so forth.

Some work arounds for Drupal 7 could be now to use modules like profile2 (a little bit limited, but fully field-able entity), or "Reply" (will be awesome, but new and needs some more help!), or to build own "entities" or content types (my suggestion) which can be made relative to users (like blog already is) using modules like entityreference or relation (awesome but for this usecase allone maybe too powerful). This gives you more than comments as an option, plus the complete freedom about how to field your custom "user pages". And you can even show them apart from the user account page, like on facebook profiles or in tabs. (advanced views and menus knowledge needed here)

Another way could be to use the manage fields settings dialog of Drupal core and "bow" them as fields with multiple values to a kind-of-comment behaviour. I already did this very successful on project, where the clime was limited and to choose this way was less effort to achieve. But for more complex needs I would rather suggest my earlier solutions.

Aaand ... an outsourcing comment solution would be: the Disqus module. Surprise: it also works on profiles. (sorry, but I am limited to less than 3 links ATM, it's a new DA account.)

But as you can see: as always in Drupal, there are more than 2-3 ways to achieve a wanted behavior in Drupal projects.

Hope it helps a 'lil bit. Best regards...


By default in Drupal if you have node/7 with an alias of some/readable/path then a user can go to either of those URLs and it will load the page.

For SEO reasons it is considered bad to have the same page viewable at multiple URLs.

For this reason a very large number of drupal sites use the redirect module.

The redirect module forces users to always access a node from the same URL so if a user navigates to node/7 it will redirect them to the aliased URL instead.

It is likely the difference between the sites you are looking at is the redirect module.


Is there any way to force blocks created by views to display even when there is no result?

Views has a somewhat hidden feature for setting the behavior when you have no results.

If you edit the view and click on Advanced, you will see some new settings:

Click on add next to NO RESULTS BEHAVIOR.  You will then get a modal with a ton of choices.  You should be able to use the textarea or markup options to plop in a &nbsp;  This should force the block to not be "empty".  You could also set a message, etc.

You can also always show the advanced options if you visit admin/structure/views/settings

I typically always set "Always show the master display" and "Always show advanced display settings".  There are some other useful settings on admin/structure/views/settings/advanced


How can I within Drupal 7 make updates to an external MS SQL Server database?

Use the Drupal database API to manipulate the data in the other database. You can use db_set_active() to switch to the other database.


How to comment on image in colorbox (modal form)?

Inline Ajax Comments should do the trick for you.

  Inline Ajax Comments is a views handler that allows you to add a field
  to a view to allow users to view and post comments on nodes in a view.
  This is a basic version of what you see with commenting in social
  networking sites like Facebook.

Ajax Comments comments can also be considered.


Node types are (config) entities, so they have the same methods available as others. Specifically, relevant for you, all entities have id() and label() methods:

use Drupal\node\Entity\NodeType;

$options = array();
foreach (NodeType::loadMultiple() as $type) {
  $options[$type->id()] = $type->label();
}

Those methods are defined on \Drupal\Core\Entity\EntityInterface, you can use them anything that's an entity and that includes almost every type of content and configurable thing, nodes, users, roles, views, image styles, ...


I don't know the relative merits of Node locations vs Location CCK for this scenario, but the CCK option's worked for me. Edit: With GMap enabled, you can select a Google Map as the field's formatter by going to Content management -> Content types -> Edit [content type] -> Display fields. If GMap's enabled, you should see an option Map only. CCK will handle storing the data. See my comment on this Q for how to get the table details. Edit2: Actually, if memory serves, Location doesn't store the CCK data as you might first expect. location.module stores locations in its own table, and the CCK field just stores an ID into that table.


When you want to create relationships between various Content Types, the first solution many go to is Entity reference.

  Provides a field type that can reference arbitrary entities:

It creates a new field type available on all entities that can reference entities of other types. You can specify, with granularity, what types of bundles to reference (in this case you'd want to select the bundle 'Node').

Once you've created this field, you can now reference the Household directly through the node edit form. From that point forward, in Views, you can create a Relationship to the Content being referenced through the entity reference field (search entity after Adding a new relationship to find this), and then you can render any type of attached Content you wish (the Title as a link to the Node, via field settings; the entire rendered Node, etc.) through either Fields (in Views) or using Display Suite.


In my VS Code launch config I had to change the pathMappings from this:
"c:\\xampp\\htdocs": "${workspaceFolder}"

into that:
"c:\\xampp\\htdocs\\sites\\all": "${workspaceFolder}"


How to add "#main-content" to the link of pager element?

You can use template_preprocess_pager to alter the pager links. You should be able to do something like the following for whatever links within the pager you want to change:

function MYTHEME_preprocess_pager(&$variables) {
  if (some check to make sure its the pager you want){
    $cur = $variables['items']['next']['href'];
    $variables['items']['next']['href'] =  $cur . '#main-content';
  }
}


Unable to upload large files (>50mb) to Amazon S3 from D7 on EC2

As pointed out in the comments, this ended up being a PHP config issue.

While I had set the post_max_size and memory_limit arguments to 1GB, the upload_max_filesize was not set at all. Setting this to 1GB in the php.ini file as well resolved the problem.


How can I load content on the same page from a search

you to load the search results on the same page - the same page as what? do you mean without a page refresh? If that's the case, then I think you're looking for Search API Ajax:

This module can ajaxify Seach API pages and views. Ajax made possible by
Drupal 7 core's jQuery BBQ (previous YUI3 History library is dropped).

and perhaps Ajax Facets:

This module allows you to create facet filters which working by AJAX.
Filters and search results will be updated by AJAX.

There are a few more suggestions here


I noticed that, any update from feature module works only if that was created using feature module.


There are several modules that you may be able to use or deconstruct to help with your custom module.

Popup (D7)
Lightbox2 (D6, D7)
Shadowbox (D5, D6, D7)
Popups (AJAX) (D6)


Better exposed filters override -any- only working on one filter at a time

I tried this kind of configuration with more then one exposed filter, yes its only overriding label for last exposed filter. May be a bug, Why not simply modify -Any- option label with hook_form_BASE_FORM_ID_alter()

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'YOUR_VIEWS_MACHINE_NAME') {
    $form['FIRST_EXPOSED_FILTER_']['#options']['All'] = t('-NEW ANY LABEL');
    $form['SECOND_EXPOSED_FILTER_']['#options']['All'] = t('-NEW ANY LABEL');
    // and so on.
  }
}


Bullets and numbers not visible in CKeditor

CKeditor uses CSS from either your default theme or it's own stylesheet. If you are are using your site theme maybe it is set to hide the bullets and numbers.


You can do it with pure CSS, here is a tutorial: http://csswizardry.com/2011/02/creating-a-pure-css-dropdown-menu/ You can find several more if you google for CSS dropdown menu.

You will need to set up your menu, clicking on the "expanded" checkbox for any submenus you want to render.


I would make two view lists, one to show forthcoming performances and one to show past performances.

This way you can title each list so it's clear to users which is which. It would be feasible through careful CSS to make it look like they are one list. And each list will only show as required.

Filter on the date, either '>= now' or '<= now', to make each list work as you wish.


BLOCK_NO_CACHE with Normal page cache enabled

Ajax Blocks or Ajaxify Regions (since you're in D6) allow dynamic blocks within cached pages.


How do I create a link to a node to put in new entity?

Entity-created:body was a formatted text type.  Because of that the rules selector was only showing values from the Node that were also Formatted text.

Once I changed the data value i was modifying to entity-created:body:value, the text part of the formatted text, it allowed me to select more things in the selector including the node:url.


'Content Type' link not available for new content type

Go to Structure >> Menus >> Navigation >> list links

(/admin/structure/menu/manage/navigation)

Make sure that the content type link is enabled.


Language specific settings for field formatters

Define a schema in your module
config/schema/mymodule.schema.yml.

Example from the date range module:

core/modules/datetime_range/config/schema/datetime_range.schema.yml

field.formatter.settings.daterange_default:
  type: field.formatter.settings.datetime_default
  label: 'Date range default display format settings'
  mapping:
    separator:
      type: label
      label: 'Separator'
      translation context: 'Date range separator'

For more information see
Block configuration form values are not translated
You need an UI to translate, which is unfortunately not ready
yet, see this issue:

Entity view/form mode formatter/widget settings have no translation
UI

Until then you can edit the translated yaml file of an exported
config in config/sync/language/[LanguageID] or install the patch from the
issue.


Store cache's datas in files instead of database

Drupal comes with a php-file based cache backend by default: \Drupal\Core\Cache\PhpBackend, the factory is available as the cache.backend.php service.

You would configure that to use that by default with $settings['cache']['default'] = 'cache.backend.php';.

That said, I wouldn't really recommend using that. PHP files are going to fill your disk as well (without a cleanup-mechanism that the database now has) and if you have a very large site then you probably also have multiple servers and then cache invalidation becomes a problem again, clearing the cache on one server won't clear it on others unless you use a shared file system and that is again slow.

The recommended approach IMHO for a big site is to use an in-memory cache backend like Redis or Memcache (varnish is not a cache backend that is used by Drupal, it's something that sits in front of it). The big advantage of those two is that they store their data only stored in memory (configurable in case of redis) and very fast to access due to that but still easy to for multiple servers. They also have built-in purging of data and a fixed size, so they will automatically delete less-frequently used cache entries. And while not perfect, they are far better at that than the default database backend now which just deletes old cache entries and keeps a fixed amount of caches.


Remove '-Any-' value from exposed filter term field

Setting the exposed filter to required will remove the -Any- option.


How can I make my brand new module dependent on a minimal version of Drupal 7 that's required for it to work OK?

The trick, apparently, is to use the system module like:

dependencies[] = system (>=7.17)


Feeds module is stripping html tags from xml

I appears to me that the issue you are trying to resolve, might be related to the issue described in issue # 2224643 (on D.O).

If that's the case, then you might want to try the commit mentioned in #22 in that issue (or the patch attached to #20 there).


What's the difference between access arguments and access callback?

"Access callback" is the function that is called to verify the user has access to the page. As special case, it could be the value TRUE, and in that case all users would have access to it; in other words, the access permission would be bypassed.

In the case you are using a function name for the "access callback" value (by default, it's "user_access"), then you can also use "access arguments", which is an array containing the arguments passed to the access callback function.
As with other menu callbacks, the arguments must be a string, or a number; in the case it's a number, the value will be replaced with a value taken from the menu path. If you want to avoid this replacement, instead of a number you need to use a string; for example, using "1" as one for the arguments passed to the access callback would avoid the automatic replacement.

These are some example of menu callback declarations used from Drupal core modules. (The examples are from Drupal 7 code, but for what I want to point out, that doesn't make any difference.)

This is an example where the access callback is user_access().

  $items['file/progress'] = array(
    'page callback' => 'file_ajax_progress',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

This is an example where the access callback is not a function name.

  $items['user'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => TRUE,
    'file' => 'user.pages.inc',
    'weight' => -10,
    'menu_name' => 'user-menu',
  );

In this case, the access callback is user_view_access() to which is passed, not the number 1, but a value taken from the menu path (which in this case is "user/%user"); this is a particular case, as the function will get the value returned by user_load().

  $items['user/%user'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view_page',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    // By assigning a different menu name, this item (and all registered child
    // paths) are no longer considered as children of 'user'. When accessing the
    // user account pages, the preferred menu link that is used to build the
    // active trail (breadcrumb) will be found in this menu (unless there is
    // more specific link), so the link to 'user' will not be in the breadcrumb.
    'menu_name' => 'navigation',
  );

Suppose the previous menu were defined as follows, and invoked with a path like "user/hello."

  $items['user/%'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view_page',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    // By assigning a different menu name, this item (and all registered child
    // paths) are no longer considered as children of 'user'. When accessing the
    // user account pages, the preferred menu link that is used to build the
    // active trail (breadcrumb) will be found in this menu (unless there is
    // more specific link), so the link to 'user' will not be in the breadcrumb.
    'menu_name' => 'navigation',
  );

In this case, the access callback would have received as argument the value taken from the path (0 means "user," and 1 means the part after "user" and the slash); in this case, that value is "hello."

To better understand these wildcard arguments, see Wildcard Loader Arguments. The documentation page is tagged Drupal 6, but what reported is still valid for Drupal 7.


Adding Ajax to Webforms in Drupal 7 - Ajax Submit


Transactions are done with SQL and in Drupal 6 you need to write all your SQL. So to use transactions, all you need to do, is to use db_query(SQL) and include transaction in the SQL you create.

This could look like this:

$sql = 'START TRANSACTION;
       SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
       UPDATE table2 SET summary=@A WHERE type=1;
       COMMIT;';
db_query($sql);

Remember to use an engine that supports transactions like innodb.


book module navigation horizontal submenu

You can override node.tpl.php and customize where to render $content['book_navigation'].

Have also look at book-navigation.tpl.php and template_preprocess_book_navigation().


Can't see the "help" hook on the Modules admin panel

You have a period at the end of your path condition.

Try this:

function first_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('A demonstration module.');
  }
}


Is it possible to pass variables as arguments to *.libraries.yml?

Instead of defining the library in the .libraries.yml file, you should add it using hook_library_info_build(), which is the hook to add dynamic library definitions, as in your case.
function mymodule_library_info_build() {
  $libraries = [];

  $js_path = 'the dynamic path to the external JavaScript file';
  $libraries['external.bc.js'] = [
    'version' => '1.x',
    'js' => [
      $js_path => ['type' => 'external', 'minified' => TRUE]
    ],
  ];

  return $libraries;
}


Adding a Meta tags CMS function to drupal 7

There is a complete rewrite of the old drupal 6 module nodewords in progress now - it is called metatags. However the metatags module looks like it is still in the initial development phase, so you might be better off using http://drupal.org/project/metatags_quick - which already has a stable 7.x release

There is no releases on the project page, but you could clone the git repo and help with the issue queue and submitting patches back etc


You can keep your versions of nodes using  Revisioning module.In addition to it you can use Diff Moudule to compare between two versions of nodes.

And you can use Scheduler Module. to schedule the node publish.


When you have an existing feature and you are changing some configurations which are stored in the feature, you have to update your features

drush fua

does an update on all enabled features. After that you deploy your features (propably using git) an then you have to accept the changes done to your feature on the production side.

drush fra

(feature revert all) does the trick.

A better explanation is here: https://drupal.org/node/582680


Can the Drupal 6 search function also index block content?

No, block content is not searchable by default.
Have you tried the Block Search module? Seems that is what you need.

edit: After reviewing the module, I now see that the search functionality inside block content is done for only administrators, so that module probably doesn't help.


How to call preprocess functions from my custom module

Looking at template_preprocess_image_formatter, I would try the following code below.

Replace mymodule with the machine name of the module. This assume foo is the machine name of your image formatter.

mymodule_preprocess_image(&$variables) {
  /* processing logic */
}

mymodule_preprocess_image_formatter_foo(&$variables) {
  /* processing logic */
}

I also recommend reviewing Drupal 8's Core Image module as it has some of the files that call the hooks you need.

image.field.inc contains template_preprocess_image_formatter
template_preprocess_image


Try giving Limit number of replacements  value as -1 This will solve your issue.


This is content - not static text; your only options are to translate it manually yourself or use one of the contrib modules like Lingotek or Cloudwords.


Changing the field separator for multivalue fields

Normally you can control this separator directly in the views field option in the multiple field settings.

Have you tried to change this ?