Custom node field type should also support content block; what should I do?

From looking at the code, the module does not define a field type. It just defines a widget for entity reference fields.

So, what you need to create instead is an entity reference field that points to paragraphs, and then select the Paragraps widget on "Manage form display".

But that should be exactly the same for nodes as well?


Associate a content type to a specific group in drupal commons

I am assuming you are using one group content type, and "Literature" and "Art" are contents of that group type.

Tell me if I am wrong in my assumption.

You can use hook_form_BASE_FORM_ID_alter() to set a default field value for group field based current content type.

    function mymodule_form_node_form_alter(&$form, &$form_state) {
      $node = $form_state['node'];
      if (!isset($node->nid) || isset($node->is_new)) {
       global $user;
       $groups = og_get_groups_by_user($user);
          if(is_array($groups)) {
          // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
          if($node['#bundle'] == "poetry" || $node['#bundle'] == "fiction" ||$node['#bundle'] == "novels") {
          $form['group_field_name']['#default'] = $groups[0];  //Whatever index Literature has
          }
          elseif($node['#bundle'] == "painting" || $node['#bundle'] == "photography" ||$node['#bundle'] == "drawings") {
          $form['group_field_name']['#default'] = $groups[1];  // Art's index
          }
          }
      }
    }


How do I add default values to a database table using hook_install()?

The better way is to do it inside hook_enable(); at the time the hook is invoked, the module is already installed, and the schema of its database is available to Drupal, and to drupal_write_record(). As the hook is invoked all times a module is enabled, and not just when the module is installed, the hook implementation should check if it didn't added those database rows already (e.g., it should use a Drupal variable containing a boolean value).

As example of module that uses hook_enable() for a similar purpose, you can check forum_enable(), or php_enable() (which adds the "PHP code" input format).

function php_enable() {
  $format_exists = (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'PHP code'))->fetchField();
  // Add a PHP code text format, if it does not exist. Do this only for the
  // first install (or if the format has been manually deleted) as there is no
  // reliable method to identify the format in an uninstall hook or in
  // subsequent clean installs.
  if (!$format_exists) {
    $php_format = array(
      'format' => 'php_code',
      'name' => 'PHP code',
      // 'Plain text' format is installed with a weight of 10 by default. Use a
      // higher weight here to ensure that this format will not be the default
      // format for anyone.
      'weight' => 11,
      'filters' => array(
        // Enable the PHP evaluator filter.
        'php_code' => array(
          'weight' => 0,
          'status' => 1,
        ),
      ),
    );
    $php_format = (object) $php_format;
    filter_format_save($php_format);

    drupal_set_message(t('A PHP code text format has been created.', array('@php-code' => url('admin/config/content/formats/' . $php_format->format))));
  }
}

As shown from those hook implementations, the code could necessarily need to be executed all times the hook is executed; it could also be the code needs to just executed once, as in the case the default values added to the database cannot be altered from the user, who doesn't have a user interface to alter/delete those values.


How do I add  tags to the output of a view list?

In the View edit screen, click Advanced. At the very bottom of that, you'll find a bit called: Theme: Information. Click the Information link and a new window will pop up, showing you theme overrides for the view. Each category changes different parts of the view.

All of the file names listed on each type will show the available filenames which could be used to override this view, in order of least specific to most specific. So if you pick the first one, it will probably override all of your views, while if you pick the last one, it will only override that view in a certain display.

Once you've picked what you're going to override, click the link and copy all of the code shown there to the clipboard. Then go to your theme directory and make a file with the filename you picked from before and paste in the code you copied. Now just add the
 tags you want wherever you like.

You'll need to click the "Rescan template files" button for Drupal to pick up your new theme override file. Views shows you which one it will use for the view by putting the one it will use in bold.

Edit: When writing this, I was going through the steps for Drupal 7, but I believe the steps are very similar for Drupal 6.

Next Edit: From the code you have pasted, it looks like the most appropriate place to put the new div tags would be (see the asterisks):

**
**
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <<?php print $field->inline_html;?> class="views-field-<?php print $field->class; ?>">
  <?php if ($field->label): ?>
    <label class="views-label-<?php print $field->class; ?>">
      <?php print $field->label; ?>:

  <?php endif; ?>
  <?php
    // $field->element_type is either SPAN or DIV depending upon whether or not
    // the field is a 'block' element type or 'inline' element type.
  ?>

    <<?php print $field->element_type; ?> class="field-content"><?php print $field->content; ?></<?php print $field->element_type; ?>>
    </<?php print $field->inline_html;?>>
<?php endforeach; ?>
**
**

I normally experiment a bit with this, so it's a bit difficult to tell you the exact spot offhand, but hopefully the above will be close...


How do I add the login form in page.html.twig?

I think your best bet is to go directly to the path '/user' where the login form will be the main contents of the page.


Adding a CDN feature for a new installation: now or later?

Easy to add later. We usually do it right at the end. =)

To expand, it's easy anyway, but the CDN module makes it even easier:
http://drupal.org/project/cdn

As described on the project page, CDNs work by taking files from your normal Drupal 'files' directory, either on demand or on creation (original pull or file conveyor) and in either case this can be done at the end - you can build your whole site, upload lots of files without it - it will all sort itself out when you hook things up.

The CDN module rewrites file links so you don't have to think about that either. And if you miss any, they'll still be there on your local server, everything will still work, and you can spot them in server logs and work out why they're still being served from local.

So yeh, it's cool. No need to worry about it right away.


Notify user if they are about to delete a node that is referenced by another node

If the node has an entity reference you can use the Rules module.


Doh, what a dummy! I missed an option in rewrite results on the image field to set output as link with no transform!

Thanks everybody.


joining profile types using views module

Currently it's creating a join for each relationship (each profile type) that's why you see several rows. Question is what would happen if a user has several profile types (can they have that)?

You might get by with putting Distinct on your query.

In Views, fold out Advanced and look for Query settings under Other. Choose settings and check Distinct. Hit save.


You can edit global.css insted of editing alpha_default_normal.css so that changes will persists even if you changes your browser resolution. And according to me, set the width of the div in percentage... so it will automatically adjust to other screen resolutions.
eg.

width:70%;
margin : 0 auto;


Is there a way to add new custom selection rules for panels?

