Trying to use hierarchical select in exposed view filter - dont get the option I have activated the Hierarchical select taxonomy views module, but when I add an exposed filter on my taxonomy term, I dont get an option to use the hierarchical select as a widget as the documentation says I should.

Use Simple Hierachical Select module instead which works

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy.


Add a conditional CSS class to the label of the view exposed form I try to add a CSS class sr-only to the label of my Views exposed form.

In form-element-label.html.twig I added:

{% if title is not empty or required -%}
  {{ title }}
  {% elseif title['#markup'] == "Search" %}
    {{ title }}
{%- endif %}

When I debug {{ kint(title) }} I get:

What I'm doing wrong?

I don't think you need to check for "required" here, just check if the field is not empty, right?

You are first checking if a field is not empty so in the elseif the title will always be empty. You should have two ifs I for your logic to work I believe.

If not empty, do this: if it has this particular value do this otherwise do that.


How to make a webform block specific template? i would to make a custom tpl for a webform in a block.I get is ID but actually i can't it to works.what the way to do this ? what si the folder / files structure to do this ?
i'm on drupal 6 and webform 3.x

thanks

EDIT: this my code for node-webform.tpl

<div class="node<?php if ($sticky) { print " sticky"; } ?><?php if (!$status) { print " node-unpublished"; } ?>">

     <?php if ($title): /*insertion du titre de la page et style differencié*/?>

<?php print $title; ?>

    <?php endif; ?>

    <?php  print $node->field_image_deco_lycee[0]['view'] /*Image deco page lycee*/ ?>

     <?php if ($submitted) { ?>
    <?php print $submitted?>
  <?php }; ?>

    <?php print $node->content['body']['#value']; ?>

    <?php print $node->content['webform']['#value']; ?>

    <?php if ($links): ?>

 <?php print $links; ?>

  <?php endif; ?>

     <?php if ($terms) { ?>
    <?php print $terms?>
  <?php }; ?>

     <?php print $picture; ?>

           <?php if ($node->field_vue_actus_lycee[0]['view']): ?>

           <?php  print $node->field_vue_actus_lycee[0]['view'] /*Vue actus du lycée*/ ?>

           <?php endif;?>

    <?php if ($terms): ?>

<?php //print $terms; ?>

    <?php endif;?>

  <?php if ($picture) { print $picture; }?>

  <?php if ($page == 0) { ?>
    <?php if ($title) { ?>

<a href="<?php print $node_url?>"><?php print $title?>

    <?php }; ?>
  <?php }; ?>

You need to copy (not move) sites/all/modules/webform/templates/webform-form.tpl.php to sites/all/themes/yourTheme/templates/webform-form-nid.tpl.php (obviously replace yourTheme and nid) and clear caches.


Add Library to Footer If I am using the Libraries API module to add a javascript library in my module, is it possible to have the library load in the footer instead of the header?

If not is there an alternative method?

Instead of running the libraries_load() function:

$library = libraries_load('easyzoom');

I just used the libraries_get_path() function to get the path and attached to the element and added scope of footer.

$easyzoom_library_path = libraries_get_path('easyzoom');

$element['#attached']['js'] = array(
  $easyzoom_library_path . '/dist/easyzoom.js' => array('scope' => 'footer'),
);


How to create file field instance that allow teaser and full description and not allowed extensions but denied extensions? I need to change the default Drupal functionality of file field:

I want to be able to allow upload of all files types, EXCEPT the extensions listed (reversing the current funcitonality)
I also want to be able to add a teaser field and a description field to the file.

Any ideas?

The second part of your question is easy with the File Entity module - it turns file uploads into fieldable entities, so adding your teaser/description field is just like adding a field anywhere else in Drupal (make you sure you read the README file - it's not overly clear at first).  The module is also on an unstable release, but Dave Reid is pretty damn awesome so I can't imagine it'll be that way for long :-)

Off the top of my head, I can't think of an answer to the first part though I'm afraid.

EDIT

There's an issue here that has a couple of patches for Core that give you a radio box to either Allow only these file types or Allow everything EXCEPT these file types.  I've not tested the patches as I don't really want to patch Core for something that I personally don't need, but definitely give it a read!


How to create product template? Please see the red box. In Magento there is a feature where i can create Product Templates - templates can be created for products with different fields.

I know i can create Content Types for this, but i felt that will make too many Content Types. Is there another work around this so that it's like Magento? Is there a module for it.

Thanks!

In Drupal Commerce you can just make product types and it will generate product displays (content types) meant for building the presentation. The product type holds all the meta data about the product itself.


Sensitive data on configuration managment How can I prevent some sensitive data (e.g. password for the SMTP module) from getting into my repo as part of the Configuration Management system?

From page 17 of the Drupal PCI Compliance Guide:

  Removing credentials from settings.php. One can include a settings.local.php file within settings.php to ensure that sensitive information is not distributed.

This is good advice and is what most people do.

If you have a lot of information you want to store securely, looking at the Encrypt module or even a Lockr integration might be advisable.


Why does d7_user_role need a db connection configured when migration group already defines it I've just done a super basic user_role import and I'm trying to do a user import. Both are in the same migration group and the migration group has a souce key to specify which database listed in settings.php to use.

I can migrate and roll back the user_role import fine, but as soon as I try to import the users, I get "Migration mysite_user did not meet the requirements. No database connection configured for source plugin d7_user_role"

migrate_plus.migration_group.basic_migration.yml

uuid: 512c4248-7f60-4b08-9cc2-8d804657262c
langcode: en
status: true
dependencies: {  }
id: basic_migration
label: basic_migration
description: 'basic migrations'
source_type: 'Drupal 7'
module: null
shared_configuration:
  source:
    key: legacy

migrate_plus.migration.mysite_role.yml

uuid: 6e288181-f2fd-4e22-885e-02282cc4d222
langcode: en
status: true
dependencies: {  }
id: mysite_role
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Configuration
migration_group: basic_migration
label: 'Mysite Role'
source:
  plugin: d7_user_role
process:
  id:
    -
      plugin: machine_name
      source: name
    -
      plugin: user_update_8002
  label: name
  permissions:
    -
      plugin: static_map
      source: permissions
      bypass: true
      map:
        'use PHP for block visibility': 'use PHP for settings'
        'administer site-wide contact form': 'administer contact forms'
        'post comments without approval': 'skip comment approval'
        'edit own blog entries': 'edit own blog content'
        'edit any blog entry': 'edit any blog content'
        'delete own blog entries': 'delete own blog content'
        'delete any blog entry': 'delete any blog content'
        'create forum topics': 'create forum content'
        'delete any forum topic': 'delete any forum content'
        'delete own forum topics': 'delete own forum content'
        'edit any forum topic': 'edit any forum content'
        'edit own forum topics': 'edit own forum content'
    -
      plugin: flatten
  weight: weight
destination:
  plugin: 'entity:user_role'
migration_dependencies: null

migrate_plus.migration.mysite_user.yml

uuid: bd0ef271-9c8f-40d7-9b65-8147e4cdda47
langcode: en
status: true
dependencies: {  }
id: mysite_user
class: Drupal\user\Plugin\migrate\User
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Content
migration_group: basic_migration
label: 'Mysite User'
source:
  plugin: d7_user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  timezone: timezone
  langcode:
    plugin: user_langcode
    source: language
    fallback_to_site_default: false
  preferred_langcode:
    plugin: user_langcode
    source: language
    fallback_to_site_default: true
  preferred_admin_langcode:
    plugin: user_langcode
    source: language
    fallback_to_site_default: true
  init: init
  roles:
    plugin: migration_lookup
    migration: d7_user_role
    source: roles
  user_picture:
    -
      plugin: default_value
      source: picture
      default_value: null
    -
      plugin: migration_lookup
      migration: d7_file
destination:
  plugin: 'entity:user'
migration_dependencies:
  required:
    - d7_user_role
    - mysite_role
  optional:
    - d7_field_instance
    - d7_file
    - language
    - default_language
    - user_picture_field_instance
    - user_picture_entity_display
    - user_picture_entity_form_display

Any pointers where to start looking would be much appreciated.

The section of migrate_plus.migration.mysite_user.yml that reads this:

roles:
      plugin: migration_lookup
      migration: d7_user_role
      source: roles

has to be edited by switching "d7_user_role" for the id of your user role migration, which in your case is "mysite_role"

roles:
      plugin: migration_lookup
      migration: mysite_role
      source: roles


Set a date field by rules I have a problem that has been discussed a lot, but I still fail at dealing with it.
I need to get and set the the value of the field by Rules. I put my conditions allright, then I define "Set a data value" as a desired action. At this point, the direct input is disabled, I can only point to another field (as far as I can understand): "switch to direct input mode" is disabled (does not appear, in fact).
Now,I've seen a number of discussions related to the issue. It seems to be related to the way the Date module handles things.

The issue seems widely discussed:
Date module:
https://drupal.org/node/1431952 (Date field will only set in Rules if it already has a value)
https://drupal.org/node/1153766 (provide a property setter callback)
Rules Module:
https://drupal.org/node/1611666 (Action "Set a data value" is not working for   date field)

There are also more general guides
Drupal 7, Rules, Convert text to date and set a date field (as setting the date supposedly works for timestamps)

While most of the problems seem solved, I can't achieve the simple (I assumed)  goal I want to get to. Can anybody explain how to connect the pieces of information and make it work as intended?

The patch from
https://drupal.org/comment/8195767#comment-8195767
seems to solve the problem.


How can I programmatically display a block? I'm developing a site using Drupal 8 beta-14. I've created a view block of different terms and now I want to display it using code. How can I display it programatically?
I used to do it in Drupal 7 using this code but I'm confused about Drupal 8.

$block = module_invoke('block', 'block_view', '4');
$text_block = render($block['content']);

There are two types of blocks, and the method for rendering the two is a bit different:
Content Blocks
Content blocks are blocks that you create in the interface. They are much like nodes configurable data structures, with fields etc. If you want to render one of these, you can do what you would normally do with entities, load them and render them with the view builder:
$bid = ??? // Get the block id through config, SQL or some other means
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->
  getViewBuilder('block_content')->view($block);
return $render;

Plugin blocks
Blocks can also be plugin, defined in various modules. An example could be the breadcrumb block. If you want to render these, you will need to use the block plugin manager.
$block_manager = \Drupal::service('plugin.manager.block');
// You can hard code configuration or you load from settings.
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// Some blocks might implement access check.
$access_result = $plugin_block->access(\Drupal::currentUser());
// Return empty render array if user doesn't have access.
// $access_result can be boolean or an AccessResult class
if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
  // You might need to add some cache tags/contexts.
  return [];
}
$render = $plugin_block->build();
// In some cases, you need to add the cache tags/context depending on
// the block implemention. As it's possible to add the cache tags and
// contexts in the render method and in ::getCacheTags and
// ::getCacheContexts methods.
return $render;