We initially did it the way that you did. However, after a site security audit, we were told that we should not include PHP in that way (even though it's there and available). The solution is to create a custom rule using ctools access plugins. This page has an excellent breakdown of how to do it. We now have about 5 or so custom ones we use through custom modules.


Where does the value $ds_content come from in display suite templates?

Looks like it's set in ds/includes/ds.registry.inc in _ds_ds_layout_info() which implements a hook hook_ds_layout_info


How to programmatically set role based permissions on a field?

Ok, worked this one out...

I created my own function to do this, which I have called in the MY_MODULE.install file, as I'm creating the fields there, and as I understand, you can't set permissions in the install file.

Note, this is just a custom function name, not a hook - you could call it anything.

function MY_MODULE_assign_field_permissions($role_name, $permission, $field_name) {
    $permissions = array($permission.' '.$field_name)
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
}

$role_name is the name of your role, $permission is the natural language permission, like 'view own', 'create', 'edit', etc. and finally $field_name is the name you gave your field.

Here's how I would call it in my MY_MODULE.install file to allow the role type my_role view their own entries for field_my_field:

MY_MODULE_assign_field_permissions('my_role', 'view own', 'field_my_field');


How can I determine if a form exists in my Drupal installation?

Since the 'ID' you pass to drupal_get_form() is actually the name of a PHP function, the simplest way to see if it exists is using plain old PHP:

if (function_exists('form_id')) {
  // ...
}

If you need to check that the return from the function is a suitable Drupal form array, you'll need to use one of the methods described by MPD.

This will only work for forms for which the name is explicitly defined as the string you're passing in; i.e. forms whose root function is provided by a hook_forms() implementation will not match using this method.

It's worth bearing in mind that with whichever method you use, any form you're trying to identify will have to exist in a file that's included in the current page request. With that in mind it might be wise to keep all the form functions in question in the .module file of an enabled module, which will always be included.


How do I control the file appearance using File Entity?

Since I've been no longer into Drupal for a long time now, I'm even not sure I remember the answer. But I managed to dig up the code below which smells like an answer @digitgopher asks for. So FWIW, and sorry for somewhat messy comments hanging around:

<?php

/**
* Implements hook_field_formatter_info().
*/
function fileformatter_field_formatter_info() {
  return array(
    'fileformatter_formatter' => array(
      'label' => t('File Formatter'),
      'field types' => array('file'),
      'settings' => array(
        'link_text' => '',
      )
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function fileformatter_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  //This gets the view_mode where our settings are stored
  $display = $instance['display'][$view_mode];

  //This gets the actual settings
  $settings = $display['settings'];

  //Initialize the element variable
  $element = array();

  //settings
  $element['link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
    '#description' => t('The text to appear next to icon. Leave empty for raw file name. Possible tokens: %fn = file name, %fd = file description, %cp = node title'),
    '#default_value' => $settings['link_text'],
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function fileformatter_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  $summary = t('will be labeled ');
  $summary .= ($settings['link_text'] == '') ? t('using file name') :  $settings['link_text'];

  return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function fileformatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    $html = '';

    // LINK TEXT
    $link_text = ($settings['link_text'] == '') ? $item['filename'] : check_plain($settings['link_text']);

    /* if (module_exists('token')) {
      $link_text = token_replace($settings['link_text'], array('node' => $entity));
    } else { */
      $link_text = str_replace('%fn', $item['filename'], $link_text);
      $link_text = str_replace('%fd', $item['description'], $link_text);
      if($entity_type == 'node'){
        $link_text = str_replace('%cp', $entity->title, $link_text);
      } else {
        $link_text = str_replace('%cp', '', $link_text);
      }
    // }

    // last resort, so to not allow for empty links
    if($link_text == ''){
      $link_text = $item['filename'];
    }

    // ICON - as CSS class background, which reduces file requests and allows for easier vertical-alignment
    $dashed_mime = strtr($item['filemime'], array('/' => '-'));
    /* // img method:
      $icon = theme('file_icon', array('file' => file_load($item['fid']), 'icon_directory' => drupal_get_path('module', 'file') . '/icons'));
      $icon_html .= '' . $icon . '';
    */

    // LINK MARKUP
    $url = file_create_url($item['uri']);
    $link_options = array(
      'html'        => TRUE,
      'attributes'  => array(
        'title' => $item['filename'],
        'class' => 'file file-formatted ' . $dashed_mime . ' file-fid-' . $item['fid'],
        'type' => $item['filemime'] . '; length=' . $item['filesize'],
        'target' => '_blank',
       ),
    );

    $html .= l($link_text, $url, $link_options);

    $elements[$delta]['#markup'] = $html; // Assign it to the #markup of the element
  }
  return $elements;
}


Sort of, but you'll need to URL encode the second ? otherwise the URL will be invalid.

The best thing to do is use l() or url() which will do this for you:

$query_string = array('destination' => 'xxx/yyy?token=zzz');
$url = url('<front>', array('query' => $query_string));

That will produce the string:

/?destination=xxx/yyy%3Ftoken%3Dzzz

Which is the correctly encoded version of the URL in your question.

Drupal will also respect this method when auto-redirecting based on a form submission etc. So the page you get directed to will actually look like this:

/xxx/yyy?token=zzz


How to do simple subtraction in Computed Field?

As per the documentation of computation field module to calculate the difference of two fields you need to use the PEAR:

$path = '/pathToPearsParentDirectory/pear/PEAR';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'PEAR.php';
include_once "Text/Diff.php";
include_once "Text/Diff/Renderer.php";
include_once "Text/Diff/Renderer/inline.php";

$diff = &new Text_Diff('auto', array(array($node->field_nameOfOneFieldToCompare[0]['value']), array($node->field_nameOfOtherFieldToCompare[0]['value']))); $renderer
= &new Text_Diff_Renderer_inline();

$node_field[0]['value'] = $renderer->render($diff);

More info about it available here http://arencambre.com/blog/2009/05/17/how-i-got-field-diffs-working-with-drupal-pear-text_diff-and-dreamhost


Transforming the external link with in the site

Using iframes is not a good option. Besides, I suggest to start using jQuery and update the function for the specific 'div'. We can add jQuery using JSinjector module, Navigate to JSinjector as Configuration/development/JSinjector.

Hope It would work fine in such a kind of issues.


select term from reference field but deny edit term

Found it. It appears to be a bug in both the rc version and the dev version of the module Taxonomy Access Control for D7. Details from project page:

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

Once a user has access to the edit node form AND they are allowed to 'add tag' on the access-rules-for-user page for that vocabulary, that term will show up and will be able to be ticked/set on the node form regardless of whether or not the default and other vocabulary terms in that vocabulary have been set to 'allow' or 'deny' the 'add tag' on the access-rules-for-user page. Hopefully this makes sense to others as well.


For this you need to create a sandbox project and open up an issue in the issue queue of the existing module, posting a link there and urging the maintainer of that project to have a look.

If they wish, they can commit that module as the official 7.x version, or might even add you as a co-maintainer of the module if you are interested. In case they do not find this module interesting, you can create it as a separate project: Create the sandbox, apply for project application approval in the Drupal.org project approval queue, and get this published as independent module.


convert node/id to node/path-alias in content body

I found a hook in Pathologic module as hook_pathologic_alter and I used it to convert node path to URL alias.

I used this hook as follows

/**
 * Implements hook_pathologic_alter().
 */
function mymodule_pathologic_alter(&$url_params, &$parts, &$cached_settings){
    if ($parts['path'] != '<front>') {

        //get the alias for the path and assign it in path
        $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/'.$url_params['path']);

        //Url::fromUri which Pathologic uses need a path without slash at first, so trim it
        $url_params['path'] = ltrim($alias, '/');
    }
}

This converts a node path to alias and pass it, so Pathologic will form a URL with alias.


How to get node ID from drupal 7 when i know title (title shouldnt be duplicated) Drupal

As suggested by Mołot you can do this with EntityFieldQuery.

// Initialize EntityFieldQuery.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');

$query->propertyCondition('title', "My title", "=");

// Execute query and collect results
$result = $query->execute();

$nids = array();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}

In the example $nids will be an array with all node ids that have the title "My title". Entity field query really helps you when the query gets more complicated. You don't have to do joins for example yourself but can instead do something like $query->fieldCondition('field_news_types', 'value', 'spotlight', '=') which using db_select would require joins on tables.


You can use Drupal's default contact form and customize the fields as per your need which will have all the required logic for form handling. Then you can check and apply the theme as per your need to it.


Alternate way to get form without using drupal_get_form

I don't belive you that mine work in any places

$form = drupal_get_form('yuor_form');
print drupal_render($form);

You can create block with form and output them where you want, somthing like that

function your_module_form_theme() {
  return array(
      'yuor_form' => array(
          'render element' => 'form',
          'template' => 'your_form',
          'path' => drupal_get_path('module', 'your_module_form') . '/templates',
      ),
  );
}


How to force a theme to use a sitewide custom menu

How can I insert a sitewide menu?

You can use Context to insert menu blocks into regions.
Contexts can be set to be site wide.
Make sure that your theme supports the region into which you are inserting the menu block.  The region should be defined both your theme's .info file and also it's relevant templates (generally the page template).

Making a menu with a custom template

You can use the devel_themer module to sniff what templates you can implement to override the menu's default theming.


Maybe there is another solution for this problem but after trying many things I noticed that one solution is to disable the sorting of the "Run Date and Time" field. This way, the table is always sorted in the same way for that field but the pager is respected.


jQuery events are lost after form reload

You need to use the drupal behaviors: if you run your code on ready function when the form is rebuilded on an ajax action all the handlers you have active will disapear because the item fields are replaced by the new ones.

This is the basic drupal behaviors template:

(function ($) {
  Drupal.behaviors.mymodulecustombehavior = {
    attach: function (context, settings) {

      // Execute your code

    }
  };
})(jQuery);

This way after a ajax, all you code inside this behaviour will be called again.

Maybe you will want to add .once() property to avoid execute some parts of your code twice.

Documentation: https://www.drupal.org/node/756722


jquery get or post methods for drupal block module

For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.

function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'access callback' => TRUE, //you can set it with your permission
      );
   return $items;
   }

and in yourhalderjust need pass a block :

function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);
}

and in your clientside get it with something like this

$.ajax({
    type: "POST",
    url: 'youruniqepath',
    //data: {}, you can also pass block name and act more dynamicly
    success: function (data){
        $('#yourplace').html(data);
    }
});


I was facing the same issue.  I think the render function doesn't add "name" to the html so the form values are not submitted. I fixed this by adding them in the array

'#attributes' => array(
  'class' => array('edit-bid-amount'),
  'name' => 'bid_amount'
),

The function now is

function custom_callback(&$form, &$form_state) {
  $next_bid = 100;
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace(
        "#test-ajax", render($form['bid_amount'] = array(
          '#type' => 'textfield',
          '#title' => t("Your Bid"),
          '#value' => $next_bid,
          '#prefix' => '
',
          '#attributes' => array(
            'class' => array('edit-bid-amount'),
            'name' => 'bid_amount'
          ),
          '#suffix' => '
',
          )
        )
      ),
    )
  );
}

Hth,
Sadashiv


How do I tell Drupal 8 to use my custom module's theme template when rendering an image that is linked?

Answering my own question. The solution was to use: hook_theme_registry_alter()

/**
 * Implements hook_theme_registry_alter
 */
function MY_MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['image_formatter']['path'] = drupal_get_path('module', 'MY_MODULE') . '/templates/field';
}

In my module I have the templates/field directory with the template image-formatter.html.twig, so no other changes were necessary.


Suggestions:

Make sure the module handling custom node type exists and is enabled.

Based on case_studies_node_form callback, it's most likely case_studies module.

If you don't know type of the node, you can load it using drush, e.g.

drush ev "var_dump(node_load(123));"

Make sure the module which handles custom node type defines hook_node_info() in its .module file.
Clear caches (drush cc all, restart Memcached/Redis if present).


Views: Filtering nodes on the basis of logged in user role

Yes, you can use node "Author uid" as the "Contextual filter" in the views and can set default value as "User id from logged in user" or "User id from URL" for the "Author uid".

If you will select "User id from logged in user", then it will display the node created by the logged in user  or if you select "User id from URL", then it will display the node created by the user id from the URL.

Regarding, displaying node published and unpublished, you need to set permission for user role to view "unpublished own nodes", so user can view his unpublished node.

For the site admin user, he can only view the node created by him. If you want to display all  nodes to site admin, then you need to create another view.


Services custom resources issues - IIS, MSSQL

In your case the path should be 'path' => 0, because it is the first argument after the endpoint url. Currently you have 1 and it will look for undefined argument which will end up with an exception.

For more information read services oop to get a better understanding in an OOP way. https://github.com/hugowetterberg/services_oop


Mandatory field (A or B) in a content type

You could use the Field validation module to take out some of the legwork.

  This module adds an extra tab to each field instance, allowing you to
  specify validation rules for your field instances.

There's a validation rule built in for

  Require at least one of several fields

which is exactly what you're after.


The key is using -1 second So

first solution: Use this values

next sunday - 1 week

and

next sunday  - 1 second
Second solution  based on you told on question :

last sunday
  and
  this sunday - 1 second


No need adition module but date module.
go to your views add a filter with type date choose Date: Date (node_revision) pass Configure extra settings for filter criterion Date: Date (node_revision) with  your optionals ,and in Configure filter criterion: Date: Date (node_revision) select Is between option.
If you want expose your filter check  Expose this filter to visitors, to allow them to change it


The function buildRow returns a render array. You can put simple strings directly in the array, because later it will be put in another html structure like a table. An example from core, where it is used both ways (CommentTypeListBuilder.php):

public function buildRow(EntityInterface $entity) {
    $row['type'] = $entity->label();
    $row['description']['data'] = ['#markup' => $entity->getDescription()];
    return $row + parent::buildRow($entity);
  }

So using the '#markup' element is optional. You can use it to be on the safe side, when you don't know how your render array is processed.

For complex elements you need a render element. The method view() would generates this:

$row['email'] = $entity->email->view();

But this does not work. The problem seems to be in the custom entity. According to the error message there is a call to an undefined method render, which should be defined in MyEntity. Your entity does not know how to handle the email field.

If you don't want to theme the field, you can use the value as markup:

$row['email']['#markup'] = $entity->email->value;

Or you can put the field as an object:

$row['email'] = $entity->email;

Or you can build your own render array, for example as a link:

$row['title'] = array(
      '#type' => 'link',
      '#title' => $entity->label(),
      '#url' => $uri,
    );


I am assuming the logic is:

Display this block only on pages with a path beginning with cart/*,
And only when the user has `access administration pages` permission

If so....

if (arg(0)=='cart' && arg(1) && user_access('access administration pages')) {
  return TRUE;
} else {
  return FALSE;
}

If you want it displayed on path cart all by itself as well, just remove the && arg(1) from the above and then it will work on cart in addtion to cart/foo and cart/foo/bar etc.

If, however, you want it only on cart/oneargumentonly, you can add in && !arg(2).

ADDITION/CORRECTION:

if (user_access('access administration pages') || (arg(0)=='cart' && arg(1))) {
  return FALSE;
} else {
  return TRUE;
}

while return FALSE if the user can access administration pages regardless of the path OR the path is cart/* regardless of any permissions.

So, if my logic is right now, if the user can access administration pages the if is "short circuited" and returns FALSE.  Otherwise, if the user doesn't have this permission, it continues on and if the path is cart/* it returns FALSE.  Otherwise, since we already know the user doesn't have the access administration pages permission it returns TRUE for any other path.

FINAL?

if (user_access('access administration pages') || arg(0)=='cart') {
  return FALSE;
} else {
  return TRUE;
}


Clearing cached CSS when updating live web page

Navigate to http://mysite.com/admin/config/development/performance and click the "Clear all caches" button :)

Or if it's an option, install drush on your server and use drush cc css-js, it will only clear CSS/JS cache so won't slow the site down while all the caches are rebuilt.


How to convert a Drupal website to standalone exe file?

You should generate a static copy of your site first.

For that you can either use a module like the static module, or just "copy" your entire site with wget or curl.

So for example you can do something like this :

wget -p --convert-links http://localhost/ -P ~/site_static_copy

(This assumes that you're accessing your localhost with http://localhost/ and that you want to copy under your ~/site_static_copy directory )

Once you've done that you'll be able to package the copy with the tools you mention.


List registered users who are currently viewing a page

Check the viewers module. Here is an excerpt from ots project page:

Viewers is a small module, which builds a block showing which other users are viewing the same page as the current user. The 'other' users are logged in users or anonymous users or both users. You can set for how long you want a user appear on the viewers list of each page. And finally you can choose the position of the block from the admin/build/block page.

As stated it won't provide you the functionality of dynamically refreshing to show page view activity in real-time, but you can modify it through the custom code by refreshing the block after a required interval of time. Or you can try the Block Refresh module. Here is an excerpt from ots project page:

Block Refresh allows an administrator to configure a block to refresh it's content via 3 different methods: automatically via a timer (eg every 30 seconds) , manually via a 'refresh' link, and once on page load.
Block Refresh uses jQuery/AJAX so the refresh happens "behind-the-scenes".
Block refresh can be handy to serve fresh content in certain blocks on otherwise cached pages. You can opt to bypass drupal's cache for the refresh callbacks for each block.


How do I alter webform values before submission?

The answer linked is mostly right, just a couple of updates to get it working. In a custom .module add:

use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    $form['actions']['submit']['#validate'][] = 'MODULENAME_form_validate';
  }
}

function MODULENAME_form_validate($form, FormStateInterface $form_state) {
  $form_state->setValue('hidden_id', 'Value for Hidden field');
}


You can check $user->getLastAccessedTime() in a preprocess function and set this as a variable, for example the view at /admin/structure/views/view/who_s_online determines if someone is "online" by checking if last accessed time is within the last 15 minutes.

function mymodule_preprocess_views_view(&$variables) {

  if ($variables['view']->id() == 'my_example_view') {
    /** @var $account \Drupal\user\UserInterface */
    $account = <load up your user>

    if ($account->isAuthenticated() && time() - $account->lastAccessedTime() < 900) {
      $variables['online'] = ['#markup' => 'online'];
    }
    else {
      $variables['online'] = ['#markup' => 'not online'];
    }
  }
}

And then to use 'online', you'd need to use a custom template for views-view-my-example-view.html.twig.

If you want to check a bunch of users, it may make more sense to use a view mode and use the preprocess function for the view mode.

The main point of this answer isn't how to theme views, but how to determine "online" as best as possible using Drupal.


Caption Filter works in Preview, but not in regular view of node

OK, I figured this issue out.  This particular content type was using a custom template and I forgot to push the body content through check_markup(..) before outputting it.


Different roles depending on a user's field

You should be able to do this with a custom module and without roles. There is plenty of documentation around for creating custom modules, so I will not go into those details.

In your .module file, make use of hook_node_access:

function MODULENAME_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  // Only work on edits.
  if ($type == 'contry_content_type' && $op == 'edit') {
    // Field get items returns an array.
    $user_countries = field_get_items('user', $account, 'country_field_name');
    $content_countries = field_get_items('node', $node, 'node_country_field_name');

    if ($user_countries[0] == content_countries[0]) {
        return NODE_ACCESS_ALLOW;
    }
  }

  // Returning nothing from this function would have the same effect.
  return NODE_ACCESS_IGNORE;
}


How to restrict entity reference displaying values?

You'll have to dynamically create that select list based on the field's values which are TRUE from the CT Y. I suppose that this select list belongs to a from, and what a convenient hook hook_form_alter is!

/**
 * Implements hook_form_alter.
 */
function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_xyz_form_id') {
    // Find all referenced items
    $target_ids = $form['field_reference_to_ct_y'][LANGUAGE_NONE][0]['#options'];
    // Load all referenced items
    $nodes = node_load_multiple(array_keys($target_ids));
    foreach ($nodes as $node) {
      if ($node->field_to_check_if_true[LANGUAGE_NODE][0]['value']) {
         // Alter the select list options
         $form[field_select_list][LANGUAGE_NONE]['#options'][$node->nid] = $node->title;
       }
    }
  }
}


How to add body class that carries the menu depth of the current page?

I did something similar in the past, but I can't remember on which project, so I don't have working code.

Inside a template_preprocess_html, you get the breadcrumb via menu_get_active_breadcrumb.  You then walk the breadcrump  keeping track of depth, comparing the paths against the current path.  When you find a match, you end the walk and then

$variables['classes_array'][] = "menu-depth-" . $depth;

I am pretty sure this is what I did.


You can add a cache context to a region the same way as to any other page element:

function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'myregion') {
    $variables['#cache']['contexts'][] = 'user';
  }
}

But this is probably not what you want, because regions are not cached. Usually the blocks inside a region are cached and the complete page which contains the regions. The cache context of the region will only have an effect on higher level elements, not downwards.


Is there a way to re-categorize content in a list form?

Assuming I read your question correctly, you could try the Edittable Views module. details from its project page:

Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.


Log in to your database panel (for example PHPMyAdmin) and run following query:

UPDATE system SET status='0' WHERE name='tagadelic';

Additionally, if you are using Drupal 7, run:

DELETE FROM cache_bootstrap WHERE cid='system_list';

After then you can uninstall problematic module via administration panel.


I want to change the order of fields in login/registration form