Config entities
Shared for the two types are blocks, are that once you insert them into a region, you will create a config entity that has all of the settings for the block. In some cases it will be more useful handling config entities. Since the same block can be place in multiple regions with and with different configuration, it can get more tricky using the block config entities. The nice thing is that you might want to render a block with specific configuration, the bad thing is that config ids can change by messing with the interface, so the code might end up not working after letting users use the block interface.
$block = \Drupal\block\Entity\Block::load('config.id');
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);
return $render;


How to create revision for a node programmatically I have node and i need to create revisions for that node programmatically . When i tried as follows :

$node = Node::create([
                'nid' => $nid, //my desired node id for the revision
                'type' => $bundle_type,
                'field1' => value1,
                'field2' => value2,
]);

$node->revision = TRUE;
$node->save();
$node->setPublished(true);
$nid = $node->id();
print 'Created revision for node' . $nid;

Its not working , instead its creating new nodes . Any solution for this ?

// Make this change a new revision
  $node->setNewRevision(TRUE);
  $node->revision_log = 'Created revision for node' . $nid;
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setRevisionUserId($user_id);
  $node->save();

Use Above Code to create a revision. :)


Post method trow an Preflight not successful response Im working with Drupal 8 and Angular.

I want to create a content from angular.

I have the Get method working.

The problem is with the Post method, I don't know how to configure it.

With the Rest Ui module, i have this configuration:

And in the services.yml file I have this one:

  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: []
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: []
    # Configure requests allowed from specific origins.
    allowedOrigins: ['*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: false
    # Sets the Access-Control-Max-Age header.
    maxAge: false
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: false

It works fine for the Get method, but for the POST, it gives me this error:

  XMLHttpRequest cannot load http://drupal.dd:8083/entity/node.
  Preflight response is not successful task.service.ts:92

The task.service.ts is from my Angular app.

Questions:

1) Is the problem from Drupal configuration or from angular? (if is from angular, i will move the post. )

2)Wich on is the correct way to configure Post Method in Drupal?

Extra info from the method

This is the right cors.config configuration:

 cors.config:
        enabled: true
        # Specify allowed headers, like 'x-allowed-header'.
        allowedHeaders: ['*']
        # Specify allowed request methods, specify ['*'] to allow all possible ones.
        allowedMethods: ['*']
        # Configure requests allowed from specific origins.
        allowedOrigins: ['*']


Do i need write access to the files directory to migrate d7_file? I'm migrating a site from drupal 7 to 8.  It has many many media files.  Something like 6TB worth.  And adding daily.  So i want to do the db migration on my machine (not the webserver), work out kinks and modify custom code to work w/ d8, then do the real thing on the live machine over a slow weekend when i have all the steps worked out.
In the migration process, i've gotten to drush migrate-upgrade d7_node, and it (on initial run, with only a token few files in /sites/default/files) created a handful of db entries in file_managed.  So i sshfs mounted the live files directory read only from my machine and re-ran migrate-upgrade d7_node from the restored db.  Now it doesn't create anything in the file_managed table, so i suspect it's not working, but it gives no errors, and some grepping doesn't readily yield the code that does this work.  I wouldn't mind hacking for this part only.
Hence the question.  And what can i do alternatively to avoid copying 6TB of files for the preparatory migration?
Thanks.

Ok, i figured this one out.  The magic lines are in /core/modules/migrate/src/Plugin/migrate/process/FileCopy.php
First, make sure source_base_path is correct in your config: Check drush mmsg d7_file after migrate-upgrade d7_node --limit=1 to see whether it is correctly finding the files.  Use drush config:export and config:import to modify it til that works.  Alter settings.php to put config/sync somewhere other than /sites/default/files
Second, mount the live site's public files dir read-only at /sites/default/files.
Third, modify /core/modules/migrate/src/Plugin/migrate/process/FileCopy.php around line 149 to comment out the action.  Make it look like this:
    if (!is_dir($dir) || !is_writable($dir)) {
      if (!$this->fileSystem->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
        throw new MigrateException("Could not create or write to directory '$dir'");
      }
    }

    $final_destination = $this->writeFile($source, $destination, $this->configuration['file_exists']);
    if ($final_destination) {
      return $final_destination;
    }