You probably should hide this fields, and show them with javascript before captcha input value is not empty. Check it with "on change" function:

 $('body').on('change', '#CAPTCHA INPUT', function(){}


How to use the Rules and Group modules to send a privatemsg to users of a role in a group?

Have a look at Comment #2 in issue # 2603136 (from the module maintainer). Here is how it looks like (I added the bold markup in it here):

Meaning you can already use Rules to:

Add a new Group
Create a new GroupMembership and save it (the equivalent of $group->addMember())
Add or remove a GroupRole from a GroupType
React on new GroupMembership or Group entities
…

What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
Useful Rules we may add could be:

E-mail all members of a Group, optionally filtered by GroupRole
Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"
Feel free to add here

As per the bold phrase above, I think the exact answer to your question is "Such Rules condition is not available ... yet".
Plan B
However, since you're also using the Privatemsg module, you may want to have a look at the community documentation about Privatemsg-Rules Integration, especially the child page about Introduction to Privatemsg-Rules: it lists the various Rules Events, Conditions and Actions you have available.
More important in the context of this question, is what's explained in the child page "Message notification via email depending on user's role".
See where I'm going ...? No? Well: if you can think of a way to assign a role that corresponds to the name of the group (so 1 role for each role), you have an alternative solution that functionally will do exactly what you want to do. Obviously, 1 role for each "group" is only manageable if you don't have dozens (or hundreds?) of groups ...
Note: I haven't checked it yet, but it may well be possible to use the Rules module to auto-assign such role automatically when a user gets granted access to a group (Homework for you? Or ask a new question?).


Values don't get saved to the database when fields are wrapped in a container

It seems Drupal adds a #tree = true property to the field parent so you need to process the data output by the form youserlf or the form nested elements will be ignored. As @IvanJaros poited out, WidgetBase::massageFormValues let's you alter the data.

public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
{
  for ($i=0; $i < count($values); ++$i) {
    if (isset($values[$i]['concelhocontainer']['concelho'])) {
      $values[$i]['concelho'] = $values[$i]['concelhocontainer']['concelho'];
    }
  }
  return $values;
}


How to move the edit tab in user-profile.tpl.php

Ok, i find the answer :

function THEME_preprocess_user_profile(&$variables) {
  $variables['tabs'] = menu_local_tabs();
}


RSS feed not updating using feeds module

If you look at /admin/reports/status does it say that cron is running?

If cron is running then looking at the watchdog entries (
admin/reports/dblog) around the time it is running may give you an insight.

If that dosn't work then you may have to start putting debug into the modules code to work out what is going wrong.


How do I override menu items with my own implementation?

You can use hook_menu_alter() to reroute the request for that page to your own module's functions:

function MYMODULE_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'MYMODULE_access_callback';
  $items['user/%user/edit']['page callback'] = 'MYMODULE_user_edit_page_callback';
}

function MYMODULE_access_callback($account) {
  if ($something) {
    return FALSE;
  }

  return TRUE;
}

function MYMODULE_user_edit_page_callback($account) {
  if ($something) {
    return drupal_get_form('some_form');
  }
  else {
    return drupal_get_form('some_other_form');
  }
}


It's very likely automated programs looking to see if you have the proper restrictions on certain directories.

There's no way to prevent it from happening, but you could either turn off 404 logging or have your server log 404 errors to a different file.


I suggest you to run -

composer self-update
composer update

It might solve your problem, but if it doesn't then try to install latest version of drush. I installed drush using https://www.drupal.org/node/1248790.
However, there is a full documentation on how to install drush for specific operating system. Link to documentation - https://www.drupal.org/node/1791676


page--user--login.tpl.php is not recognized

This question is similar to https://stackoverflow.com/questions/8712061/style-drupal-7-log-in-page

It looks like you need to also have:

a page.tpl.php in your theme for page--anything-else.tpl.php to work
a page--user.tpl.php in your theme

You should also always clear the theme cache after adding/removing template files.


How do I format the display and submission format of a datetime field in a custom composite?

For defining the format of the DateTime field you can use CUSTOM COMPOSITE SETTINGS.

Example: To set the format to datepicker like a normal date field, set datepicker: true
inside the custom text field for the respective composite DateTime element. All other properties can be added here.

You can checkout the JSON representation of the respective property from the source option of the webform. Copy-pasting the properties inside the custom composite setting is all needed.

To set the submission format:

Go to Advance option of the composite element > Under submission display fieldset select the way you want to display the items.


Rule running after node update shows previous content

you can use

entity_get_controller('node')->resetCache(array($node->nid));

Working for me!!


How to change a fields label name based on another fields value?

Consider using the Conditional Fields module. Excerpt from its project page:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

So if you have like 6 possible values (Option 1, ... Option 6), as in your comment below the question, you could create 6 fields with label "Option 1", ..., "Option 6".
Not sure if it is acceptable to "split" your "Field Two" in like 6 separated fields, but at least it would change the field labels as you are asking for.


How can I show contextual links on my node's full content view mode?

if you want to show contextual link on a node view
try out this code on your custom module file.

function mymodulename_node_view_alter(&$build) {
  $node = $build['#node'];
  if (!empty($node->nid)) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }
}


If this is you own script, you could simply convert it into a module. That is easy, just create a module (tons of guides to be found in the internet) and put your functions in the .module file, then they will be available to all other code running on the site.

If this is a script/library provides by someone else, you could either place it in a custom module folder and include it with module_load_include() or (better!) declare it as a library with the help of the Libraries module. You will however need to create a custom module with some code to connect the functions of your script with drupal (Usually implementing the correct hooks and calling your functions from that) for both methods.

See also How do I go about putting standalone PHP files into Drupal 6? and How do I load a library defined with hook_library() on node/edit pages?.


What do I add to template.php so I can render regions in a page created in hook_menu()?

Well, replace this line

render($region['sidebar_left']);

with

render(block_get_blocks_by_region('sidebar_left'));

and replace this line

render($region['sidebar_right']);

with

render(block_get_blocks_by_region('sidebar_right'));

hope it will work for your case :)


Commerce / Rules - commerce-order:mail is empty for anonymous users

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Action in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Checkout process" for sure completed, and your "eMail ID" will have been updated as expected.

Rules debugging

If none of the above helps, then move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your commerce-order:mail). It may help to check if the cause of your problem is because of what is written in the comments from james, i.e.:

  anonymous user won't be having any mail, that is why the commerce order also not having any mail. There is an option in commerce to allow the user to login while checkout. I believe the functionality works fine. I usually ask user to login before proceeding to checkout itself. So, I have never faced the above mentioned issue with commerce and rules.


Comment styling dependent on author's user roles

I got it myself. Here is how to do it:

In your theme template.php:

function MYTHEME_preprocess_comment(&$vars) {
    // user roles
    // 1 = anonymous user
    // 2 = authenticated user
    // 3 = administrator
    // ...
    $vars['role_classes'] = '';
    $sql = "SELECT users_roles.rid FROM {users_roles} WHERE users_roles.uid = " . ((int) $vars['comment']->uid);
    $result = db_query($sql);
    foreach($result as $record) {
        $roleId = $record->rid;
        if($roleId == 3) $vars['role_classes'] .= ' comment-by-admin';
    }
}

Then change in your comment.tpl.php

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

to

<div class="<?php print $classes; ?><?php print $role_classes; ?> clearfix"<?php print $attributes; ?>>


Add a relationship as Entity Reference: Referencing entity
Name it with the name of your content type for instance (easier to read in the view settings)
Check the Require this relationship option
Add a contextual filter with Content: Nid

Here comes the trick!

Choose Provide default value in the WHEN THE FILTER VALUE IS NOT IN THE URL fieldset
Type should be Content ID from URL

This will make Drupal fetch the context from the current URL where your block is displayed and loop through the files referenced by the current node.

TA-DAAA :-)


What are differences/advantages of Invite vs. Referral modules?

Invite module is more popular and is a more active project. The last commit was 4 weeks ago, while User Referral git repository has been inactive for more than 1 year. Considering that the last version of User Referral is still in beta, I would check Invite first.

Back in 2007, there was an idea of merging the two into Invite, but apparently did not happen.

You can see some differences between them discussed in the previous link. Some of them are:

Invite sends a coded registration link by e-mail whereas User Referral displays it.
Referral's tracking uses a session variable to store referral information. Invite's tracking code is lost if the user moves away from the registration page.
Invite codes are always unique and can be used only once.
Invite codes have an expiry date.
User Referral display a referral link (such as referral/123) in the user's page.

They also seem to provide integrations with different modules.


What is best method for token replacement within node content?

Token Filter

  Token Filter is a very simple module to make token values available as
  an input filter.


Use a twig variable inside a twig render

You can use the variable inside of the method get():

{{ node.get(MYVARIBLE).entity.fileuri }}


Feeds: update nodes using a second import

To update existing content using feeds importer, you will have to mark Customer ID field as a Unique Key.


How to change field cardinality per form either programatically or by rule?

There are the following hooks which allow to alter the widget form such as hook_field_widget_form_alter and hook_field_widget_WIDGET_TYPE_form_alter, but they only apply to widget form element.

As for workaround, it's possible to set the field to Unlimited and use hook_form_alter to remove add_more element manually like:

$form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
$form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;

or overriding/removing #theme:

unset($form['field_foo'][LANGUAGE_NONE][0]['#theme']);

for certain conditions.

Using Rules, it's possible to use Rules Forms Support module which can deal with form elements, so you can change the items_count. Here is sample rule dealing with a multi value field in Entityform:

/**
 * Implements hook_action_info().
 */
function mymodule_entityform_rules_rules_action_info() {
  return array(
    'foo_entityform_rules_set_cardinality_value' => array(
      'label' => t('Change items count of a multi value field'),
      'group' => t('Rules Forms'),
      'parameter' => array(
        'form' => array('type' => 'form', 'label' => t('Form')),
        'form_state' => array('type' => 'form_state', 'label' => t('Form State')),
        'element' => array('type' => 'form_element', 'label' => t('Target Element')),
        'value' => array('type' => 'form_element', 'label' => t('Value from Element')),
      ),
      'base' => 'foo_entityform_rules_set_cardinality_value',
      'callbacks' => array(
        'access' => 'rules_forms_integration_access',
        'form_alter' => 'rules_forms_element_form_alter',
      ),
    ),
  );
}

/**
 * Implementation of rule callback.
 */
function mymodule_entityform_rules_set_cardinality_value($form, $form_state, $element, $value) {
  module_load_include("module", "rules_forms", 'rules_forms');
  $val_elem = &_rules_forms_get_element($form, $value);
  if (!isset($form_state['field'])) {
    return;
  }

  $element = substr($element, strpos($element, ':') + 1);
  $path = explode(':', $element);
  if (count($path) == 1) {
    $path[] = LANGUAGE_NONE;
  }

  $field_state = &drupal_array_get_nested_value($form_state['field'], $path);
  if (!$field_state) {
    return;
  }

  $limit = !empty($val_elem['#value']) ? $val_elem['#value'] : (!empty($val_elem['#default_value']) ? $val_elem['#default_value'] : NULL);
  $field_state['items_count'] = $limit;
  $field_state['field']['cardinality'] = $limit; // Won't work for field_multiple_value_form().
}

This works when field is set to Unlimited, however Add another and Remove buttons still needs to be removed from form_alter as shown below:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

    // Check cardinality.
    // If items_count for a field has reach its cardinality limit,
    // then remove Add more and Remove buttons.
    foreach ($form as $key => $item) {
      if (is_array($item) && !empty($item['#type']) && !empty($item['#language']) && $item['#type'] == 'container') {
        $field = &$form[$key];
        $langcode = $field['#language'] ?: LANGUAGE_NONE;
        $field_state = field_form_get_state($field[$langcode]['#field_parents'], $field[$langcode]['#field_name'], $langcode, $form_state);
        if ($field_state['items_count'] == $field_state['field']['cardinality']) {
          $field[$langcode]['add_more']['#access'] = FALSE;
          foreach (array_column($field[$langcode], 'remove_button') as $key2 => $rm_item) {
            $field[$langcode][$key2]['remove_button']['#access'] = FALSE;
          }
        }
      }
    } // end: foreach
  }
}

It's also worth to try some patches from Allow cardinality to be restricted (overridden and reduced) in the field instance settings or  Add hook alter to override field_multiple_value_form().

There is also Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

Some other proposed workaround from here by @donquixote (without actually hacking Drupal core) could include:

a new widget type with FIELD_BEHAVIOR_CUSTOM with widget settings to change a cardinality limit, the name of another ("decorated") field widget type and other settings for the decorated field widget type,
add a number field in the instance settings form and use hook_field_widget_properties_alter to replace $instance['widget']['module'] (keep original in $instance['widget']['_module']) and replace override $instance['widget']['type'] with own FIELD_BEHAVIOR_CUSTOM and save the original in $instance['widget']['_type'], so you can do the same decorator trick in hook_field_widget_form as above.

Modules

Related modules:

Multivalue Extras

  Enhances settings for multiple value fields.


How do I edit the response of successful register.json?

I was never able to get back the raw text password without hacking on the logintoboggan / user modules themselves (similar to what is shown in my question).

However, I solved my same purpose of providing immediate-login-upon-registration for Services/API calls using the services_token_access module. This code only hooks onto a success registration then ads the services_token to the response which is now the only thing my client now needs for validation.

function HOOK_services_request_postprocess_alter($controller, $args, &$result) {

if ( gettype($result) == 'array' && isset($result['uri']) && isset($result['uid'])) { // THIS CONDITION MATCHES THE DEFAULT RESPONSE OF A SUCCESSFUL REGISTRATION.
        $user = (object)$result;
        $user = user_load($user->uid);
        $user = HOOK_services_account_object_alter($user);
        $result = array('token'=>$user->services_token, 'user'=>$user);
    }
    return $result;
}

function HOOK_services_account_object_alter(&$user) {
    $user->services_token = services_token_access_update_token($user->uid, FALSE); // essential for logging in later
    $user->specialstuff = 'whatever else you need';
    return $user;
}

(The services_token_access module is not particularly popular and barely supported, but worked for me.)


How to link a view to a user profile created using views

Hope this will help  you,

As I understand you have 2 views, first view is to list the users and the second view is to show the particular user detail information.

In Drupal 7 you can achieve it easily.

Let say the first view path will be users/listing and the second view path is user/%/other.

Steps

In first view where you are listing all the users, add another field UID and pull it to the top and exclude it.

And go to USER NAME field and uncheck Link this field to its user and goto Rewrite results and check Output this field as a link and enter user/[uid]/other and save it. [uid] is taken form the Replacement patterns

Now its time to create new view which will be showing the user information based on the user id. In this view we need to add the contextual filter, based on that the user detail will be shown.

Add contextual filter


If you want your website to load fast, you need to cache.

Go to Performance (/admin/config/development/performance)

and enable caching and aggregate css and javascript


Adding Google Remarketing Script tags to Drupal 7 website

I think you are looking for the Google Adwords Remarketing module. Here is a quote about it (from the module's project page):

Adds the Google Adwords Remarketing web statistics tracking system to your website.
NB - Google now has another (easier) method for using Remarketing tags. If your Adwords account is linked to your Google Analytics account you can enable the tag by installing the Google Analytics module and ticking a tick box under the Google Analytics Drupal admin page - see attached image.
This tick box causes a slight alteration in the GA tag which is needed by Google Remarketing.


How do I display all available field types?

With the term "field type" you probably don't find what you are looking for. Better search for "form and render elements". You can find a list of all available elements here:

https://api.drupal.org/api/drupal/elements/8.2.x

You can use all elements of the type "FormElement".


How do I set up an action to email all users with a certain role?

I have "Send mail to all users of a role" available when I add an action.

edit rule
click add action
Under system section select "Send mail to all users of a role"
Select role and save


how see left or right sidebar in search result page?

Create one template file: page--search.tpl.php.

Write the following code:

//to print the main content
print render($page['content']);

//to print your right side-bar
print render($page['name_of_the_region_with_right_sidebar']);

and other customization as needed.


How to redirect a user to a personal area of page once logged in?

You can create a View to show the infomation that you need and with the help of the LoginToboggan module you can redirect the users to the view's url.

  The LoginToboggan module offers several modifications of the Drupal
  login system in an external module by offering the following features
  and usability improvements:

  Optionally redirect the user to a specific page when using the
  'immediate login' feature.
  Optionally redirect the user to a specific
  page upon validation of their e-mail address.

For more info about creating Views, you can read:

  Creating new views (Community documentation).
  Creating your first View in Drupal 7.


You want to specify that you searching for nodes first (and optionally by your content type), and then filter by term:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'YOUR_CONTENT_TYPE_HERE')
->fieldCondition('field_game', 'tid', 5);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = entity_load('node', $nids);

How to use EntityFieldQuery


How do I define an external URL in settings.php and call it in a custom module?

Trying using the full path of the class:

\Drupal\Core\Site\Settings::get('external_url')

In Drupal 8, an ideal place for custom variables is in config files. Create a yml file in the config directory and import the configuration.

my_variables.settings.yml

external_url: 'url-string-here'

Then to fetch the values, it's:

\Drupal::config('my_variables.settings')->get('external_url')

https://www.drupal.org/docs/8/converting-drupal-7-modules-to-drupal-8/step-4-convert-drupal-7-variables-to-drupal-8


How to enable Ckeditor for email templates?

I recently had the same issue and was able to accomplish this through a hook_form_FORM_ID_form_alter(); in a custom module.

<?php

function MYMODULE_form_webform_email_edit_form_alter(&$form, &$form_state) {
  // This check will determine whether the form already has a ckeditor textarea on it, if not it will initialize ckeditor requirements.
  if (!function_exists('ckeditor_load_by_field')) {
    module_load_include('inc', 'ckeditor', 'includes/ckeditor.lib');
    $input_formats = ckeditor_profiles_compile();
    drupal_add_js(array('ckeditor' => array('input_formats' => $input_formats, 'plugins' => array())), 'setting');
  }

  // Set some vars.  Modify these as needed.
  $format_key = 'full_html';
  $element = $form['template']['template'];
  $element_id = 'edit-template--2';

  // The format array here is used within the ckeditor_load_by_field() function, without it things won't work.
  $format = array(
    '#options' => array(
      $format_key => $format_key,
    ),
    '#value' => $format_key,
  );

  // Both of the following keys are required for the textarea to become ckeditor-ified
  $element['#wysiwyg'] = TRUE;
  $element['#id'] = $element_id;

  // Run the ckeditor_load_by_field function which does all the magic.  Modify to match the $element var set above.
  $form['template']['template'] = ckeditor_load_by_field($element, $format);
}


Using Rules to create a Comment with multiple fields formatted in the Main Body Text