*/
      return $destination;```

Last, run drush migrate-upgrade d7_file

Enjoy.


How do I make entity reference lookup faster I am trying to look up entity reference id's for each node so I can do stuff with them.

$all_nodes = db_select('node','e')->fields('e',array('nid','type'));
$all_nodes->addField('e','nid');
$all_nodes->condition('type','author');
$data = $all_nodes->execute();
$the_result = $data->fetchAll(\PDO::FETCH_ASSOC);

foreach ($the_result as $node){
     $node_load =  \Drupal\node\Entity\Node::load($node['nid']);
     foreach ($node_load->field_institution_with_date as $item) {
        $the_entity_id = $item->entity->id();
     }
}

Any idea on how to optimize this? it seems that $item->entity->id(); is the bottleneck and it is taking several seconds to iterate through about 1000 nodes.

Ideally you'd use an Entity Query for this, but in principle:

You can batch load the parent nodes

...
$nids = $data->fetchCol();

foreach (Node::loadMultiple($nids) as $node) {

If memory is a concern with thousands of nodes, just implement some simple php logic around the loop to batch it into, say, 50-100 at a time.
If you don't need the child entities, just their IDs, they're available without a DB hit

foreach ($node_load->field_institution_with_date as $item) {
    $the_entity_id = $item->target_id;

If you do need the entities, you could build an array of all IDs using this method, and batch load those using Node::loadMultiple after the outer loop.


How to add background images to blocks? How to upload background images to blocks individually ?

Is there any contributed modules available uploading background images to blocks?

Try the Background Images Formatter module

This module provides an image formatter who allows you to set an image in background of a div.
The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.

This can be done using Views. Create a block, select the "Background Image" formatter for your image field, save, place the block, boom, you're done.


Remove content translation links from contact form I'm having a difficult time diagnosing a problem on a site I'm working on. By default on a multilingual site Drupal puts "content translation links" at the bottom of nodes. I've disabled the content translation links in favor of the language switcher block. However, on the contact form from the contact module I still have what look like content translation links at the bottom of the form (see screenshot below).

In the screenshot the translation links that I don't want are labeled #1 and the language switcher block is labeled #2.

I've selected "hide content translation links" under /admin/settings/language/i18n , but I guess this doesn't apply to the contact form for some reason.

So far I've been able to deduce that these links are getting passed through the $content variable because when I remove print $content from page.tpl.php, the links (as well as the contact form itself, of course) disappear. It also seems that the links are being treated as part of the contact form itself; when I tried using the panels site contact page override, whenever I added the contact form widget the links were included.

I apologize if this is perhaps too "localized" (pardon the unintentional pun) a question, but any help with figuring out how to get rid of these content translation links from the contact form page would be greatly appreciated. On the one hand I highly doubt this is the expected default behavior, so I feel like I must have tripped a setting or missed a setting somewhere. But at the same time I've looked through pretty much everything I can think of, so I'm at a loss.

If you want to hide that button, you can use the CSS Injector module, create a CSS class to apply to that data, and set display:none !important. It's not necessary to use a Drupal hook.


How to I retrieve default checkbox values using Form API? How do I retrieve saved checkbox values from a field using the FormAPI?

The form/node saves successfully, and when I look in the DB, the data was successively saved in the 'field_data_field_test' table, but I can't figure out how to pull that back out and apply the 'checked' status using #default_value.

$form['field_test']['und']['#default_value'] = $How_Can_I_Get_This_Data_From_DB

Is there a function I can use to retrieve checked values for a given field within a given node?  I'm trying to avoid direct queries. :)

Edit:

Ended up using

function _get_review_site_defaults() {
    $query = new EntityFieldQuery;
    global $user;
    $result = $query
            ->entityCondition('entity_type', 'node', '=')
            ->entityCondition('bundle', 'field_test', '=')
            ->propertyCondition('uid', $user->uid, '=')
            ->propertyCondition('status', 1)
            ->execute();
    if (count($result) == 0) {
        $defaults = array(1);
    } else {
        $entities = entity_load('node', array_keys($result['node']));
        foreach ($entities as $key => $value) {
            if ($value->field_default_field_test[$value->language][0]['value'] == 'Yes') {
                $defaults[] = $value->nid;
            }
        }
    }
    return $defaults;
}

after you save it, it saves the value of the checkbox as #value (not #default_value).

When defining the field settings:
(pulled from D7 cck_table.module)

  $form['css_class'] = array(
    '#type' => 'textfield',
    '#title' => t('CSS Class'),
    '#description' => t('Specify a class to be added to the table element.'),
    **'#default_value' => isset($field['css_class']) ? $field['css_class'] : '',**
  );

Revised:

More likely you would want to do this:

If you want to grab the default values, you can call `field_info_field($field_name

  Returns data about an individual field, given a field name.


How to create Scald Atoms media library for each content type? I need to categorize the "Atoms Library" items in a way that there would be a "Atoms Library" for each content type. How  could create a Atoms Library for each conten type? or How I could categorize the items in "Atoms Library" according to content type?

Is this possible to create a "Atoms Library" for each content type?

There are two Views that come with Scald:

scald_library - Which, for our purposes, is what controls the format of the menu in the editor.
scald_atoms - Which controls the format of the Scald Library at /admin/content/atoms.

Both are fully editable views.

For the admin page, clone the View and assign each one a unique filter for Atom:Type and give each View a unique path URL. Add these URLs to an admin menu somewhere to make them findable.

The editing menu is a little more complicated. Cloning and filtering the View is the same, but I believe using them would require adding new functionality to either the editor or Scald. Though people editing content can still filter by type in the Scald search pane.


how to add the "add content" to menu drupal I want to add my "Add Content" --> Products " into my menu bar for a menu link. How can I achieve this? Thanks. I want to add this for ease of access.

Navigate to 'Add Content" page from admin menu & copy the path after $base_url.

Example - If it looks like "http://example.com/node/add/product" then copy "node/add/product".

Go to your menu and add one more menu item with the Menu link title of your choice & put this node/add/product in Path over there. All the user will have access to this menu item who ever have permission for adding content of this particular content type.


Why does the files directory ignore system wide umask? I have a Debian test system running Nginx and PHP-FPM, and have set a system wide umask of 027 which translates to default permissions of U=RWX G=RX O= for directors and U=RWX G=R O= for new folders and files, respectively.

After running the Drupal installer and reviewing directory structure, I notice that the installer generated files directory has default permissions of U=RWX G=RWX O=RX.  Any files uploaded to this directory also receive similar permissions.  Why is this so?  Is it hard coded into the software to provide such permissions?

It would seem that if any new folders of files created in the files directory will receive hard coded permissions, that you would need to regularly update those permissions to something of your choosing.

Yes, if Drupal has permission to write to your doc root then it will certainly create the files folder on your behalf during installation, and attempt to set sensible permissions on it (775 seems perfectly reasonable to me considering the web server itself is creating the folder). This all happens in the /includes/install.inc file.

If your server is secured correctly, though, this should not be able to happen. The web server user should not be able to write to the doc root, only to the public/private filesystems. So you would create the files folder manually, and whatever permissions you decide to grant become part of that process.

See Securing file permissions and ownership for a full set of instructions on properly securing a Drupal site.


Displaying title of an empty view I would like to display the title (and the field titles) of  a view even when the view is empty. By default, if a view is empty its title and fields are hidden. How can I force displaying title and fields on an empty view?

I am using views in a panel if that makes a difference.

Quick and dirty way: make a view that displays just one row, take the source html, edit relevant part of it so that it looks the way you would like to printed when there are no results, ie remove field contents and leave only field titles. Copy and paste that html to No results behaviour -> Global text area.

The view title should always be displayed, right?


drupal_render radios missing name attribute When rendering form type radios using drupal_get_form, each one of the radio's options can be exclusively selected, as the html name attribute is set to the parent's ('radios') id.

However I'm working on an ajax form module that integrates with mailchimp, and renders these form elements individually in isolation using drupal_render so they can be placed in a template.

My code to render radios is as follows:

$form_child = array (
  '#title' => 'Some Radios',
  '#weight' => '6',
  '#required' => false,
  '#default_value' => '',
  '#type' => 'radios',
  '#options' => array (
    'Option 1' => 'Option 1',
    'Option 2' => 'Option 2',
    'Option 3' => 'Option 3',
  ),
); // This is generated in my module

$form_child = form_process_radios($form_child);

$myhtml = drupal_render($form_child);

And here is what happens on my form:
HTML output

In the browser

the function of the form_process_radios as given by the documentation is as follows

  Expands a radios element into individual radio elements.

So the out put you are getting is correct as per the documentation.

So in your case you dont need to call the form_process_radios. You can directly call the drupal_render function.


What is the difference between KPR() and DSM() I am learning advanced theming for which I am using Devel Module kpr() and dsm() functions to print the arrays on the page for finding variables. So I want to know, What is the main difference between kpr() and dsm() functions? And which one is the best for which condition.

In Devel there are various formatters you can use to dump variables. But the main difference of dsm() is, that it uses drupal_set_message(), which displays the output in the message array via a session, so that the information is preserved between different requests of the same user. This is helpful for debugging code, which doesn't result in a html page to display a normal var dump, for example a form submit. The disadvantage is, that dsm() sometimes produces the output asynchron, not when you expect it, which can lead to false conclusions.


Selectively applying image style to a class On a page that displays pictures that have two different classes, how to I apply an image style to one class and not to the other?

Or, how do I apply different image styles to images that have different classes?

Thanks. :)

Image styles and HTML classes on images are completely unrelated, so you would have to do some sort of manual hack to achieve this. A very basic effort might be to use hook_preprocess_image_style like so:

function MYTHEME_preprocess_image_style(&$vars) {
  if (array_search('some-class', $vars['attributes']['class']) !== FALSE) {
    $vars['style_name'] = 'some_style';
  }
  elseif ($another_condition) {
    $vars['style_name'] = 'some_other_style';
  }
}


Drupal views filter exposed with condition fields I have a page about buying/selling the car, on the views I have filter with by exposed function. My expected is, when I select the first category, the hidden sub level 1 category should be visible then the User can select level 1 category, we continue show the level 2. Then we make the filter with this filter.

For ex.

All Categories
Used Cars for Sale
Motorcycles
Boats

[Selected [Used Cars for Sale]:

Acura
Honda
Toyota
Huynhdai...]

[Selected [Motorcycles]

Cruiser/Chopper
Off-Road/Dual Purpose
Sport Bike]

Select All Categories with Used Cars for Sale, 1 should show and 2 show invisible, select Motorcycles 1 should invisible and 2 should visible, and so on.

Click Filter, it should filter the current views.

It should be customize with the text, the range slide, the checkboxs... So what is the best modules or best way that I can do with the Views module?

Looking for somebody help me the solution

Kind regards,
John

If you have planed to use just one vocabulary and you have designed it properly , then Hierarchical Select Module can help you to provide the functionality you expect.


Get default image directory with styles large? My images are saved in folder

sites/all/default/files/styles/large/public/field/image

But to make this future save i dont want to hardwire the path? Is there a drupal function to get the images in a proper way?
I played around with

image_style_url(uri)

But i just need the default dir to pass it to javascript, I dont have image uris yet...

Thanks a lot!

I'm not sure this will get you exactly what you want, but the 'default' path is just public://, so.

$url = image_style_url('large', 'public://');

will return

http://yoursite.com/sites/default/files/styles/large/public

I think it's more likely you're looking for a specific path, e.g.

$url = image_style_url('large', 'public://field/image');

which returns

http://yoursite.com/sites/default/files/styles/large/public/field/image


Remove main menu title from page Hi i'm just starting out with Drupal, Have what I think is a really simple question and it has been asked a lot but the answer dont work for me.

I am using the Stark theme to start to buid a theme. I am trying to remove the main menu text from above the menu, please see

I have tried How to remove "Main Menu" title from Stark Theme but this does not work, infact if I remove the block from admin/structure/blocks the menu still shows.

Does any one know how I can fix this?

Thanks.

For blocks, Title fields is optional so it is not required to enter. However
Description field is mandatory to enter but it displays in the admin side listing only.

So you can keep title blank or use <none> as Patrick mentioned in his comment.


How to load a node based on current language? I have 2 content bundles for node entity:

Custom Layout Pages (custom_layout)
Recipes (recipe)

Then I created two content using those content types, Potato (recipe) and Homepage (custom_layout).

I have 2 languages for both content, en and fr. I'm trying to load the potato recipe node inside of the homepage content.

So inside the preprocess hook, I have this code

...
if(isset($vars['node']) && $vars['node']->type === 'custom_layout'){
    $recipe_id = 10;
    $vars['recipe_side'] = render(node_view(node_load($recipe_id)));
}
...

Then I echo the $recipe_side in the custom_layout template file.

When I load the fr version of the page, I expected the recipe to be loaded in fr as well, but it always displays the en version.

I'm guessing it's because the en recipe node id is 10, and it doesn't load the translated node.

If that's the case, how can I make it work so that the loaded node follows the current language?

Try this code:

 $node_trad = node_load($variables["node"]->nid); // in your case, 10.
 $idi_trad = translation_node_get_translations($node_trad->tnid);

  $vars['recipe_side'] = render(node_view(node_load($idi_trad["fr"]->nid)));
  //$vars['recipe_side'] = render(node_view(node_load($idi_trad[$language->language]->nid)));
  // alternative, more dynamical

Essentialy you load the node in original language, use the translation function to get all available translations, and use that what you need.
Instead of "fr" you could use language->language instead to make it completely dynamical.


csrfToken: reget without logout user I have a site where I use AngularJS to connect to Services module paths.

Now, we know that I need to send (for every put connection) the CSRF token into headers request, and this token is linked to user's session id.

My problem is that some users are currently logged into the system for Drupal (I can see all content for authenticated users ) but when I send a PUT request, Drupal return me the error of invalid CSRF token.

So, how can I retrieve a new CSRF token without logout the user ?

M.

To get the CSRF Token, do a GET on:

?q=services/session/token

Please note that 'services', is not the path to your endpoint, its a built in path provided by the Services module.

After grabbing the token, you then pass the token along in the header for any POST, PUT, and DELETE requests from authenticated users:

X-CSRF-Token=abcdefg123456789

jDrupal may be of use in this scenario as well, it's a JavaScript API for the Drupal Services module


Where to put formatting I am building a custom module to grab data from an XML feed, however some of the data comes in badly formatted and I would like to change some of it around (for example put line breaks after certain words). Where would be the most Drupaly place to put the code that does this? In the module's .inc file? Preprocess it in template.php? Or put it in a field template file?

I would add the necessary reformatting of the badly formatted XML to the input processing of the custom module (the one you're writing).

If that is not an option (e.g. if the client insists that the XML feed is saved verbatim), then I would create a custom filter for this content.  Drupal filters do not change the input - it only changes the presentation.


Any ways to create count column like mysql "COUNT(*) as counted" Column with d7's db_select()? hello everybody i have to make tableselect form with some extra fields. To make table sortable I have to show which DB fields is used for the column in header:

$header = array(
    'uid' => array('data' => t('UID'), 'field' => 'u.uid'),
    'name' => array('data' => t('Name'), 'field' => 'u.name'),
    'mail'=>array('data' => t('Mail'), 'field' => 'u.mail'),
    'last_access' => array('data' => t('Last Access'), 'field' => 'u.access'),
    'login_count' => array('data' => t('Login Count'),'field'=>'a.count_logins'),
    'join_date'=>array('data' => t('Join Date'), ),
    'post_count'=>array('data' => t('Posts Count'),),
    'comment_count'=> array('data' => t('Comment Count'),)
  );

then I created a query for this:

$query = db_select('users','u');
  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query->leftJoin(db_select('mycustom_report','r')->fields('r',array('count(*)    AS  count_logins','uid'))->groupBy('uid'),'a','a.uid=u.uid');
  $uids = $query
    ->fields('u',array('uid','name','mail','access'))->fields('a',array('count_logins'))->where('u.uid!=0')
    ->limit(50)
    ->orderByHeader($header)
    ->execute()
    ->fetchAll();

this query gives me this error

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r.countAScount_logins'

any ways to create count field with db_select method in drupal? db_query() seems does not support ->orderByHeader() method

my full query which works fine looks like:

select u.uid,u.created,u.name,u.mail,u.access,counted_login,counted_post,counted_comment
  from users as u
          left join (select r.uid, count(*) as counted_login  from mycustom_report as r group by r.uid ) as d on u.uid = d.uid
          left join (select r.uid, count(*) as counted_post from node as r group by r.uid ) as p on p.uid = u.uid
          left join (select r.uid, count(*) as counted_comment from comment as r group by r.uid ) as c on c.uid = u.uid;

This error simply means that column does not exist in your database which means u have to write addExpression() method for solving these problem as follows and even you have not joined the table properly use your query as below

$query = db_select('users','u');
$query = $query->extend('PagerDefault')->extend('TableSort');
$query->leftJoin('mycustom_report','r','r.uid=u.uid');
$query->fields('r');
$query->fields('u');
$query->addExpression('COUNT(uid)', 'uid_count');
$result = $query->execute()->fetchAll();

this will surely removes your error the main issue with your query is that you are combining the db_query syntax with db_select


Redirect after login through different login form I try redirect user to specific tab on user profile page. I found couple solution how I can do that but it doesn't work if I use login form modules like Super Login, Bootstrap login form, fancy login, etc. When I try redirect user via trigger It give me AJAX error.

Then I try use Rules module and it doesn't redirect after login at all. All of it works fine if I login through standard login form.

I spent 2 days for this issue and can't find any solution. Please give me right way how to do that.

I use Bootstrap login module

link to my tab: user/[account:uid]/mytab

This is my rule:

    { "rules_red" : {
"LABEL" : "redirect",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_login" : [] },
"DO" : [ { "redirect" : { "url" : "user\/[account:uid]\/mytab" } } ]
 }
}

I found out how to solve this issue. I install popup module and activate popup block submodule. then go to block  and set "User login" block in "Navigation" region (I use bootstrap theme), after that open configuration of "User login" module and do it popup. I hope it  will usefull for anybody.


Auto Increment - Order/user numbers not changing I've executed the following via phpmyAdmin but nether the order nor user numbers change.

ALTER TABLE 'users' AUTO_INCREMENT = 1025;
ALTER TABLE 'commerce_order' AUTO_INCREMENT = 1025;

I checked inside 'commerce_order' and the AUTO INCREMENT is set to: 1025(order numbers should change).
When i check inside the 'users' table, AUTO INCREMENT is NOT available(why?).

I've cleared the cache.
Shouldn't this be working?
Drupal7

Thank you for your help!

The users table does not work with AUTO INCREMENT in Drupal 7.
Instead, the ids are generated in PHP.

See What could cause uids to not be numbered consecutively?


File (Field) Paths get year only I've recently found and started using the File Fields Path module in Drupal 7 and I have a date field that I'm only collecting the year from.  Using that in the file path part of the module, it returns the value as YYYY-MM-DD-HHMMSS.

So a value of 2017 shows up as 2017-01-01-000000 since I didn't collect any of the other information.

Is there a way to just get it to make the folder as 2017 instead of the whole date?

Thanks for any help!

You should be able to go to the manage fields area for that field - something like admin/structure/types/manage/article/fields/field_field_path

and for the "file path" setting, enter [current-date:custom:Y].

This is untested, but should work. Get back to me if it doesn't.


How can I disable a user that should still be visible on the site? It seems that User name on blocked user account not visible in view for anonymous users is basically the same question I'm asking, but it doesn't have an accepted answer or one that works for me.  This is a different take on the question than the one I'm making.

I am migrating a site from another CMS.  I am bringing over staff members, both past and current as users of the site.  As part of the migration, users who are no longer with the organization are being marked as blocked to prevent them from logging into the site.

These users are then associated with nodes on the site via various entity reference fields.  The problem I run into is that for anonymous users, indeed for anyone that doesn't have bypass access controls on their account, these user accounts are not visible.

What is the proper way to keep an account visible, while not allowing users to log-in to it?  For me, the answer will need to be something that will work with the Migrate Module.

Obviously blocking the user seemed like the obvious way to do it for me, but I can't find any permission that will allow access to blocked user info.  Is there another way of doing this, or is there a way of making blocked account info visible?

My Solution

Based on the accepted answer from @kiamlaluno, I created a solution that works for me:

I already have an end_date field for each user (field_user_end_date), so most of the time, that would suffice as a limiting factor for the login, but based on discussions with the stakeholders, I added an additional admin only boolean field named field_user_account_locked.

I implement hook_form_alter to add my validation function to the form:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
        $form['#validate'][] = 'mymodule_user_login_validate';
    }
}

And here is my validation module:

function mymodule_user_login_validate($form, &$form_state)
{
    if (!empty($form_state['uid'])) {
        // The user trying to login is not limited by flood control;
        // user_login_authenticate_validate() found a user with the username and password entered in the login form.
        $user = user_load($form_state['uid']);
        $end_date = (isset($user->field_user_end_date[LANGUAGE_NONE][0]['value'])) ? strtotime($user->field_user_end_date[LANGUAGE_NONE][0]['value']) : time() + 300000;
        if ($end_date < time() || $user->field_user_account_locked[LANGUAGE_NONE][0]['value'] == 1) {
            form_set_error('name', t('The username %name cannot be used to login.', array('%name' => $form_state['values']['name'])));
        }
    }
}

I'd love some constructive criticism on it, if you have some.

Using a custom module, you could change the permission to see user profiles. For example, the following code could be used for Drupal 7.

function mymodule_permission() {
  return array(
    'access blocked user profiles' => array(
      'title' => t('View user profiles of blocked users'),
    ),
  );
}

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user'])) {
    $items['user/%user']['access callback'] = 'mymodule_view_access';
  }
}

function mymodule_view_access($account) {
  $uid = is_object($account) ? $account->uid : (int) $account;

  // Never allow access to view the anonymous user account.
  if ($uid) {
    // Admins can view all, users can view own profiles at all times.
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
      return TRUE;
    }
    elseif (user_access('access user profiles')) {
      // At this point, load the complete account object.
      if (!is_object($account)) {
        $account = user_load($uid);
      }
      if (is_object($account)) {
        // If the account is blocked, show the profile to users with the right
        // permission.
        return ($account->status ? TRUE : user_access('access blocked user profiles'));
      }
    }
  }
  return FALSE;
}

Give the new permission to anonymous users, and they will be able to see the user profile of blocked users.

This is probably easier than changing password and email, and it's easier to revert if you block by mistake a current employee: Just unblock the account.

The code I shown works for a direct access to the user profile, and for modules that only verify the user has the access user profile permission to show the link to a user profile. This is what Drupal does, for example in template_preprocess_username().

  $variables['profile_access'] = user_access('access user profiles');
  $variables['link_attributes'] = array();
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
    $variables['link_attributes'] = array('title' => t('View user profile.'));
    $variables['link_path'] = 'user/' . $variables['uid'];
  }
  elseif (!empty($account->homepage)) {
    // Like the 'class' attribute, the 'rel' attribute can hold a
    // space-separated set of values, so initialize it as an array to make it
    // easier for other preprocess functions to append to it.
    $variables['link_attributes'] = array('rel' => array('nofollow'));
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
  }

Any module using theme('username') (for which template_preprocess_username is a preprocess function) to show the user name will print the link to the user profile, even if the shown user account is blocked, if the currently logged-in user has the access user profile permission.

If there are modules that check the user account is blocked before showing a link to the user profile, then this method will not work.

In this case, the alternative I would adopt is the following:

Don't block the user accounts for those ex employees
Add a flag to the user accounts that says if an account can be used to log in
Using an extra validation handler for the login form, return an error if one of those accounts is used to log in

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['#validate'][] = 'mymodule_user_login_validate';
  }
  elseif ($form_id == 'user_register_form') {
    $form['account']['can_login'] = array(
      '#type' => 'checkbox',
      '#title' => t('The user account can be used to log in'),
      // The form is for registering a new user; there is nothing to load from the database.
      '#default_value' => TRUE,
      // See user_register_form() which set the following value to TRUE if
      // the currently logged-in user administer users.
      '#access' => $form['administer_users']['#value'],
    );
    $form['#submit'][] = 'mymodule_register_submit';
  }
  elseif ($form_id == 'user_profile_form') {
    if ($form['#user_category'] == 'account') {
      $form['account']['can_login'] = array(
        '#type' => 'checkbox',
        '#title' => t('The user account can be used to log in'),
        '#default_value' => mymodule_load_flag($form['#user']->uid),
        '#access' => user_access('administer users'),
      );
      $form['#submit'][] = 'mymodule_profile_submit';
    }
  }
}

function mymodule_user_login_validate($form, &$form_state) {
  if (!empty($form_state['uid'])) {
    // The user trying to login is not limited by flood control;
    // user_login_authenticate_validate() found a user with the username and password entered in the login form.
    if (!mymodule_load_flag($form_state['uid'])) {
      form_set_error('name', t('The username %name cannot be used to login.', array('%name' => $form_state['values']['name'])));
    }
  }
}

function mymodule_register_submit($form, &$form_state) {
  if ($form_state['values']['administer_users']) {
    // The user submitting the form can administer users.
    // user_register_submit() sets $form_state['values']['uid']; save it in
    // a database table the module creates when installed.
    mymodule_save_flag($form_state['values']['uid'], $form_state['values']['can_login']);
  }
}

function mymodule_profile_submit($form, &$form_state) {
  if (user_access('administer users') && $form['#user_category'] == 'account') {
    // user_profile_submit() sets $form_state['values']['uid']; save it in
    // a database table the module creates when installed.
    mymodule_save_flag($form_state['values']['uid'], $form_state['values']['can_login']);
  }
}


View ignores unchecked "require this relationship" I am building a view in Drupal 8 that calls for two relationships:

Nodes referenced by the current node (relationship required)
A single node referenced by the above reference node (relationship not required)

Although that second relationship isn't required, my view is still filtering out all nodes where that second relationship is null. Is anyone else having this problem?

I was able to solve this by changing which field I wanted from the reference node. I was originally trying to get the path, but I switched it to "Link to Content." Still, it's odd that when trying to get just the path, views suddenly requires the relationship.


How to return a user's group access permissions? I am trying to block a user from accessing certain content/blocks if they do not have permission to view content of a certain type within a group.

I have the user ID and the group ID, but how do I check the user's permissions for that group? I can't find any documentation.

To start, how would I print all the permissions for a given user and group?

The Group class has a userHasPermission() method you can use. So something like this:

if ($group->userHasPermission($user->uid, 'some permission')) {
  // do something.
}


Using Configuration API in drupal 8 I altered node_type_edit_form and added a section to get some settings like below:

Now I need to save the configurations and build the default value based on last selection using Configuration API .

The problem is it needs to build the fields selected (checkbox) in every content type form.

I believe that you have machine name of content type while altering node_type_edit_form. So I assume that $node_type is the variable in which machine name can be accessible.

So as stated in drupal list changes, variable_get and variable_set is replaced by config system in drupal 8.

To save a configuration you need to add this code in your submit function :

\Drupal::configFactory()->getEditable('modulename.settings')
    ->set('checkboxsetting_' . $node_type, $form_state->getValues()['checkboxsettings'])
    ->set('radiosettings' . $node_type, $form_state->getValues()['radiosettings'])
    ->save();

and to get the saved values you need to :

\Drupal::config('modulename.settings')->get('checkboxsetting_' . $node_type);

To set the default configuration from yml file. Create a yml file and content will be :

modulename/config/install/modulename.settings.yml

checkboxsetting_page: whatever
checkboxsetting_article: whatever
radio_page: whatever
radio_article: whatever


Embedding content in a panel ctools plugin- any other options instead of using views, on some occasions, I want to write custom code to display a list of content. I know how to create ctools content type plugins, and in here I could create my EntityFieldQuery to display my content and allow it to be embedded. I was wondering if there are any other options for making my custom code available for embedding in a panel other than creating a ctools content type plugin as mentioned. Ctools content type plugin feel a little  verbose for for the task...

I definitely understand your problem with a ctools pane feeling verbose.

Unfortunately I don't have a great fix. I tend to copy an old content type to a new one and edit names and such.

What you make not know is that the normal single => TRUE property of a content type can be switched to FALSE allowing the code to create multiple panes in a single content type. (Actually I think FALSE is the default, so you don't even need to).

This allows you to share a lot more code between several panes that act similarly.

Another, simpler but more limited option is Fieldable panels panes, which basically allows you to take an entity, put fields on it, and stick it directly into a variant. If your needs are simply to display simple content, that could be enough, but this isn't enough when more complex logic is needed.

Actually a pane that requires a EntityFieldQuery context as an argument and then basically just themes it would be very interesting. There's probably use for at least a sandbox that provided the context and content type for that. :)

I'll try to write up more details if necessary, but look at plugins/content_types/custom/custom.inc for an example of a content type that does the above.

Someone may also have taken the time to write a drush command to generate a content type from a template. Haven't looked around for one though.


Cloning / Copying value of multi-value field I do not wanna create another wheel but could not find a solution yet.

I have multi-value field (which I implemented myself) and I would like to have possibility to add 'new item' with already predefined values.

What would you recommend to do?

I googled and did not find anything suitable for me and considering to create my own module for this.

Consider using Entity References and not a complex compound field like your using now.

By using references you can use either the Inline Entity Form or the References Dialog modules to provide a more streamlined UI for adding new events from new popup windows. I was hoping you could reference exisitng events through a search using these modules (you can) but it won't clone the reference directly.

BUT, you could use the Replicate module, to replicated the entity reference you've selected to then edit it -- using custom code.

An example way to replicate a referenced entity can be seen in this replicate issue, as shown below:

/**
 * Replicate entities that are the target of entityreference fields
 *
 * Implements hook_replicate_field_FIELD_TYPE
 *
 * For entites that have one or more entity reference fields we need to replicate the
 * referenced entities as well so the cloned parents don't all point to the same children.
 * We also need to update the entityreference fields to point to them.
 *
 * @param object $replica
 *   Reference to the fully loaded entity object being saved (the clone) that
 *   can be altered as needed.
 * @param string $entity_type
 *   Type of the entity containing the field.
 * @param string $field_name
 *   Name of the field that is going to be processed.
 *
 * @see replicate_clone_entity()
 */

function MY_MODULE_replicate_field_entityreference(&$replica, $entity_type, $field_name) {

  // Only replicate entity reference field you are interested in
  if ($field_name == 'field_MY_ENTITYREFERENCE_FIELD') {

    // Wrap the replicated entity.
    $wrapper = entity_metadata_wrapper($entity_type, $replica);

    // Loop over the field values
    foreach ($wrapper->$field_name as $delta => $referenced_field_item_wrapper) {
      $referenced_entity = $referenced_field_item_wrapper->value();

      // Replicate the referenced entity and get the new id
      $replicated_referenced_entity_id = replicate_entity('node', $referenced_entity);

      // Give the replica reference field the new target id
      $replica->{$field_name}[LANGUAGE_NONE][$delta]['target_id'] = $replicated_referenced_entity_id;
    }
  }
}

So I'm saying Replicate and 1 of the many "dialog" modules could help make what you want to create more pretty. You could probably use the Replicate API and a custom button in your own form too -- if you want to do even more learning ... :)


Ajax processed not added on link element I am stuck on a case where I am trying to ajaxify a link, following the tutorial placed here http://clikfocus.com/blog/simple-ajax-example-drupal-6-and-7.

The problem is that the .ajax-processed is not added to the link.

Can you suggest any common pitfalls here?

The weirdest part is that some of the other modules is blocking the functionality. Could it depend on the setting of the view that prints this element?

In order to have the AJAX event assigned (and the ajax-processed class added) to a link you need two things:

use-ajax class on the anchor tag
AJAX library loaded

I'm guessing you're missing item #2, and that can be done in a few different ways:

If you're generating a renderable array, use #attached:

$my_data['#attached']['library'] = array(
  array('system', 'drupal.ajax')
);
Or you could run this PHP pretty much anywhere prior to the page being rendered:

drupal_add_library('system', 'drupal.ajax');


How do I jump to a specific place on a page? I wish to be able to jump to a specific place on a given page.

I have inserted  into the text of the page, and set the link to the page to be "about_us/customers/#placetojumpto."

If I type the URL in the address bar it works fine, but when I try use the link generated by Drupal, it converts the "#" to "%2523," so the link becomes "about_us/customers/%2523placetojumpto" and then fails.

The problem is that you have the #, called fragment, in the path, Drupal escapes it for you, and what you need to do is tell Drupal specifically that you want a fragment in the url.

Example:

l('linktext', 'node/1', array('fragment' => 'placetojumpto'));

Documentation here: http://api.drupal.org/api/drupal/includes--common.inc/function/l/7


Entityqueue - Handler drop down is empty after installation I have just installed the Entityqueue module on my drupal 7x site. However, when I go to the /admin/structure/entityqueue/add page, the Handler dopwn down is empty and therefore the form will not validate so I cannot create a new list.

I've checked the \modules\entityqueue\plugins\entityqueue\handler folder and the simple handler is present along with it's class file.

Help!

I uninstalled the module but it was still appearing in the Modules list and I could not re-install it for this reason. However when I re-enabled it and saved, the Simple Handler appeared in the drop down. Good grief.


Form API image preview I've read many discussions about image preview in fapi with 'managed_file', but I can't find a conclusive answer on how to do this properly in D8.

An obvious solution would be to reuse Drupal\image\Plugin\Field\FieldWidget\ImageWidget, but I don't know how to accomplish this.

So my question is: how can I have an image upload field with image preview in my form in D8 and what would the associative array in my buildForm function look like?

After searching for a while, I have found some kind of workaround solution for this here: https://stackoverflow.com/a/38268567/2267244

I have tested it and it works, here is bit modified version which I have used.

Also I'm not sure if we should mark this question as dpulicate as I found the solution on stackoverflow.com.

Anyway Here is how your form field should looke like:

$form['image_with_preview'] = [
  '#type' => 'managed_file',
  '#title' => t('Image with preview'),
  '#upload_validators' => [
    'file_validate_extensions' => ['gif png jpg jpeg'],
    'file_validate_size' => [25600000],
  ],
  '#theme' => 'image_widget',
  '#preview_image_style' => 'medium',
  '#upload_location' => 'public://',
  '#required' => FALSE,
];

And also you will need to implement hook_preprocess_HOOK in your module like this:

function YOUR_MODULE_preprocess_image_widget(&$variables) {
    $element = $variables['element'];

    $variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));

    if (!empty($element['fids']['#value'])) {
      $file = reset($element['#files']);
      $element['file_' . $file->id()]['filename']['#suffix'] = ' (' . format_size($file->getSize()) . ') ';
      $file_variables = array(
        'style_name' => $element['#preview_image_style'],
        'uri' => $file->getFileUri(),
      );

      // Determine image dimensions.
      if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
        $file_variables['width'] = $element['#value']['width'];
        $file_variables['height'] = $element['#value']['height'];
      } else {
        $image = \Drupal::service('image.factory')->get($file->getFileUri());
        if ($image->isValid()) {
          $file_variables['width'] = $image->getWidth();
          $file_variables['height'] = $image->getHeight();
        }
        else {
          $file_variables['width'] = $file_variables['height'] = NULL;
        }
      }

      $element['preview'] = array(
        '#weight' => -10,
        '#theme' => 'image_style',
        '#width' => $file_variables['width'],
        '#height' => $file_variables['height'],
        '#style_name' => $file_variables['style_name'],
        '#uri' => $file_variables['uri'],
      );

      // Store the dimensions in the form so the file doesn't have to be
      // accessed again. This is important for remote files.
      $element['width'] = array(
        '#type' => 'hidden',
        '#value' => $file_variables['width'],
      );
      $element['height'] = array(
        '#type' => 'hidden',
        '#value' => $file_variables['height'],
      );
    }

    $variables['data'] = array();
    foreach (\Drupal\Core\Render\Element::children($element) as $child) {
      $variables['data'][$child] = $element[$child];
    }
}