Step 1: Getting around a known comment body limitation

I think the core of your question relates to what's written in Comment # 10 of the Rules (support) issue titled "Access and Set Comment extra fields ", i.e.:

  ... param_comment_body doesn't assume any data types except 'formatted text' ...

This issue includes a Rule example that looks like so:

{ "rules_test" : {
    "LABEL" : "Comment bot",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "zzz",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : {
                "value" : "This text will be replaced in the next action.",
                "format" : "filtered_html"
              }
            }
          },
          "PROVIDE" : { "entity_created" : { "new_comment" : "New comment" } }
        }
      },
      { "data_set" : {
          "data" : [ "new-comment:comment-body:value" ],
          "value" : [ "node:field-status" ]
        }
      }
   ]
  }
}

The clue to solve your issue (= work around?) is to rework your exported rule (as in revision 1 of your question) so that it uses that last Rules Action starting with "data_set".

Step 2: Combining 3 fields

However, since in your case you want to combine those 3 text area fields, you should also include these extra Rules Actions (prior to that Rules Action starting with "data_set"):

Add a variable (to use as your comment-body later on), say with machine name like variable_for_comment_body.
3 (similar) Rules Actions to Set a data value, for variable [variable-for-comment-body] (added in the prior Rules Action), whereas each of these 3 Rules Actions will refer to the value of each of your 3 text area fields.

For an example rule where you can see this technique at work, refer to my answer to "How to use Rules to send an eMail with a body containing all items of a field collection?" (you don't need a Rules loop though, just those 3 similar Rules Actions.

And with the above logic in place, theh value in your last Rules Action starting with "data_set" simply becomes [ "variable-for-comment-body" ].


View Shows Latest Members - How to Limit Count by Last 3 Months

In your views 'Filter criteria' add another filter and choose 'User: Created date' and choose an operator which suit your needs, An example shown below. It will list users that are created between last 90 days


How to make Toolbar unsticky at the top?

The fixed position is hard-coded into the toolbar.css file included with the core module.

To override it add the following to a CSS file that you're including with the admin theme:

#toolbar {
  position: static !important;
}

body.toolbar, body.toolbar-drawer {
  padding-top: 0 !important;
}

The !important declarations may or not be necessary depending on the order of inclusion...try without it first, and if it doesn't work, try adding it.


How do I import products using commerce_feeds and commerce_autosku?

Seeing this issue, seems that is not currently 100% possible: https://www.drupal.org/node/1662620

Answer from the mainainer in that issue:

  Have you tried unchecking the "Always regenerate SKU's" checkbox for this product type? That should allow your SKU's to be accepted without being overwritten.


How to create a rule to email all users who bookmarked the author of new content?

As i can see in your Actions -  Send mail - To:[site:current-user-mail]. You need to create action Send mail and chose 'Send mail to all users of role` - and chose roles for which you want to send mail.


Popups API - Drupal 6.x-2.0-beta0 - Popup is automatically closing

I have did some analysys and changed the following code its started working

$settings['popups']['originalPath'] = $_GET['q'];

//Replaced with following code

$settings['popups']['originalPath'] = 'popups/test';

There is a function in popups.js which will check the end point of the form. Not sure exactly the cause of the issue.

 return done = (path === Popups.originalSettings.popups.originalPath);


Schedule a mail on the 1st day of the following month

Try "first day of +1 month" as your scheduled date.


They are relations, so firstly you need to create the tags with the taxonomy REST service.

/taxonomy/term

You must take into account they are entities ( node and taxonomy_term ) and the field_tags field only stores the reference to the entity taxonomy_term.

Once you have created it, you will have to add the tags in the following way in your node definition.

Don't forget change the term_id ( in my case 1 ) and the uuid :

{
  "_links": {
    "type": {
      "href": "http://localhost/drupal/rest/type/node/page"
     }
  },
  "title": {"value": "Does it work?"},
  "body": {"value": "node body"},
  "_embedded": {
    "http://localhost/drupal/rest/relation/node/page/field_tags":
      [
        {
          "_links": {
          "self": {
            "href": "http://localhost/drupal/taxonomy/term/1?_format=hal_json"
          },
          "type": {
            "href": "http://localhost/drupal/rest/type/taxonomy_term/tags"
          }
        },
        "uuid": [
          {
            "value": "ff61ea71-2540-47fe-a4bb-384b12d4de47"
          }
        ],
       "lang": "en"
      }
    ]
  }
}

More information in the following link.


Submit handler is not called from theme function

I Updated my theme function like this and now it works like a charm :-)

$output .= drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);


Make sure that the field is visible under 'Manage Display' for the view mode you are working with.

If you setup the field to display in a format you like you can also just do this in your template file (instead of the format_date() part):

<?php print render($content['field_date'] ?>

In any case make sure that you also do the following before $content is rendered:

<?php print hide($content['field_date']) ?>


How to generate custom template for views page

In your view, click on your field, then click on STYLE SETTINGS

Checkmark Customize Field HTML, select DIV.
Give it a class name, Ex: cool
Uncheck Add default classes, that's just extra markup that you don't need.

Then in your theme's .css file add

If your title field is a link put

.cool a{ color: red; }

If your title field is NOT link (you have link this field to the original piece of content unchecked) put

.cool { color: red; }


You could probably do this if you use something like javascript or jQuery and using the tabindex attribute.  Take a look at the below link at Stackoverflow as an example:

https://stackoverflow.com/questions/2894539/how-to-set-tab-order-in-jquery


Unable to login as user in my drupal 6.x website while able to access without login

As you can not login from in your site the only way to do something is from database end, if you have access to database try doing this to come out of this mess up:

Try to empty the sessions and the cache tables. Not DELETE! Empty them.
then see if you can login from http://www.yoursite.com/?q=user

Or look if your site is in maintenance mode if it is the follow instructions given here: https://www.drupal.org/node/276457

Hope above will work for you and you will get your site back to normal.
Good luck!


How to find and delete nodes with duplicate titles?

This Drupal 6 script should do the job for you.


In your form_set_error() call, you haven't set a specific field name on which to set an error. It's possible that without a form_set_error() call identifying a real form element no error is happening.

form_set_error('subject', t('Error!'));

Also, check to make sure your validation function is being called with a drupal_set_message()


Try

$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids) AND ur.rid NOT IN (:rids2)';

$result = db_query($query, array(':rids' => array(7), ':rids2' => array(8)));

Or if you wanted just the more specific version

$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid = (:rids) AND ur.rid != (:rids2)';

$result = db_query($query, array(':rids' => 7, ':rids2' => 8));


How can I get other content type data in current content type?

What you need to do is make X a taxonomy term.

1) Go to taxonomy and create a vocabulary (ex: Colors)

2) Inside Colors vocabulary, add terms. (ex: Red, Blue, Green, Yellow etc..)

3) Go to contentype1 manage fields and add a new field of type: Taxonomy Term Reference. Then select the vocabulary (colors).

4) Now edit your contentype1 nodes and give them a taxonomy term. Ex: Node 1 blue, Node 2 red, Node 3 blue, ...etc

5) Repeat steps 3) and 4) but with contentype2 this time.

6) Create a block view of contenttype2 (You will see it lists all the contentype2 nodes)

7) Under Advanced, add Relationship of Terms of the node, checkmark Colors and checkmark require relationship.

8) Add a contextual filter of Taxonomy Term and for when filter is not available, set it up like this (using screenshot from another answer):

Once you add the contextual filter, your view preview will go blank, which is normal. Go to a contentype1 node, where you placed the view block, and you should see contenttype2 nodes that have the same taxonomy term as the current contentype1 node that you're viewing.


Spam url_alias entries being created - how do I stop them?

Who have access to Administer ➔ Site building ➔ URL aliases depends on how you've set access to the permissions administer url aliases and create url aliases under  Administer ➔ User management ➔ Permissions.  If you've granted access to the Anonymous user role, everybody can do it.  If you've granted access to Authenticated user role, a rogue authenticated user can do it.