I have tested it on my local Drupal instance and it works fine, image preview was displayed after AJAX upload finished.


moving a drupal website to another server I've been working on a drupal website in a server for months but after moving it to another server and url some of the files are not read. for example it seems that it does not read colors.css or all of the image files used in the site.

for more clarification I must add that there is a joomla site on www.example.com then I've put my drupal site on  www.example.com/test this is the site which does not work properly.

and before that it had been working on www.something.com/test/test1.

I don't have a clue why it has happend! help

check the sites/default/settings.php for $base_url

it might have been set for a sub-directory install, and may still reflect the original server location.

if it wasn't set originally, setting it now may help as well.


ADD MORE option in form element I am working with WEBFORM module, and I provided only one text area for the user to enter his choice but I want a "ADD MORE" button in my form element so that my user can enter his second choice also. I want to know what I can do to achieve described action?

Not possible at the moment with Webform, but hey, do you really need a webform module to achieve what you need?

You could create a custom content type with any fields set you can imagine (single and multiple) and give users permission to create nodes of this type. So this way you'd be able to gather form submissions as separate nodes.


How to display the field in a joined table with hook_views_data() I am trying to figure out how to display a field in a joined table, but documentation isn't that great or obvious.

I have my base custom table with a tid field that ties to the taxonomy_term_data table.  I want to display the term name, based upon my tid field.  How to I specify that name field for display in my view?

You'll need to add a relationship to that table, then add the field from that table to your view.


Node Form Not submitting on ctool modal I have a custom form, on submission of which I am calling ctools modal with a node form(content type: turn).

Code for Custom Form.

function _my_module_name_files_listing_form($form, &$form_state) {
  $form = array();
  $form_state['storage']['values'] = $files;
  $form['download_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Download'),
    '#submit' => array('_my_module_name_files_download_submit'),
  );
  $form['create_segment'] = array(
    '#type' => 'submit',
    '#value' => t('Create Segment'),
    '#attributes' => array('class' => array('ctools-use-modal')),
    '#ajax' => array(
      'callback' => '_my_module_name_files_create_segment',
    ),
  );
  $form['upload_content'] = array(
    '#type' => 'submit',
    '#value' => t('Upload Content'),
    '#submit' => array('_my_module_name_files_upload_content'),
  );
  $form['delete_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#submit' => array('_my_module_name_files_delete_submit'),
  );
  return $form;
}

Callback code for ajax submission rendering node form.

function _my_module_name_files_create_segment($form, &$form_state) {
  global $user;
  $form_id = 'turn_node_form';
  ctools_include('node.pages', 'node', '');
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  ctools_add_js('ajax-responder');
  $destination = 'node/1';
  $form_state = array(
    'ajax' => TRUE,
    'title' => t('Form Title'),
  );
  $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'turn',
        'language' => LANGUAGE_NONE,
        'status' => TRUE,
  );

  $form_state['build_info']['args'] = array($node);
  $output = ctools_modal_form_wrapper($form_id, $form_state);
  if (!empty($form_state['ajax_commands'])) {
    $output = $form_state['ajax_commands'];
  }
  if (!empty($form_state['executed'])) {
    $output = array();
    // Redirect to destination.
    $output[] = ctools_ajax_command_redirect('node/8', 0);
  }
  print ajax_render($output);
  drupal_exit();
}

Problem:
Node Form is coming fine on modal and hitting save button triggers ajax call but node form does not submit. Am I missing something here?

Try replacing

ctools_include('node.pages', 'node', '');

with

ctools_form_include_file($form_state, drupal_get_path('module', 'node') . '/node.pages.inc');

It's possible that the node.pages.inc file isn't loaded if the form is found from cached data.


How to access $vars['some'] variables in html.tpl.php template In the template.php, I am using the following code for mytheme_preprocess_page().

 // Return nid for node of type "interface_configuraitons".
    $nid_config = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->fields('n', array('type'))
        ->condition('n.type', 'interface_configuraitons')
        ->execute()
        ->fetchCol();
    //load the configurations
    $configurationNode = node_load($nid_config);
    $interfaceConfig = array();
    $interfaceConfig['driver_url'] = $configurationNode->field_driver_url['und'][0]['value'];
    $interfaceConfig['driver_port'] = $configurationNode->field_driver_port['und'][0]['value'];
    $vars['interfaceConfig'] = $interfaceConfig;

While $interfaceConfig is initialized and available in any of the page templates, it is NULL in the html.tpl.php template. I was trying to run mytheme_preprocess_html() without success.

How do I get this preprocessing take place, so it is available in the html.tpl.php template file?

The general rule for any THEMEHOOK.tpl.php file (where THEMEHOOK is something like 'html', 'page', 'node' etc.) is:

The default variables are set in template_preprocess_THEMEHOOK() (eg.
template_preprocess_html)
Any module can add variables using MODULENAME_preprocess_THEMEHOOK() (eg. toolbar_preprocess_html)
The active theme can add variables using THEMENAME_preprocess_THEMEHOOK() (eg. bartik_preprocess_html)

The $variables array (sometimes called $vars) is passed on from function to function in the above order, so each function can expand on or overwrite the variables added before.


how to add multiple style values in attribute in drupal form I have form element like as follows :

$form['precio'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#default_value' => $precio,
  '#size' => 20,
  '#attributes' => array(
    'style'=>'background: none repeat scroll 0 0 #EAEAEA;'
  ),
  '#description' => t('Change the price'),
);

how i add more style attributes to 'precio' ?

You can nest the style attributes as follows :

$form['precio'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#default_value' => $precio,
  '#size' => 20,
  '#attributes' => array(
    'style'=>'background: none repeat scroll 0 0 #EAEAEA;
              margin: 0 3 4;
              color:red;'
  ),
  '#description' => t('Change the price'),
);


How do i take a specific node and turn it into a block I created a content type of which there is only one node of, and i want to add to sidebar left. How can that be done? i would prefer not have to use a module to do this., thanks

I would suggest using views for this.

Create a "Content" view and choose your content type in the "Show" dropdown
Uncheck "Create a page" and check "Create a block"
Choose "Unformatted list" and "Full posts"
Limit the block to 1 "items per page"
Click the Continue & Edit button
Add a contextual filter for Content: NID
Provide a default argument of Fixed value and enter the Node ID of the node you want to display within the block

Optionally, you can choose to create a fields based view instead of full posts which would allow you a little more control over the layout of the nodes content within the block.

If you are set on not using ANY modules to do this then you'll want to look into https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view_MODULE_DELTA_alter/7 which would allow you to override a blocks output in your themes template.php.

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function YOURTHEME_block_view_block_BLOCKDELTA_alter(&$data, $block) {
  $data['content'] = drupal_render(node_view(node_load($nid)));
}