First, check out these permissions and make sure they are safe.  Leave them unchecked for all roles. Then, only the super admin (user #1) can create aliases using the GUI.

If these setting are secure, and you still get unwanted url_alias entries created, then some outsider has gained direct access to your database.  That's bad.

Finding the cause of database intrusion is not easy. Possible attack vectors are: A bad module that permits SQL injection, some means outside of Drupal (an inscure phpMyAdmin is the most common cause), or (in particular if you're on shared hosting) a host misconfiguration.

However, without having direct access to your site's and its log for forensics, it is impossible to know how an outsider has gotten into your database (if that is indeed the cause).


How to restrict node access based on user roles?

What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather coarse, and to control access to view a node by role, you must use some sort of node access control module.

There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module to control access based upon roles.

When working with access control, it helps to understand how Drupal access control modules actually work, here is a quick description:

Users granted permission to administer nodes are never restricted by node access control. Users who do not have permission to View published content can never be granted access by a node access module. Only users who have 'access content' and not 'administer nodes' are eligible for the wild world of node access module control.
Node access control in Drupal is as a rule additive. This means that any module doing access control in accordance with the “the Drupal philosophy” should only allow access, not deny it. An administrator who wants to fine tune access to a node must first make sure nobody has access, and then add access grants to anyone that shall have access.

This means that it may be rather cumbersome to restrict access to individual with a module like Content Access, since you must start by denying everyone access, and then add it back to those nodes you don't want restricted.  However, I think it is the best option if you really need to do it node by node. Its primary resolution is content types, but it allows you to override this for single nodes.

Unfortunately, you shall not be able to use Deny access since it only works on content types, with no override for individual nodes.

NB: Using more than one node access module is not recommended.

Note that if you can change your requirements so that you can use content type as your basic unit for node access control, then Deny access would be ideal.   For instance, if you have a role "student" and you want to deny access to nodes with answers, then you can create a content type "Answer" (which can just be a clone of the default "Article") and Deny access will take care of protecting all nodes of the type "Answer" from being viewed by the role "student".


How do I get translated label for a base field definition?

There are two possible translation methods for a base field, interface translation and configuration translation.

Base fields are defined in code and translated by t(), which gets the translatable string from the core interface translation table.

$translatableMarkup = t($label, [], ["langcode" => $langcode]);
//optionally, render to string
$translatedLabel = $translatableMarkup->render();

If a base field override exists in configuration, then it contains a translatable label:

// Override language before loading field configuration.
$language = \Drupal::languageManager()->getLanguage('fr');
\Drupal::languageManager()->setConfigOverrideLanguage($language);

$field_override = BaseFieldOverride::loadByName('entity_type', 'bundle', 'myField');
if ($field_override) {
  $label = $field_override->getLabel();
}


hook_update_n($sandbox) batch getting executed only once

There is no need for batches if you intend to run all entries in one process.

This is something we had use to update around 30.000 entries i quickly adapted from your example :

/**
 * Query all commerce_product of type default
 *
 * *
 * @param array $sandbox
 *
 * @return string
 *  Number of updated rows
 */
function mymodule_post_update_0801(array $sandbox) {
  /** @var $connection Drupal\Core\Database\Connection */
  $connection = \Drupal::service('database');
  $query = $connection->select('commerce_product', 'p');
  $query->fields('p', ['id'])
    ->condition('type', 'default');
  $toUpdate = $query->execute()->fetchAll();

  $result = array_map( 'update_description_value', $toUpdate);

  return sprintf('Number of row updated: %s', count($result));
}

/**
 * Update a product description
 *
 * @param stdClass $defaultProduct
 *  ->id
 *
 * @return string
 *  product id
 */
function update_description_value($productQueried) {
  /** @var $connection Drupal\Core\Database\Connection */
  $connection = \Drupal::service('database');

  $updated = $connection->update('commerce_product')
    ->fields(['field_meta_tags' => serialize(['description' => ''])])
    ->condition('id', $productQueried->id, '=')
    ->execute();

  return $productQueried->id;
}

Let me know if there is typo somewhere.


You can create a multiple-value field collection field.

In the "field collection item" entity type, you can create the fields for the image and body text.

Afaik, the built-in image field type does not really work with external images. This problem is discussed here: Linking image field to an external URL

And now for the output.

Under "manage display" of the field collection item, use Display suite, with ds_extras enabled. Choose "Reset" as the layout (which will disable all divs that wrap the field collection item). Then create a ds custom field using token, and use it to put the other fields into your custom html.

Or alternatively, override field-collection-item.tpl.php in your theme, or better, override field-collection-item--field-xyz.tpl.php. I am not sure which exact template suffix to use to target the specific field collection item type. You should play around a bit and then we can update the answer based on your findings.


In your case i would use the EVA Field module in combination with Display Suite module.

The EVA field module provides an extra views display plugin (EVA Field Display) that allows you to attach a view dynamically to a node, user, term etc.

The Display Suite module works great with EVA and helps you by letting place the attached view any where you want within the node display layout.

Create a content view and add an EVA Field display. In the Entity Content Settings of this display select:

Node for Entity type
Content type A for Bundles
Leave Arguments as it is (id)

Then:

Add a relationship for the entity reference field you have on content type B referring to A
Add the fields you want from content type B.
Add filter for content type = content type B
Add a contextual filter Content nid with the relationship of the entity reference!
Go to query settings and check the Distinct setting.

Now what will happen is that for every node of type A an EVA field view display will be attached showing the corresponding fields of node type B. Using Display Suite you can place this attached view any where you want in the node layout.

Hope this helps.


How to add a placeholder to a form element using a twig template override

Altering forms in Drupal 8 is the same as in Drupal 7 - you have:

hook_form_alter()

  Perform alterations before a form is rendered.

hook_form_FORM_ID_alter()

  Provide a form-specific alteration instead of the global hook_form_alter().

Always use an alter/preprocess hook to change variables before they get to the template file, it's bad practice to change them once you're in the template file itself.


How to I trigger Xdebug 3.x with Drush in PHPStorm

I am guessing that you have changed your xdebug.ini according to the new standards. (Port changed from 9000 to 9003 etc...)
If not you should do that first.
Check this link for additional information on the matter.
Besides that considering that you are using phpstorm, you should simply run
export XDEBUG_SESSION=PHPSTORM

before running the drush command. This must be done once every time you open a new terminal session. (Not sure if there is a way to have it permanently and if there is i am not sure you want it.) Nevertheless, if your configurations are ok, this should work.
Best Regards.


Navigation buttons move around in responsive design

To resolve the problem I used @media queries to distinguish a different setting per responsive size. So I copied and deleted line 58 (.flex-direction-nav a) from the flexslider.css. I then added this code below at the bottom for the CSS file. *This is also good as you can control the nav in all variations of size. for instance in the mobile @media below I dropped the buttons down (removed top: 50%; from mobile) some to help users see the flexslider on a small screen better.

/* LANDSCAPE PHONE TO DOWN MOBILECSS */
@media all and (max-width: 480px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LANDSCAPE PHONE TO PORTRAIT TABLET MOBILECSS */
@media all and (max-width: 759px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LANDSCAPE DESKTOP TO DOWN 720CSS */
@media all and (min-width: 481px) (max-width: 760px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* PORTRAIT TABLET TO LANDSCAPE AND DESKTOP 720CSS */
@media all and (min-width: 761px) and (max-width: 980px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LAGACY DESKTOPS 960CSS */
@media all and (min-width: 981px) and (max-width: 1289px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%; z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}


As kantu's comment suggests, there is no formal "approval" system for modules on drupal.org.  Instead, module maintainers decide when to release their modules and what version number to assign them.

As pageflip is a highly specialized module, I doubt that there is another module that has similar functionality (a quick search returned none).  However, since it is beta 5, it is probably stable enough to use in production, as Countzero pointed out.  The alternative would be to write a module yourself, but since the pageflip module is already far along in its development it would probably be best for everyone if you would extend and contribute back to the pageflip module (assuming you were going to write your own module).

How do you really know whether the module is ready for production?  First, look at the list of open reported bugs.  In this case there are only 3 for the 6.x series, so it shouldn't take you very long.  If these bugs don't affect you, the module is probably safe to install.


Using Feeds module to import to User_Reference fields?

Did you try patch from this thread?

The patch is http://drupal.org/files/userreference-mapper-748582_0.patch.


Problem in deploying Drupal 8 application

The error indicates that Drupal is failing at boot(). Check if your DB connection settings in settings.php that is located in the sites/default directory points to your new database.


When are '$form_state['values'] copied to '$form' on rebuild?

Nothing like "??? old user input from $form_state is copied to every $element[#value]" happens. Simply $form_state['input'] is kept so that when the form is built the values are filled in based on that.


How can users write a bio on their profile page?

Re: the second/existing option, if you have a custom module already, could do a form_alter() on the node form to remove the title field.  Or, you could look into the auto_nodetitle module that does this for you:

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

  Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.

If instead you wanted to stay/go back to the first option, you could create a menu link/path like user/%/edit/bio that presents the user_profile_form that has been form_alter()ed to show only the bio field based upon the fact that it was called from this new path.


How to resolve error with drupal commerce 2 installation via composer

This turned out to be a problem of running composer through Acquia Dev Desktop's terminal launcher.

When using native terminal the installation completes without issue.


How to check if a user has any previous order?

Try this method. commerce_order_load_multiple will return order

function module_user_has_order() {
    $order = commerce_order_load_multiple(array(), array('uid' => 'user_id','status' => 'completed'));
  if(empty($order)) {
    //user has no previous order.
  }
  else {
    // user has previous order.
  }
}

Hope it works for you.


How to delete the bulk of custom data when the associated user is deleted

One approach would be to add a deleted column to your messages table, and mark the messages for deletion when a user is deleted, e.g.

function statuses_user_delete($account) {
  db_update('statuses_message')
    ->fields(array('deleted' => 1))
    ->condition('uid', $account->uid)
    ->execute();
}

Forgive the obviously incorrect table name, I'm not familiar with the statuses module.

Then in a cron hook, you could grab x number of the messages marked for deletion, and process them:

function statuses_cron() {
  $max = 50;
  $sql = 'SELECT message_id FROM {statuses_message} WHERE deleted = 1';
  $message_ids = db_query_range($sql, 0, $max)->fetchCol();

  statuses_delete_message_multiple($message_ids);
}

I'm making some assumptions about how things are set up in your module, but hopefully the principal is obvious enough. You could one step further and implement hook_cron_queue_info(), which will give you a finer grained control over the amount of time your worker can run for. I think some profiling with both methods would probably be appropriate to determine which which is better.

This is along the same lines as the logic the core field module uses to purge deleted data on the cron run, so I think it's safe to assume the principal at least is well tested...it's just whether this method will work for your use case.

I guess the only sticking point here would be the amount of code you need to change in the rest of the module to respect the new deleted column (i.e. not showing deleted messages to users). Again I can't really comment on that as I'm not familiar with the module, but if you take a methodical approach to implementing changes I can't imagine it being that much of a problem.


How do I map active directory group membership (ldap authorization) to og groups in open atrium?

I had this same problem recently whereby this was originally working:

GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

During this course of development this stopped working and on alternate logins a user in that LDAP group would either be a member of the organic group, or not (but never an administrator of that group).

I eventually worked out that it had stopped working because I had since overridden the permissions of the space, which meant that the OG role ids were different, even though they had the same name.

Therefore:

GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

was being automatically converted to

GroupA|IT:member (raw: node:3:5)
GroupA_Admins|IT:member (raw: node:3:5)
GroupA_Admins|IT:administrator member (raw: node:3:6)

when actually since it was no longer using the default roles, it should have been using 8 and 9 instead of 6 and 7.

Rewriting the mapping to explicitly use the ids for the overriding roles rather than their names worked:

GroupA|node:3:8
GroupA_Admins|node:3:8
GroupA_Admins|node:3:9

I know this is a very old post to reply to, but I was struggling with this yesterday so hope it helps someone else in future.


Using hook_mail_alter() for pending approval admin does not make any effect

The emails are being sent because in admin/config/people/accounts the option Visitors, but administrator approval is required is selected for Who can register an account.

If you selected Visitors or Administrator only no email would be sent.

In the case you wanted to just avoid emails where sent to the administrators, but still wanted the administrator users to approve accounts, then the implementation of hook_mail_alter() should look for messages whose ID ($message['id']) is equal to user_register_pending_approval_admin_. Also, the example in the documentation of hooks don't show the correct name a hook implemented by a module should have: Always replace hook_ with the short name of the module implementing the hook.


How to get rendered content properties from an entity reference in Twig

In PHP you could force to build the render array of the field of a referenced entity early:

$build = $node->reference->entity->field_stock_photo->view();

And then look for '#uri' in the build array.


Only require comment approval when an image is attached

I got this working using the Mollom module.

In Mollom's configuration, you can enable spam filtering and set up your own blacklist terms for the spam filter. I created blacklist terms for <img and "media-image" (TinyMCE's encoded image class). Then I told Mollom to "Retain the post for manual moderation" if it gets detected as spam.


Locale module by default provides you a block, Language Switcher, that switches language of the site. It's a list of installed language.

If you like a fancy switcher, you can install this module:
Language Switcher Dropdown

  Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.

  The module also integrates well with Language Icons module if
  installed.

Here's an example


Yes, the solution is not available yet in core, see https://www.drupal.org/node/2245767.
But you can use this contrib module https://www.drupal.org/project/block_in_page_not_found and negate the condition to not show the block on a 404 page:


Apache AddDefaultCharset utf-8 - filename not saving in utf-8

According detailed explanation at https://bugs.php.net/bug.php?id=47096 temporary solution would be, explicitly converting filename encoding using iconv().Now it raising new warning message(shall I have to open another issue thread for this?)

Warning: filesize() [function.filesize]: stat failed for public://noëlle_châtelet12.jpg in file_save() (line 566 of C:\server\www\drup_dlist_mys\includes\file.inc)

temporary solution until it is fixed in php move_uploaded_file() function.
In file.inc I added the line in drupal_move_uploaded_file function block

+$uri= iconv("UTF-8","ISO-8859-1//TRANSLIT", $uri);
$result = @move_uploaded_file($filename, $uri);
// PHP's move_uploaded_file() does not properly support streams if safe_mode
// or open_basedir are enabled so if the move failed, try finding a real path
// and retry the move operation.
.
.

This is only happening in WAMP and working fine in linux. I don't know how this new iconv statement will affect in unix/linux environment.Can it be possible to check whether the current locale supports for utf-8 just before iconv() statement?.


Video embed field doesn't honor the autoplay settings

Use the following code to change autoplay to 1 in your template or Javascript file. It works for me.

jQuery('.video-embed-field-launch-modal').attr('data-video-embed-field-modal', function(i, oldSrc) {
  var isAutoPlay = oldSrc.match(/autoplay=([^&]*)/);
  if (isAutoPlay && isAutoPlay[1] == 0) {
    return oldSrc.replace('autoplay=0', 'autoplay=1');
  }
});


Hide "Submit"/"Save" button until file has finished uploading

Havent tried this, but you might be able to use jquery's global ajax event handlers, to hide the submit button, in particular the .ajaxStart() and .ajaxComplete() handlers. Something like the following, added in a .js file in a custom module (not tested):

(function ($) {
  Drupal.behaviors.YOURMODULE = {
   attach: function (context) {
     $(document).ajaxStart(function(e){
       $('#edit-submit').hide();
     });
     $(docment).ajaxComplete(function(e){
       $('#edit-submit').show();
     });
   }
  };
})(jQuery);

You'd have to edit that to work the way you need it to, save it in a js file, and add it to the node edit form (or any other form you need it for).

Aside from that, the "ajax HTTP request terminated abnormally" errors occur in D7 whenever a http request is made before an ajax request has completed. In my opinion this is undesirable behaviour. It's been discussed here, for example, and the prevent js alerts module suppresses such errors across your site.


Which nid to use for translated node in a menu

In Drupal 7 you can use Locale core module to translate.

Locale : Adds language handling functionality and enables the translation of the user interface to languages other than English

After enabling the Locale module , add German language using admin/config/regional/language.

Use English words to create menus.
After creating the menus use admin/config/regional/translate/translate link to translate English string to German.

Search for the string. I'm using About Us to translate. Click the corresponding edit link to translate.

Enter German string


Stop caching for a specific node (by nid) Drupal 7

A module with the below in it should stop caching on node 2. Change the number to do it on a different node id.

function MYMODULE_init(){
  if (arg(0) == 'node' && arg(1) == 2) {
    drupal_page_is_cacheable(FALSE);
  }
}


Relation between User field and current user

You'd need to add a relationship in views to your custom field you created and then provide a default value of "User ID from logged in user"


Elysia cron and feeds being stuck - how to resume the imports?

I have discovered that the following lines had been wiped out from the code somehow in my module:

 while (FEEDS_BATCH_COMPLETE != $source->import()){
// nothing
 } // while

This piece of code keeps de feeds working after it finishes. When the resetting is done via phpMyAdmin, the cron itself (called every minute) launches again the tasks. The Elysia task when being called, but the callback did not do anything as the feed had started and the code lacked the while() construction


Using Workbench Moderation state changes as events

We are using Workbench Email to accomplish this on our D8 site, would this work for you?


How to hide nodes in a VIEW where the user is not referenced?

You have to add a filter under Filter Criteria Section which is, if a 'yourfield-name'is 'is not empty (NOT NULL)' from the select list.

This filter only shows results which have the value for this particular field. Otherwise it will not show you any result for that node.

I hope it will work.


How to increase weight range avaliable when using Tabledrag?

If you are using a field of type "weight" like in the examples module you need to use the #delta attribute.


How to make Username as non mandatory on Drupal 7 registration form?

Yes it's possible, there are couple of modules out there that will auto-generate the username and just require an email address on the registration form (and there are probably a few more as well)

Email registration

  Allow users to register and login using only an email address. Users can then log-in using their email address and password for authentication.

  A username is generated and assigned based on the user name part of the email address. Subsequent users who have the same name (email prefix) are numbered sequentially. For example, "johndoe@a.example.com" would be assigned username "johndoe", "johndoe@b.example.com" would be assigned "johndoe_1" and so forth. Sites that want to create usernames in their own way can do so by implementing hook_email_registration_name.

Login Toboggan

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

  Allow users to login using either their username OR their e-mail address.

Out of those two Email Registration is a bit more lightweight, so if you don't need the features from LoginToboggan it would make more sense to use that one.


Views is an awesome query builder and formatter - all through the UI. In my past coding days I did that all manually and recently I started to appreciate the power of views.

Just go into views settings / basic and turn on "Show the SQL query". Then create a basic view of nodes. Now add fields and filters to see how the SQL changes. Add a relationship and you'll see how views adds the "SQL Joins" automatically.

When you add some "fields" it will automatically add some joins without you having to add relationships. For example add "last comment author" field to a node and views will automatically add:

INNER JOIN {node_comment_statistics} ...
LEFT JOIN {users} ....

When you want to add some fields that you don't see in the selection, for example "author of the node", you add the relationship "Content: Author - Relate content to the user who created it."
Views adds the SQL:

INNER JOIN {users} ....

Now you'll have the user related fields available, for example "(author) User: Picture (Picture)".

So in summary: most views will pull data from multiple tables but most of that detail is hidden from the developers because views does it all for you. If you understand tables and SQL turn on the SQL output and see what views does. Sometimes all those "joins" are not optimal from an optimization standpoint ;-)


Creating node in installation profile but body field stays empty

I know this old, but I just came across it.  It's really difficult to know what's going on without being able to look at all of the code, but my guess would be you are trying to use 'format' => 'filtered_html' before you've define it in the .install.  In the distributions I help to maintain, we always call filter_format_save as one of the first items of business...

http://cgit.drupalcode.org/cm_starterkit_easy/tree/cm_starterkit_easy.install#n14