How to expand NodeForm so new argument can passed to it I have a content type called service request, which have some conditional fields that each might appear or disappear based on an other field value called service type.
I have used conditional field and they work just right but for better user experience I want node form to be called using one of the service types.
so I tried to follow this instructions provided by Jaypan to extend NodeForm, but when overriding form function of NodeForm, it leads to Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId()
this is how I used to create $form:
class ServiceBuilderForm extends NodeForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state, $serviceType = NULL) {
    // Added as a fallback in case a developer uses this form without passing
    // $someId:
    if (is_null($serviceType)) {
      $form = [
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => $this->t('Form is missing Service Type which is required'),
      ];
    }
    else {
      $form = parent::form($form, $form_state);
      // Do something with $form and $some_id
    }

    return $form;
  }
}

and in my Controller I have get my form using:
$form = \Drupal::formBuilder()->getForm('\Drupal\{my_module}\Form\ServiceFormBuilder', $serviceType);

After you have integrated the form class in the entity type as form mode
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('service', 'Drupal\mymodule\Form\ServiceBuilderForm');
}

and invoked the node form in a controller
$form = $this->entityFormBuilder()->getForm($node, 'service');

or without controller directly in a route:
_entity_form: 'node.service'

the entity including the field data is passed to your form
class ServiceBuilderForm extends NodeForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $node = $this->entity;
    if ($node->getType() == 'service_request') {
      $field_value = $node->field_service_type->value;

and you avoid the error from your question that the entity is null.


Services module, custom endpoint & authentication I have a have setup a custom endpoint via services and a REST server the custom end point looks like this,

https://website.local/api/v1/druaplsquare

The custom endpoint is built using the following code,

drupalsqaure.module

function drupalsquare_services_resources() {
  $resources = array();
  $resources['drupalsquare'] = array(
    'operations' => array(
         'create' => array(
             'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),
             'callback' => '_job_resource_create',
             'args' => array(
                 array(
                     'name' => 'node',
                     'optional' => FALSE,
                     'source' => 'data',
                     'description' => 'The node data to create',
                     'type' => 'array',
                 ),
             ),
             'access callback' => '_drupalsquare_resource_access'
         ),
         'delete' => array(
             'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),
             'callback' => '_job_resource_delete',
             'args' => array(
                 array(
                     'name' => 'jobref',
                     'optional' => FALSE,
                     'source' => array('path' => 0),
                     'description' => 'The job reference to delete',
                     'type' => 'string',
                 ),
             ),
             'access callback' => '_drupalsquare_resource_access'
         ),
    ),
  );
  return $resources;
}

resources/drupalsquare.inc

<?php

function _drupalsquare_resource_access() {
    return TRUE;
}

//function _drupalsquare_resource_retrieve($uid) {
//  $account = user_load($uid);
//
//  if (isset($account->data['checked_in'])) {
//      return array(
//          'uid' => $account->uid,
//          'name' => $account->name,
//          'last_checkin' => $account->data['checked_in'],
//      );
//  }
//  else {
//      return FALSE;
//  }
//}

function _drupalsquare_resource_checkin($JobReference, $date = NULL) {
    die(print_r($JobReference));
//  $account = user_load($uid);
//  $account->data['checked_in'] = is_null($date) ? REQUEST_TIME : $date;
//  user_save($account);
    return TRUE;
}

function _job_resource_create() {
    die("create");
}

function _job_resource_delete($jobref) {
    die("here");
}

I am making a cURL request this is endpoint, but I am first of all authenticating a user, and getting a token, I am then sending this token in the request header, however the endpoint above is returning,

  Access denied for user anonymous

Can anyone see any reason as why this would be happening?

In your code
Replace 'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),
with 'file' => array('type' => 'inc', 'module' => 'NAME_OF_YOUR_MODULE', 'name' => 'resources/drupalsquare'),
It seems you're wrongly defining your INC file.


How to filter views using Ajax I have an array that I stock in the browser's storage. I retrieve it in Javascript.

I'd like to use those values to display a view. They IDs represent a nid.

I already created a view, took a wildguess and decided to use the contextual filters, allowing me to pass parameters in the URL.

But now, I'm stuck.

Any hints/tips ?

Thank you

Don't use Contextual filters in this case, cause they are sent in url - use exposed filter.

Exposed filter will create form, which you can fill in and submit by js-code. Turn on AJAX fro view and filters will also work via AJAX.


confirn in link on overlay lists I create in administration list of some content and create link delete. On link delete I add attribute

onclick="return confirm('Are you sure?);"

but when you click "cancel" on confirm block drupal still go to link href:

http://www.supermarket.hr/#overlay=admin/categories/delete/6939/0

How can I anticipate some hidden overlay functions that ignore added confirm?

thx

Some code:

$option_delete = array(
        'attributes' => array(
            'onclick' => "return confirm('Delete order?');",
            'class' => "delete"
        )
    );

link:

l('delete', 'admin/orders/categories/'.$node->id.'/'.$page, $option_delete),

this link is showing up in list on administration overlay.


How to define ranges for integer/decimal/float fields in D7? I would like to add an integer/decimal/float field to a content type where users can define ranges for these numbers as two separate fields.
Like when adding a Date field, and being able to add an end date as a separate field with a little checkbox:

 (So the output will be like this: 2011 - 2012.)

Use case: users would like to define approximate numbers, they don't know data exactly, for example:

Stream bed's average depth: 0.3 m - 1 m
Stream bed's average width: 1 m - 2 m

(m would only be a suffix)
etc.

I needed the same functionality for a project I am working on.

I have created a sandbox project http://drupal.org/sandbox/thepearson/1842424 which I'll be working on hopefully releasing as contrib. I still need to do some more testing, tidy up and documentation.

Obviously it's in sandbox so, use at your own risk. Currently supports int and float. Supports defining min and max limits on both start and end values along with prefix, suffix and range indicator. ie:

[prefix] [min] [indicator] [max] [suffix]
[$ ]     [123] [<----->]   [157] [per person]

alnum type is there but limit validation seems a bit buggy. I would recommend not using alnum until more testing is done.

It's also supports some hook_info/hook_info_alter functions for you to either define your own range datatypes, or change the existing ones. Look at the sub-module range_integer to see how it's done.

If you find any bugs please raise bug reports at drupal.org.


hook_menu_links_discovered_alter() not being called I'm working on a theme for a Drupal 8.8 project. I've implemented hook_menu_links_discovered_alter() in my .theme file – but Drupal doesn't seem to be invoking it, and I don't understand why.

(For context: my goal is to make some modifications to the "Log in" and "Log out" links on the user account menu. I've found numerous examples online which say that this is the right hook to use for this purpose.)

Here's what I've tried:

I've checked (a dozen times) that I'm using the correct function name, with the correct signature: mythemename_menu_links_discovered_alter(&$links)
I've added die('in hook') in my hook function to determine whether it's even being called. (It's not.)
I've cleared cache many times, from both the Drupal web dashboard and via drush cr. No luck.
I've noticed that Drupal sometimes takes a while to notice changes to .theme files, even after you've cleared cache. So, to be absolutely sure that Drupal is using the latest version of the file, I've added echo statements to other (already-working) hooks. This has confirmed that Drupal is using the latest version of the file – but mythemename_menu_links_discovered_alter() still isn't being called.

Any ideas?

Generally, alter hooks are invoked even if they are implemented in themes, but to be sure you always need to check the code invoking the specific alter hook.
In this case, hook_menu_links_discovered_alter() is invoked from MenuLinkManager::getDefinitions. You can see this by clicking on 1 invocation of hook_menu_links_discovered_alter().

That method only invokes the hook implemented by modules, as it uses the following code to invoke it.

  $this->moduleHandler->alter('menu_links_discovered', $definitions);

To allow themes to alter those links, the code should contain a line similar to the following one, where $this->themeManager is an object implementing the ThemeManagerInterface interface.

  $this->themeManager->alter('menu_links_discovered', $definitions);

In short, you can only implement hook_menu_links_discovered_alter() in a module.


Help with hook_views_pre_build() I have set up a View to show a list of stories, and then set up an attachment to my View that puts the first 4 stories at the top of the View styled differently. I need those 4 to only show on the first page of items. Every other page will show the normal styling without the top 4. I have created a custom module using the following code. However, now every item is showing on one page. I have set number of items for the pager in the main view to 10 with an offset of 4, and in the attachment it is set to 4. Any suggestions?

<?php
/**
 * Implements hook_views_pre_build().
 */
function custom_stories_views_pre_build(&$views) {
  if($views->name == 'stories' && $views->current_display == 'block_1') {
    // if 'attachment_1' is not defined, we assume it is the first page.
    if (empty($_GET['attachment_1'])) {
      // The offset number y should be equal to the number of items on
      // attachment. If we want to keep the total n items on list, the
      // number of items on main display should be (n - y).
      $item_num = $views->get_items_per_page() - $views->get_offset();
      $views->set_items_per_page($item_num);
    }
    else {
      // Remove attachment for other pages.
      $views->is_attachment = TRUE;
      // We don't need to handle the offset anymore.
      $views->set_offset(0);
    }
  }
}

EDIT

You can try the below code its working fine for me.

$views->items_per_page($item_num); instead of
$views->set_items_per_page($item_num);

Related questios

May be this can help you


How to conditionally hide a space in a rules action if the first token is empty? I am using the tokens module to print personalized email notifications. Sometimes a webform component is not filled out and the email notification leaves an empty space before the token. I am using the Rules module to send a mail.

E.g.

[data:title-value-raw] [data:name-value-raw]

Default output

Mr. Example

Expected result

Example

Actual result

 Example

How can I hide the space if the first token is empty?

Drupal rule to send message.

{ "rules_mail_confirmation" : {
"LABEL" : "Mail Confirmation",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "webform_rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
  { "node_is_webform" : { "node" : [ "node" ] } }
],
"DO" : [
  { "mail" : {
      "to" : "[data:email-value]",
      "subject" : "Confirmation",
      "message" : "[data:title-value-raw] [data:name-value-raw],\r\n\r\n",
      "from" : "[site:mail]"
    }
  }
]

}
}

If I was to implement this, I'd create a special (tiny) Rules Component as a kind of helper function, and use that in your existing rule also. The clue of that Rules Component is the (not often used) "Provided" facility for one of its parameters. More details below ...

Part 1: Create a Rules Component

Create a new Rules Component that looks like so (in Rules Export format):

{ "rules_create_email_body_prefix" : {
    "LABEL" : "Create eMail body prefix",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "title_value" : { "label" : "Title value", "type" : "text" },
      "prefix_value" : { "label" : "Prefix value", "type" : "text", "parameter" : false }
    },
    "IF" : [ { "NOT data_is_empty" : { "data" : [ "title-value" ] } } ],
    "DO" : [
      { "data_set" : { "data" : [ "prefix-value" ], "value" : "[title-value:value] " } }
    ],
    "PROVIDES VARIABLES" : [ "prefix_value" ]
  }
}

Some details about the above Rules Component:

It uses 2 parameters:

it accepts title_value as an input parameter (Usage = Parameter).
it provides prefix_value as output of it (Usage = Provided).

The logic of this Rules Component is like so:

Rules Condition: verify that the value of title_value is NOT empty.
Rules Action: set the value of prefix_value equal to the value provided via title_value, and follow it by a space (note!).

Part 2: Integrate the Rules Component in your existing rule

Here is an updated version of your rule (also in rules export format).

{ "rules_mail_confirmation_with_optional_prefix" : {
    "LABEL" : "Mail Confirmation with optional prefix",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
      { "node_is_webform" : { "node" : [ "node" ] } }
    ],
    "DO" : [
      { "component_rules_create_email_body_prefix" : {
          "USING" : { "title_value" : "[data:title-value-raw]" },
          "PROVIDE" : { "prefix_value" : { "prefix_value" : "Prefix value" } }
        }
      },
      { "mail" : {
          "to" : "[data:email-value]",
          "subject" : "Confirmation",
          "message" : "[prefix-value][data:name-value-raw],\r\n\r\n",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

These are the changes I applied (as compared to your rule):

Rename the rule (to not override your own rule).
Add a Rules Action (as the first one) to invoke the newly created Rules Component (whereas the value [data:title-value-raw] is passed to the title_value parameter).
Adapt the message body of the eMail, to now use the prefix_value as provided by the Rules Component. To be complete: if the Rules Condition in the Rules Component is NOT satisfied, the value of prefix_value is empty, otherwise the Rules Component will assign a value is equal to title_value followed by a space.

Notes:

The exported rule as included in the 1st revision of your question, contains some errors/challenges, i.e:

It contains a syntax error, the comma at the end of your 2nd Rules Condition should not be there (only after I removed that comma I was able to import your rule ...).
Something doesn't seem right in the [data:[data:title-value-raw]] token you included, pretty sure it should be [data:title-value-raw], as confirmed somehow also in the edit you applied in revision 6 of your question.
IMO there is no need for "PHP" (as shown within "REQUIRES" in your exported rule ...), as confirmed somehow also in the edit you applied in revision 6 of your question.


Any imageslider for my homepage. am using drupal 5.21 on my website Any imageslider for my homepage? am using drupal 5.21 on my website.

You can try using Jquery slideshow module which support Drupal 5.x

Project page says

  This module creates a javascript slideshow using the Cycle plugin for
  Jquery. The slideshow is created from multiple imagefields of a node.
  There are settings to change the type and speed of transitions.
  Settings also exist to use Imagecache presets for the images.


Disable email updates alert on expired domain As per question, my domain already expired for over months now and im not planning on using it anymore but i keep getting the modules updates email alert coming from the domain.
How can i disable it since i can no longer access the domain to change the setting. I find its kinda weird how the domain still able to send the email.

Thanks.

If you still have access to the FTP folders where you uploaded Drupal just remove the folder where you previously installed Drupal. If you can't access it anymore, there's not much you can do. You can setup a filter in your mailbox though.


Making a home page without /home My website is mycapecodvacations.com I need help how to make the default home page mycapecodvacations.com instead of going to mycapecodvacations.com/home I'm using host gator .com and want to know how to make the home page without /home and just " mycapecodvacations.com" i tried removing the htaccess file. do I need to edit a specific file?

You can use Global Redirect module.

  Checks if the current URL is the same as the site_frontpage and
  redirects to the frontpage if there is a match.

Every time when mycapecodvacations.com/home is accessed, Global Redirect will redirect to mycapecodvacations.com.


Pantheon Live / Test / Dev Login Issue I have recently inherited a Drupal 7 site on Pantheon.io. None of the admin logins that work flawlessly in the Live environment work in either Test or Dev. I have pushed/pulled code and DB between the three to make sure they are all identical, but the logins still fail in Test and Dev. Any thoughts or suggestions would be greatly appreciated.

After more hours than I care to admit, I came to realize that the issue was very simple... The Pantheon Dashboard's links to "site admin" go to the http:// site and NOT the https:// site, therefore, none of the addresses were resolving correctly. The live site automatically redirects http:// traffic to https:// so it works just fine.


Problem with character encoding ( danish æ ø å ) when using page handler include files in hook_menu(). When I use an .inc file to handle my page output, all the danish special characters (Æ, Ø and Å) shows up as question marks, i.e. they are rendered with the wrong character encoding.
This following module works as expected.
stack_exchange_minimal.module
<?php
/**
* Implements hook_menu().
*/
function stack_exchange_minimal_menu() {
  $items['mypage'] = array(
    'title' => 'Minimal example',
    'page callback' => 'mypage',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mypage() {
 return 'ÆØÅ - æøå'; //outputs 'ÆØÅ - æøå'
}

When I split the code up in two files, however, it doesn't.
stack_exchange_minimal.module
<?php
/**
* Implements hook_menu().
*/
function stack_exchange_minimal_menu() {
  $items['mypage'] = array(
    'title' => 'Minimal example',
    'page callback' => 'mypage',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'stack_exchange_minimal.pages.inc',
  );
  return $items;
}

stack_exchange_minimal.pages.inc
<?php
function mypage() {
 return 'ÆØÅ - æøå'; //outputs '��� - ���'
}

I have tried passing the text through a render array instead of just dumping a string as the return value, but whith the same results.
I'm using drupal core version 7.31
What can I do to work around this issue?

The problem was, as Andy pointed out, that the file wasn't encoded in UTF-8.

The .inc file was created from the context menu in Windows: 'New' -> 'Text Document', which defaults to the ANSI encoding.

The solution is simply to convert the file to UTF-8, that can be done for example in Sublime Text by choosing 'File' -> 'Reopen with Encoding'. Other text editors have similar commands.


How to implement Facebook style Notifications for Organic Group posts? I am using Organic Groups, Drupal Commons. If someone posts in group, then all the members should be notified like in Facebook with the number of notifications. Similar to this screenprint:

How can I achieve that ?

Notes:

By Posts I mean a creating new node of Post content type (default) in Organic Group (and commenting part is not required now).
I have not implemented any rule for this, can you explain how can I achieve this using rules ?

Below is a blueprint of how you can make this work. To avoid writing a manual as an answer, and to avoid repeating myself, I use some links to other answers (not all of them are mine ...).

Step 1: Get Rules involved

Use the Rules module to capture events about new nodes being created, which belong to some Organic Group. Have a look to either of the answers to  "Get organic group name in a rule?", for 2 possible alternatives to "send an eMail" to each member of the group.

With that, all that's left is to replace the Rules Action to "send an eMail" with something that shows the number of notifications (as in your question), as further explained below.

Step 2: Use Messages to create notification entities

Install/enable the Message module also. So that you replace the Rules Action from the previous step to "send an eMail" by a Rules Action to create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages later on (hang on: in a format like your shiny notification button ...).

Here is a summary of what you'd need:

Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes.
Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples.
Possibly you may also want to add a Rules Action to pass any relevant tokens, via Rules, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
Use Views to display the created messages in the format you prefer.

Step 3: Transform the view in a notification icon

The Menu Badges module can be used to add such notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

  Provides a method for adding iOS-style badges to menu items. (see screenshot)

  Adding Badges to Menus

  Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.

  Adding Badges to Tabs

  For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.

  Badge Types

  The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like this:

Just create an appropriate view of it, create a menu item or menu tab for that view. Obviously, the view created in Step 2 is the view you want to use.
Do a 15 seconds Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Video tutorials:

Defining Menu Badges with Views in Drupal (from the module maintainer).
Drupal 7 Menu Badges Module.

Step 4: Updating the notification icon

After you completed the above steps, you'll have such shiny notification icon corresponding to the relevant messages. What's left is to implement something to get the icon (ie the counter shown in it) updated, as further explained below.

Option 1 - Make the Messages manage-able

This option allows a user to indicate which messages have been read already, and which ones are new (= unread). For that, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the Flag module).
Create a view 'Messages by user' (= improved version of the view specifications described above).
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

Option 2 - Remove the notification icon after visiting some path

This option will remove the notification icon entirely, after the user visited the dedicated path to display all messages. Refer to the answer to "How to make menu badges count disappear after the page is viewed?" for details about how to do so.


Views field rewrite onClick attribute not rendering In a D7 instance, in Views under "Rewrite the output of this field" I have this in the textarea:

[field_downloads_1-description]

All data is displaying except for the onClick attribute. Any ideas why?

Views rewrite uses the filter_xss_admin function to produce safe html. It's designed as a security measure and is in place even if the user has permissions to add PHP and unfiltered HTML in other contexts.

You can work around by using Views PHP for example. See this issue at drupal.org for discussion and more on workaround approaches.