How do I disable the "Group activity" tab on the organic groups page I've got organic groups setup in Drupal 6 and have been asked to remove the "Group activity" tab from the groups page (example.com/og). I suspect that this is being driven by one of the views, but I can't seem to find one that is powering it. Is it possible to disable this tab or control its output at least?

This tab appears to have been removed from the Drupal Groups site: http://groups.drupal.org/og

The Tab tamer module is a quick and easy way to hide or disable extra tabs.


With states, how to uncheck a disabled checkbox, but not check it when it becames enabled? I have a Form API checkbox that can be enabled and disabled by another ("parent") one:

$form['my_checkbox']['#states'] = array(
  'enabled' => array(
    ':input[identifier="parent"]' => array('checked' => TRUE),
  ),
);

Works like a charm, but now I want it to get cleared if it is dizabled. So I made my code look like this:

$form['my_checkbox']['#states'] = array(
  'enabled' => array(
    '[:input[identifier="parent"]' => array('checked' => TRUE),
  ),
  'unchecked' => array(
    ':input[identifier="self"]' => array('disabled' => TRUE),
  ),
);

Sadly, this also automatically checks that checkbox when it becomes enabled, and that's not what I want - I want to give my user an option, but not suggest him to check that field at all.

Can this "one way" action be achieved with '#states'? If so, how? Or is it always two way deal, and there is no option to uncheck on disabling without checking on enabling?

Note: I tried to use both disabled and enabled of self, and checked & unchecked of parent, with the same results.

I know I can achieve it with behavior, that's how I have it done now, but states api is there to avoid behavior's complexity and my use case seems pretty simple.

Turns out that with current implementation of states it is not possible. When condition gets true, state is applied, and when it gets false, state gets removed. No way around it so far, not without hacking core, so it's more feasible to write custom behaviors instead.


Getting error 'The requested page could not be found' after https is enabled The link to my content is lost

default settings:

# Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

my serversupport suggested:

#Rewrite everything to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

both didn't work, when comment out everything. My link to the content is fixed using http.

how to solve this?

The link to my content is lost

So you enabled HTTPS and you can no longer see your Drupal website? It sounds like you have uploaded your Drupal installation in public_html and are now serving content from the private_html folder.

If you are on a Direct Admin installation you can toggle the symlink private_html to public_html configuration That should make sure the correct files are served via HTTPS as well.

Enabling HTTPS

The rewrite rules that ship with Drupal are intended for mix-mode HTTPS (in which case your site supports both HTTP and HTTPS).

If you want the best security, just redirect everything to HTTPS. See the 3rd bullet point of Enabling HTTP Secure (HTTPS):

  For best possible security, set up your site to only use HTTPS, and
  respond to all HTTP requests with a redirect to your HTTPS site.
  Drupal 7's $conf['https'] can be left at its default value (FALSE) on
  pure-HTTPS sites. Even then, HTTPS is vulnerable to man-in-the-middle
  attacks if the connection starts out as a HTTP connection before being
  redirected to HTTPS. Use the HSTS module or Security Kit module, or
  set the Strict-Transport-Security header in your webserver, and add
  your domain to the browser HSTS preload list, to help prevent users
  from accessing the site without HTTPS.

  You may want to redirect all traffic from http://yourdomain.com and
  http://www.yourdomain.com to https://youdormain.com. You can do that
  by adding this to your .htaccess file:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com*
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

  Put that below RewriteEngine on.


Alter a panel page variant provided by another module (programmatically) How can I alter a panel page variant provided by another module in my own module?

I am using Advanced Forum, and it provides a panel page to override Drupal's core forum display behavior and some variants: Top Level Forum, Container and Forum. But I have changed some layout options, and added a few more panes, and disabled some other panes etc in page manager UI. Now I want to export this into code, i.e. in my custom module. I can export the code using the export option in the UI, but I don't know how to add that code in my module. In other words I don't know which hook to implement to override this variant provided by Advanced Forum, instead of creating my own variant.

I know how to provide default panel pages or variants using hook_ctools_plugin_api() and hook_ctools_plugin_directory(), but I couldn't find out how to alter an existing page variant provided by another module.

Is there a hook for that?

You might try creating a clone of this variant and then making your custom changes to it. You can then reorder this variant so it is above the original. This way your custom variant will always get executed and the original one ignored.

Once that is completed, you should then be able to export your variant using features.


What is the best way to add the latest version of jQuery to a theme? This is just a simple question I have. I'm most interested in seeing what others are doing to use the latest version of jQuery in themes.

The reason for this is that some of the best jQuery plugins I use require much later versions of jQuery than what Drupal comes with.

I have tried the update jquery module but it is not as good for Drupal 6 sites.

Is there another way outside of adding your own version of jQuery. Then once you have it finding and replacing jQuery with something like myQuery and sticking myQuery.noConflict() at the end? And then once this is done rewriting plugins to work with myQuery?

In my opinion the best solution is to replace drupal jQuery with the latest jQuery only on the pages where you really need it. If you go on with newest jQuery many of drupal out of the box functionality will be broken.

You can remove native jquery like in the code snippet below only on certain pages that meet your conditions:

function MYTHEME_preprocess_page(&$variables, $arg, $delta) {
  if(YOUR CONDITION HERE) {
    $scripts = drupal_add_js();
    unset($scripts['core']['PATH TO DRUPAL JQUERY']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

to add your newest jquery file you can use drupal_add_js('path to yor newest jquery') function.


CCK Date field not showing stored values in node edit form After moving a Drupal 6.x site to a new server, I've found that a CCK date field being used by multiple content types is not displaying the values that are stored in the database for the field OR the default value as defined under content management and date field when creating a new node. The field is just blank. For stored nodes, the values are still there when viewing the node, they just disappear when editing it.

I've found two similar issues, but both relate to multilingual support in Drupal 7:
 1. Why some fields values are getting empty when editing a node?
 2. https://www.drupal.org/node/1146056

ANSWER: I upgraded the Date API module to 6.x-2.10 and the problem was fixed.

I'll assume you have the latest Date module version installed, 6.x-2.10. There is a similar issue in the module's queue here. Run phpinfo() and see if Memcached is installed on your new server. Uninstalling the extension could possibly solve your problem.


In content type show same field twice with different widget I want to show one field (file type) twice in the same content type (without display suite as it breaks my other modules). After a user uploads a pdf and saves this content. I want one link to lead to pdf file for download(which it does) and the other link to show generic file (open a pdf in browser) and i dont know how to do that part (To change widget type). I have searched Drupal Answers and found some clues on how to do this in template.php

function bsthemel_preprocess_field(&$vars) {
 $node = $vars['node'];
     if($vars['element']['#field_name'] == 'field_document_pdf') {

        //code to copy and render this field with different widget (havent figured out how yet)
}

Now i am still new to drupal and can't seem to figure this out. Also what i have found is function hook_field_widget_form_alter but i think this has to be done after the new field is made. Or i might look at this completely wrong. Any help is appriciated

The "right" way to add additional elements to a view mode (without using a module like Display Suite or Panelizer to take over view modes) is to use hook_field_extra_fields():  This hook will make your added element visible on the core view mode configuration screen.

If you're new to Drupal it might be easier to go with the preprocess route. But instead of working at the level of template_preprocess_field() you should be working at the level of template_preprocess_node(). The node hook contains the field you want to duplicate. The field hook deals with only one field at a time.


How can I add a Pathauto pattern for a content type depending on a reference field? On my site I have a content type 'Article' that has a reference field to a taxonomy vocabulary 'Type of Article' containing terms like 'Blog', 'News', etc.
Now I would like to have Pathauto form a different URL for each type of Article. E.g. /blog/article-title, /news/article-title, etc. Is it possible to set a pathauto pattern depending on the settings of that reference field?
Earlier I used different content types, with which it was no problem to get a different Pathauto pattern for each. But as the fields in the content types were the same I would like to solve it like this.

Right beneath the pattern input you have a link that opens a popup to let you choose tokens to be put in the pattern. For field values it normally goes along the line of [node:field_foobar:value]. Depending on the field value you may also consider to either provide your own custom token or to alter the current token with an alter hook to replace the value with an URL-safe value (like to prevent the URL contains an Emoji for example).


How to change block visibility/pages in hook_block in my module? I implement mymodule_block and for case 'list' I have blocks like:

  $blocks[CN_BLOCK_RHM_BUTTONS] = array(
        'info' => t("Block name"),
        'status' => 1, // on by default
        'weight' => -99, // should be at the top
        'region' => 'right', // RHM
        'visibility' => 1, // Only on these pages
        'pages' => 'page1' . PHP_EOL .
          'page2' . PHP_EOL .
          'page3' . PHP_EOL

This works great for new blocks created on our dev site. But I want to change the pages settings in source control, and for these changes to propagate when we updated this module on our production site. It seems that for existing module deltas, Drupal looks at the block table fields and ignores any changes in hook_block. If these any feature of Drupal or cool snippet that will help me 'reset' blocks to the module's settings?

You can achieve this by writing a hook_update in your module's .install file. You will need to update the 'block' table directly in that hook to change the block settings as needed. After moving your updates to production, run update.php, which will apply the changes in hook_update.


Custom node actions/ I have a view which is rendered as a table, the last column is labeled "actions" which I display both the "Edit" and "Delete" links accordingly.

I need to implement a few more custom operations, I found this as a starting point:

Custom entity operation links

Here is what I have thus far:

module.module

<?php
  function module_views_api() {
    return array(
      'api' => 3,
      'path' => drupal_get_path('module', 'module') . '/views',
    );
  }

module.info

files[] = views/module.views.inc
files[] = views/module_handler_print.inc

module.views.inc

<?php

  function module_views_data() {
    $data = array();
    $data['node']['print'] = array(
      'title' => t('Print link'),
      'help' => t('Provide a simple link to print the content.'),
      'field' => array(
        'handler' => 'module_handler_print',
      ),
    );

    return $data;
  }

module_handler_print.inc

<?php
  class views_handler_field_node_link_print extends views_handler_field_node_link {

    function render_link($node, $values) {
      // Ensure user has access to edit this node.
      if (!node_access('update', $node)) {
        return;
      }

      $this->options['alter']['make_link'] = TRUE;
      $this->options['alter']['path'] = "node/$node->nid/print";
      $this->options['alter']['query'] = drupal_get_destination();

      $text = !empty($this->options['text']) ? $this->options['text'] : t('print');

      return $text;
    }

  }

I can see the option when adding the field to VIEWS but when I select it I get the error:

  Configure field: Broken/missing handler

Any ideas???

You can try this module: https://www.drupal.org/project/ccl

or create your custom solution based on this code snippet


Why the ETAG always change of my D7 site ETAG should not change if the page not changed.

But when I refresh the web page after login, the ETAG always change.

In my setup, if I am logged into the CMS, then the Etag seems to be written as a unix timestamp, which is clearly being done to force caching off.  So this may be the reason you see the Etag constantly changing.

However, even when not logged in, in my case the Etag seems to change when the associated page cache expires, even if the content in the resource doesn't change at all.  I don't know why this is happening.


Some nodes served headless Drupal and some nodes served with Drupal We are building a site that will be built and served via Drupal.  We want to have microsites that we want to share SOME of the content between the main site and the microsite.  We are thinking to build the microsites via Headless Drupal and use API from the main site.

The problems I see:

For example, node/2 should only be accessible on the microsite.  How would the main site which is not headless know that it can't access node/2?  Basically, some nodes will be served headless and some will be regular Drupal.

Would it make things easier to just have the main site be headless as well?

Take a look at the Permissions by Term module.  You can add a term field that defines the site(s) the node is accessible by and limit access to content authors on the main site.

Your API for the microsites can use this to limit access by site as well.

If that one doesn't work, it's description lists another module that might work.


8 - How to run jQuery to show a div, after register form is submitted? I've looked at this question, but I want a div to be displayed rather than a Drupal Message

After a user successfully submits the user_register_form, I want to call a jQuery function like this:

function showMessage(){
  $('#message-overlay').fadeIn();
}

This is so I can show users that they have to confirm their email address in order to login.

I tried using hook_form_alter like this to display a custom message, but even this does not work...

function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
    $form['#submit'][] = 'submitForm';
  }
}

function submitForm(array &$form, FormStateInterface $form_state) {
  drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

Please advice!

I used like below and it works for me:

function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
      foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_message_submit';
        }
      }
  }
}
function _message_submit(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  drupal_set_message(t('The user @name account has been created successfully.', ['@name' => $values['name']]));
}


Drupal Commerce AJAX HTTP Error 200 while adding product display has anyone else come across this?  I'm getting an error when I'm trying to create a product display.  It happens when I'm trying to put in the product SKU.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: http://hayfield.com:8082/commerce_product/autocomplete/node/field_product/product_display
StatusText: OK
ResponseText: {"glorious_dream":"\u003Cdiv class=\u0022reference-autocomplete\u0022\u003Eglorious_dream: Glorious Dream\u003C\u002Fdiv\u003E", "Hayfield_Elegance":"\u003Cdiv class=\u0022reference-autocomplete\u0022\u003EHayfield_Elegance: Hayfield Elegance\u003C\u002Fdiv\u003E"}jQuery.extend(Drupal.settings, {"thmr_1":{"id":"thmr_1", "name":"link", "used":"theme_link", "type":"func", "duration":2.78, "candidates":[ "hayfield_link" ], "preprocessors":[  ], "processors":[  ]}, "request_id":"1852760308506e2eabeea31", "devel_themer_uri":"\u002Fdevel_themer\u002Fvariables\u002F1852760308506e2eabeea31"});

Thanks in advance!!

I've seen this error before, you should start from scratch with the latest release candidate for Drupal Commerce, located here: http://drupal.org/node/1786764. This fixes the AJAX bug.


nginx sets content-type text/html on redirect I set up nginx as a reverse proxy for Drupal. Static files are served from a different domain. It works well, imagecache files are generated well, too. But the problem is: when the derivated image does not exist, the request for this image returns a redirect with the content-type:text/html, and Facebook or jQueryMobile (only when running in an iPhone, not in desktop browser) does not like it.

The context: when a file is requested from mycdn.com, if it does not exist, it is redirect to mysite.com which is a site that does the reverse proxy. So, it can be seen that imagecache does nothing here, just a use case. The question here: why nginx adds a text/html when it does a redirect?

Here is  the scenario:

GET http://mycdn.com/sites/default/files/imagecache/gallery/myfile.jpg

Server  nginx
Date    Tue, 26 Jul 2011 05:28:09 GMT
Content-Type    text/html
Content-Length  154
Connection  keep-alive
Location    http://mysite.com/sites/default/files/imagecache/gallery/myfile.jpg
Expires Thu, 25 Aug 2011 05:28:09 GMT
Cache-Control   max-age=2592000

then the result of the redirect

GET http://mysite.com/sites/default/files/imagecache/gallery/myfile.jpg
Server  nginx
Date    Tue, 26 Jul 2011 05:28:10 GMT
Content-Type    image/jpeg
Connection  keep-alive
X-Powered-By    PHP/5.2.17
Expires Tue, 09 Aug 2011 05:28:10 GMT
Cache-Control   max-age=1209600, private, must-revalidate
Etag    "58a657c2ee47424f202387000c191b7e"
Set-Cookie  DRUPAL_UID=64; expires=Thu, 18-Aug-2011 09:01:29 GMT; path=/; domain=.thongtincongnghe.com
Vary    Cookie,Accept-Encoding,User-Agent
Last-Modified   Tue, 26 Jul 2011 05:28:10 GMT
Content-Encoding    gzip
Content-Length  1400

nginx configuration on mycdn.com (I removed unrelated info):

server {
    listen       80;
    server_name mycdn.com;
    root   /home/ttcn/public_html;
    expires 30d;

    location / {
        try_files $uri @redirect;
    }

    location @redirect {
        rewrite ^(.*)$ http://mysite.com$1;
    }
}

Brief, with a desktop browser, there is no difference. Everything works flawlessly. But jQueryMobile on a mobile does not work (until the derivated image is generated, through a desktop browsing), Facebook OpenGraph does not work (I put the derivated image url in the og:image value) - it does not take that image until it exists on the server.

There is nothing wrong with the redirect having a content type of text/html. On the contrary, it is actually mandated by the HTTP/1.1 specification itself:

  The temporary URI SHOULD be given by the Location field in the
  response. Unless the request method was HEAD, the entity of the
  response SHOULD contain a short hypertext note with a hyperlink to the
  new URI(s).

The cache control header might be confusing Webkit mobile. Have you tried add expires off; inside the location @redirect block?


insert data into database using web service I am creating a custom web service. In this, as soon as service call, data should be store into database. I am using Hook_service_resource() function. How can i implement insertion into database using services. I created my_module.install file and prepare database schema. BUT i actually don't know how to use query in hook_service_resource() function.

Create a Custom Drupal Module

Create these empty files in the new directory:

my_module.info
my_module.module
my_module.install
my_module.resource.inc
my_module.services.inc

Place this code in the my_module.info file:

name = My Module
description = My custom Drupal module.
package = Other
core = 7.x
dependencies[] = services
dependencies[] = rest_server

Place this code in the my_module.module file:

<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_module_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'my_module.services.inc'
    );
  }
}

Place this code in the my_module.services.inc file:

<?php

function my_module_services_resources() {
  $resources = array(
    'my_module_resources' => array(
      'actions' => array(
        'insert_into_database' => array(
          'help' => t('Insert Database Example.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'my_module',
            'name' => 'my_module.resource',
          ),
          'callback' => 'my_module_insert_into_db',
          'args' => array(),
          'access arguments' => array('access user profiles'),
          'access arguments append' => FALSE,
        ),
      ),
    ),
  );
  return $resources;
}

Place this code in the my_module.resource.inc file:

<?php

function my_module_insert_into_db() {
  $id = db_insert('example_table') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
))
->execute();
  if ($id) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Change the access arguments as per your permissions settings..

Call the service

http://www.example.com/?q=serviceendpoint/my_module_resources/insert_into_database.json


Content:author Relationship Not Showing Fields for Comments View I have created a view to show a nodes comments in a block.

Authors on my site have different roles, and they can create a single business page. On that page, other users can leave comments.

For site authors that have a "Free Listing" role, I want to hide the ability for other users to post comments.

To do this, I have added a view to display comments, then added a relationship for Comment:Content, then a relationship for Content:Author.

In my previous experience, this should give me a field (Content)Author:Role to filter results by. Instead, I get no additional fields, just the standard Content:Author ID field, which then tells me..."If you need more fields than the uid add the content: author relationship", I have!!!

Have I uncovered a bug? Or am I missing something?

Any advice appreciated.

You need to filter for a User fields if I understand correctly (i.e. you want to display only comments on the current node when the node author has a certain role).

Select User: Roles as the filter and make sure the Relationship select box is set to the identifier for Content: Author. That will let you filter the comments by the node author's role.


How to setup a csv-file to import image-paths into an image-field via Feeds-module? I import a csv-file via Feeds-module and got stuck with the images for a node. All the other fields are importet as wanted, except the path for the image-field.
The images are already uploaded to the directory below...

An example for a row value of a path:
sites/all/default/files/images/name.JPG

After the import, the image field is just empty:

Any help would be highly appreciated!
Thanks in advance...

You need to specify the full HTTP path. It's possible that something like a file schema might work (public://images/name.JPG), but in my extensive use with Feeds we import file fields (mostly images but also mp3, pdf, etc) by specifying the full HTTP path that the file can be found at, e.g.: http://example.com/sites/default/files/images/name.JPG.


How do I filter a view based on a multilingual alias? I have a view with a contextual filter which builds a page based on a product's model number. The path is /support/%, where % is the contextual filter for the model number.
This works fine for English content. I would like additionally take a path of /assistance/% for French content. How can I have one view with two, or variable paths?

You can not two views with same path.
You need to create copy of the view and change its path.

For french language you need to use filters? When you create your view, you add a new filter and select "Node translation" from the "Groupes" list and the check "Node translation: Language" and click "Add". Then you can chose language(s) on which you want the view to show.


How to configure Wysiwyg + Ckeditor Library not to breaks source code lines I'm using WYSIWYG Module with ckeditor as an editor.
I use it with the full_html format

My problem is that when switching from the rich-code to the source code view all the line breaks are removed.

So this portion of code :

Nemo enim ipsam voluptatem quaerat voluptatem.

Doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

transforms into something like this :

Nemo enim ipsam voluptatem quaerat voluptatem.

Doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Is there a configuration that prevents this from happening ?

I think what you are looking for is WYSIWYG Linebreaks.


Using the Panopoly and Commerce Kickstart distributions together I want to create an e-commerce site, and also have the ability to easily create landing pages, using the wonderful responsive layouts of the panopoly landing page editor.

What is the easiest way to go?

Install panopoly on top of commerce kickstart distribution?
Install commerce modules on top of the panopoly distribution?
Edit the distrubtion makefile - like someone did with other distributions.

How to do it successfully? And did somebody do it?

I would do #2.  To my knowledge, all of the modules in Commerce Kickstart can be downloaded separately; Commerce Kickstart just offers some default configurations.  If you run into trouble setting up the Commerce modules, you can always install a copy of Commerce Kickstart on a local machine/another server and reference that while you are setting up your main site.

By contrast, the problem with #1 is that not all of Panoply is easily configurable if you are not using that distribution (for example, the responsive layouts).  So it will be much easier to use that, especially if you are going to host it on Pantheon, which is behind Panoply.

You could edit the distribution makefile but that is probably more trouble than it's worth; the Commerce modules are designed to be installed on any Drupal site, so adding them to Panoply is very straightforward.


I want to modify the drop down menus for Marinelli (a Drupal theme) I have the Marinelli menu setup in a website I am internal testing.
I want to modify the drop down menu (I know it uses jQuery), but I have no idea what to do to show the drop down all nested.

In other words, instead of having this in the Marinelli theme

MENU1
submenu
underMenu
undermenu
submenu
undermenu

I want to have the menu like the corolla theme

MENU1
submenu
submenu

and when I hover a submenu:

SUBMENU
undermenu
undermenu

Any help is welcome.

The marinelli_menu.js on the marinelli theme folder is controlling the JavaScript.

The primary-links.css file is handling the theming.

Armed with this knowledge you can use Firebug to easily tweak the CSS and find out how it looks without having to save the file. And with Firebug's command line and debugging you can explore how those JavaScript functions behave and what's the best way to modify them if necessary.

If you don't know JavaScript or CSS then you have bigger issues.


How to list all nodes of nodetype A which has the current node referenced? So this is what I'm trying to do in Drupal 6:

Node type A is video, node type B is a person
Nodetype A has a reference field where you can enter a reference to any Node from nodetype B

how can I create a block view which will be displayed on nodes from node type b, which will show all the nodes from node type A where the current node from node type B is referenced?

Simplest way would be to make references two-way. To do this, use:

Corresponding Entity References for Drupal 7
Corresponding node references for Drupal 6

That way, current node will reference all nodes that reference it - and from this point creating a view is trivial - or you can simply display the field created for back reference, without need for a views module at all.

Other way is to use Views. Create a view displaying nodes from content type A, add argument content reference field > provide default argument > node ID from URL and display this block view on the nodes from content type B.


Can't add custom.tpl to my module I create a custom module that included hook_menu and hook_block_info and ...
i wanna add a tpl to this module . here is my code :

        function hookmenu_menu() {
            $items['hookmenu'] = array(
                'title' => 'Soheil',
                'page callback' => 'hook',
                'type' => MENU_NORMAL_ITEM,
                'page callback' => 'myhook_page',
                'access arguments' =>array('administer content'),
            );
            return $items;
        }

        /*
         * page callback
         */
        function myhook_page(){

            return theme('my_custom_template');
        }

    /*
 * Implement hook_theme().
 */
function custom_example_theme(){
    return array(
        'my_custom_template' => array(

            'template' => 'custom-page',
        ),
    );
}

and i created a custom-page.tpl and wrote hello world .
result : i can see my page but i can't see hello world

thx

Your file needs to be named

custom-page.tpl.php

Note the .php extension. You might need to clear the caches to make that change show up

You also need either a variables or render element property as outlined in the docs


Does using Views & Panels on every page will effect site performance (speed)? I am building a community site.
The site would have A LOT of data on it.

I thought about creating a lot of content pane with views, and use them with panels - for every page.

I will be happy to hear your thoughts about this idea.

It will make my site much slower?
Or it depends entirely on different things?   if so, I will be happy to get more information. I know I need to cache,  but I don't really know how to do that on the user's computers.

Thanks!

Panels is actually sometimes faster than core is on it's own.

http://www.codeenigma.com/en/blog/performance-panels

And that's without utilizing caching, something Panels can do much better than core, because it allows you to do it from on a page by page basis, down to on a block by block basis.


How to list profile fields in a tableselect? I'm attempting to list out all the fields a user profile object would have into a tableselect. This will be displayed on the configuration screen of a module that I have been building. I have managed to make a tabelselect with checkboxes and dropdowns in it. That part I got down.

The part that I thought would be easy and ended up getting me stuck is getting an array of the fields a profile has. This would include any user made profile fields. Is there a simple way to get an array of the profile fields without needing to relate it to a user? The module would need this list on the front end for anonymous users so comparing it to the user would not work.

I don't need the values of any fields just the names and type of field maybe some settings like max and min. But will not need the value of any set user.

It sounds like you want field_info_instances():

$fields = field_info_instances('user', 'user');
$rows = array();

foreach ($fields as $field_name => $field) {
  $rows[] = array(
    $field_name,              // eg. 'field_my_field'
    $field['label'],          // eg. 'My Field'
    $field['description'],    // eg. 'A Description of my Field'
    $field['default_value']   // eg. 'default value'
  );
}


How to use AJAX form on custom maintenance page I have been working to customize our maintenance page via custom template and hook_preprocess_maintenance_page(), the intent is to provide the maintenance message, some static text, as well as a basic AJAX form that allows the user to select a state, and then a specific location in that state, once they submit they will then be passed to the appropriate location outside of our site.

This is how I am handling the form:

in hook_preprocess_maintenance_page()

$vars['maintenance_header'] = $vars['content'] ? "
" . $vars['content'] . "
" : "
System Maintenance
";
$vars['maintenance_content'] = "
Don't go anywhere!
";
$maintenance_form = drupal_get_form('ajax_example_simplest');
$vars['maintenance_join_form'] = drupal_render($maintenance_form);

in maintenance-page.tpl.php

<?php print $maintenance_header; ?>
<?php print $maintenance_content; ?>
<?php print $maintenance_join_form; ?>

In building the form I noticed that when the Ajax callback fires, the contents of $vars[maintenance_header] is printed to an alert window on the screen, instead of the page being updated as I expect. To validate if this was an issue with my form specifically, I grabbed the simple ajax example which is linked below, and the behavior is exactly the same.
https://api.drupal.org/api/examples/ajax_example%21ajax_example.module/function/ajax_example_simplest/7

In searching for questions around this I continue to find general ajax questions, and questions about theming the maintenance page, but nothing that covers using an ajax form within the maintenance page, so I have started this new topic to see if others have encountered this specific issue. I am wondering whether an ajax form simply won't work on a custom maintenance page or if this is related to how I am handling the form in the preprocess hook?

Thank You,
Rose

When you put your site to offline mode, the menu router system (which is called first when a request is received to serve a page).

By default, Ajax forms are handled from the path system/ajax, which is not allowed when the site is in offline mode. This is not an issue with Drupal itself, it's just that when a site is in offline mode, there is no guarantee that any system is in working condition.

Ajax forms require the form to be cached, and that cache storage is the database unless you alter otherwise. When the database connection is failed, Drupal returns the same maintenance-mode page. Now, if you embed an Ajax form, imagine how there will be a recursion.

If you still need an Ajax form, you need to implement hook_menu_site_status_alter() to alter the site status for a specific path. Then, in your form, your will need to turn off caching ($form_state['no_cache'] = FALSE), and add your own #ajax properties with especially ['#ajax']['path'] set to your custom path that bypasses site status check (from the hook_menu_site_status_alter() hook).

I didn't bother to write an example since your question indicates you already have the Ajax form setup. Disable its cache, add a custom path to handle the submitted data, and make that path accessible with a hook_menu_site_status_alter() hook.


Send e-mail after entityform submission using field from referncing node I have a content type called contact page and several entity forms. The content type contact page has two fields on it one entityreference field that is used to reference an entityform and the other a text field used to store an e-mail address.

If the user selects an entity form then when the contact page is rendered so is the referenced entityform. When a user submits and entityform I would like to send an email to the email address supplied on the contact page.

I've been looking at rules but I am struggling to find out where I can load fields from the referencing entity so that I can use the email address on the contact page once an entityform is submitted.

First you have to add a condition "this entity has the field". Then you will be able to access this field in the selector in other condition.


How to add a class or id wrapper to a I added a footer to a view and I need to give this footer a wrapper class or id. How can I accomplish with this?

You  an can put HTML in there, just make sure you choose an Input Format (Text Formats in D7) that allows you to use the HTML tags you'll be putting in there.


How I get notified every time their is an *new* update and not every day for the sames updates? The update module can send you email when a new release is available for a module you installed. The problem is I get a email everyday. Some security update are very minor and unreachable for an attacker, I don't want to update the website and so I don't want future notification about this update.

I would like to be notified every time their is an new update, not every day for the sames updates.

I can use hook_mail_alter to cancel the sending of the mail. I can simply store a md5 of the mail's body every time the mail is send and compare it with the "new" email, if it's the same I don't send it.


How to use the Rules and Group modules to send a privatemsg to users of a role in a group? I am using the module Rules with Group (not Organic groups) as well as the Privatemsg module.

I want to send an email to all users of a role that are in a group. I am able to send an email to all users of a role, but I need a Rules condition that sends it to members of a certain group.

Any Suggestions?

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

Meaning you can already use Rules to:

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

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

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

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


Given a book node nid, programmatically get all child node nids I use the D8 Book module to create books with chapters. Works great.
When an editor makes a certain change to a book node, I need to look at each of its chapter (child) nodes to potentially adjust a field in them.
I know how to detect the book node change in node_presave(). I know how to load, modify, and save a child node once I have its nid. What I don't know is how to get a complete list child node nids for the book.
I've read many posts related to this subject, but none that provide a straightforward way to programmatically get a list of child node nids given the parent book node nid. I've also looked at the Book module documentation. I assume I'm just overlooking something simple.

To get the complete list of child node nids for the book:
use the BookOutlineStorage::loadBookChildren from the book.outline_storage service.
like the following:
/** @var \Drupal\book\BookOutlineStorageInterface $book_outline_storage */
$book_outline_storage = \Drupal::service('book.outline_storage');
$childrens  =  $book_outline_storage->loadBookChildren(NID);


Drupal 7 - Advice needed to accomplish the idea of embedding a view in a view Using Drupal 7 - I have a view that displays all project assignments per employee.  This view works properly and is displayed as a block on Department nodes.

I have another view that displays a page,"Department Directory".  Where the directory lists fields of such as Department Name, Address, Phone, Fax, Email.

The idea I am trying to accomplish is to have a list of fields of the department, and then have it list the employee assignments. Example:

View Page: Departments:

Finance Department

Address 123

555-555-5555

Email@mail.com

(This is where the views employee assignment block fields would be displayed)

PERSONNEL ASSIGNMENTS:

John Smith:  Complete Budget

Alan Wayer:  Generate Monthly Expense Reports

Upon doing some research, the Views field view module gave me the results I needed, however, I read that this module is resource heavy.  Is there a more efficient way that this can be accomplished?

Where did you read that Views is resource heavy?  While there is some overhead to running Views, it is generally not significant unless you are getting enormous amounts of traffic.  Your system sounds like it will be used internally, so I highly doubt that you will run into performance issues.

Views is a visual SQL query builder.  It is also the most popular module for Drupal and one of the best supported modules.  The alternative to Views is to write the SQL queries yourself, but unless you're a SQL expert this is error-prone and time consuming.  You can always do everything in Views first and then re-write some of the queries manually if you run into performance problems.


Custom 500 Error page: Is there a way to theme a fatal error? In /core/includes/errors.inc, when there is a fatal error it outputs a response with the message "The website encountered an unexpected error. Please try again later." and a back-trace, if error_level is set to verbose, and without the back-trace otherwise.

It seems like at this point, there's no way, with an event subscriber to capture the response and alter it.

Is that correct?

Or is there a way to wrap the output from line 268 of errors.inc in Drupal 8.4 with markup?

Note, there's another answer that works if it's not a fatal error, but that doesn't offer a complete solution.

Also, I looked into .htaccess and Apache ErrorDocument directive, but that was misguided. Once Apache passes off to PHP, it can no longer use that directive.  That's for real server errors.

Symfony's HttpKernel uses the event dispatcher to allow subscribers to handle exceptions and send custom responses. Only if no subscriber does so will it throw the exception further up and let it reach the global error handler. (At which point it's indeed too late to do anything else.)

Drupal already comes with such a subscriber (or rather several of them, which check particular conditions) for HTTP exceptions (These are implementors of \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface, such as NotFoundHttpException.)

If you absolutely need to intercept non-HTTP exceptions wherever they happen, and return custom responses, you can create your own subscriber (see  Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase), and give it a very low priority (< -128) to avoid interfering with the core HTTP exception subscribers.

However, architecture-wise I would suggest this is not a good way to go. If you have a controller that triggers a particular exception, then it should catch it and throw the appropriate HTTP exception instead. This also requires much, much less code than messing around with event subscribers. ;)

If need be, you can even throw a ServiceUnavailableHttpException (503) or set a custom status like new HttpException(500) if there is no class for it.

Drupal core's exception subscribers don't actually handle 5xx errors, but you can create your own that does, which would probably look something like the following:

class Custom5xxHtmlSubscriber extends HttpExceptionSubscriberBase {
  public function on5xx(GetResponseForExceptionEvent $event) {
     // Do stuff
     (new Response())->send();
  }

With a corresponding service definition like the following:

  custom5xxsubscriber:
    class: ...
    tags:
      - { name: event_subscriber }


How can I add image map on drupal? I am working on a website that is about history and there are some map for this website.

I am using map tag of HTML to select a part of image(map), how can I merge that <map> to  that uploaded by drupe

or how can I put the image address and merge map to it:

<map name="Map">
  <area shape="poly" coords="396,270,516,286,549,324,502,353,447,342,406,343,384,366,400,396,386,414,353,344,346,293,345,263,389,235,428,223,470,234,487,252,596,243" href="#">
</map>

Where is the path (address)  of files on drupal that I can link to it insted of the path that I give on top source

Try the jQuery Map Hilight module

  It enables the simple addition of mouseover highlighting of hotspots to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.

Features

provides simple interactive graphics via HTML image maps (no flash
required).
easy to use: either select the 'highlight all image maps' default
setting or simply add class="jq_maphilight" to the  tag of any
specific image map you wish to highlight.
no jquery or javascript knowledge required: plugin configuration is
handled via an admin/settings screen rather than having to enter
jquery code.
fully configurable: options for fill, fill color, fill opacity,
outline, outline color, outline opacity, outline thickness, as well
as a fade effect.
per image map settings: add image map specific options with an
additional class.


Pass parameters to Drupal to Return XML data Is there a module that allows the user to pass the parameters in POST or GET form, and Drupal will return in XML.

Like I have a view named table. table has fields named account_number and device_id. I would like to pass parameters in URL like

?view=table&account_number=123&device_id=d12

Then the Drupal would return in XML based on the searching criteria passed in URL.

Exposing Views as XML is one of the features of the Views Bonus Pack module.  You would lose your idea of using GET parameters, but you can easily build up other paths, pipe in your parameters, and get output as XML.

This is also something that the Services module can handle, but isn't as tightly coupled with views.  This module is very well documented, though.  In particular, I suggest reading the REST examples.  This is an add-on, Services Views, that may fit your needs, but I have never tried it.


What argument to use in Views that excludes the node currently being displayed? For instance: if you have a view that produces a list of titles of nodes of content type X, how can you make that list exclude the node that is currently displayed to a site visitor?

This can be done with a regular argument.

Create an argument for Node -> ID, choose Node as the validator and Node ID as the argument type. Then just tick the Exclude the argument check box. You can also choose specific node types here if you want.

Used with a block, this will list all nodes that aren't the one currently being viewed. You can then filter it further to suit your needs.


Can you use the features module to replace existing functionality Say I have an existing content type and related view on a site.  Can I install Features and convert that content type and view into a feature.

I want to start using Features for better portability.

Yes, you can. You can install features, then export all the things you want to change. Install the feature on a copy of the site you are working on, and export again, after you made the changes. (and reinstall again to that copy site, until you are satisfied).

Then copy your feature to your production site, enable, and revert the feature (revert in this case means, making sure the feature behaves like defined in the feature, hence upgrading).

Good luck!


How to create a Default Argument based on Tags I need to create a view block where users who have entered a specific tag on their personal profile page are displayed. I have the page set and it works properly. I just need to know how to set up the default argument based on context when associating that specific tag.

There are 2 types of profiles:

business (has a tag field X)
employee (has same tag field X)

Business owners have personal and a business profile access. Employees just have access to the personal profile.

For those employees that have a matching tag with the business profile I need them listed in a block as employees on that company/business profile page.

At first glance I think you should create a taxonomy view with relationship to the content type where it was use by the user, then create a contextual filter to filter the nodes where the user is the author.

I am not sure if the tags created by the user will get the uid of the user that created out of the box, but if you can control that then the view will be even simpler just a taxonomy view with a contextual filter to the field holding the uid by the login user.


Create exposed filter for Views PHP value I have created a views field using the Views PHP module. This field converts a text date string into a date stamp, and now I need to create an exposed filter for organising the rows.

I add a filter "Global: Combine fields filter", and under "CHOOSE FIELDS TO COMBINE FOR FILTERING" I select Global:PHP to select my field, but the filter doesn't work, I just get the following error...

SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax
to use near ') LIKE '2014-01-03') ))) subquery' at line 4

I need to create an exposed grouped filter for "Todays events", "Tomorrows events", "upcoming events". Is it possible to create a filter for a field rendered by views PHP?

I have searched loads of similar questions, but they have all gone unanswered. Can anyone help?

If you are using Views PHP, then you are using it's alpha or development version. Alpha tests means that maintainer expects there to be bugs and want you to report them in issue queue. Development version almost certainly have issues, that's the nature of ongoing development.

Having that said, you shouldn't attempt to use exposed filters on fields that are not in database, and cannot be readily joined and used in SQL WHERE with your data. Unless, of course, module that provides it already implemented it properly, and it appears it is not the case here. So your options are:

Forget Views PHP for dates, and use regular Date to get date fields attached to your entities, and Date views submodule for views exposed filters, or
Post a bugreport and wait for it to be fixed. Just don't really expect it to happen, as module currently lacks manpower and is seeking co-maintainers.


Got error while posting comment I'm using "Unpublish comments with keywords" action. I've just noticed a PHP error on submitting any comment.

  drupal_render() expects an array but comment_unpublish_by_keyword_action() calls it with $comment object. And we have a WSOD.

That's part of error.log

  [error] [client 127.0.0.1] PHP Fatal error:  Cannot use object of type stdClass as array in /.../includes/common.inc on line 5672, referer: http://.../comment/reply/28

any suggestions?

It looks like it's already in the issue que at drupal.org (a better place to resolve module issues then here)

Although doesn't look the patch has been merged into the latest cut release (as of time of writing this), but you can see the changes that were made here:

http://drupal.org/node/1461732#comment-5727124


How can I fallback to one field in absence of another How can I make one field show up, unless it has no value, in which case another field is shown? I want to do this on the default node view, I already know how to accomplish it in views. I'm assuming it will mean coding something in my theme, but where best to do that is a little confusing to me.

I would checkout Field formatter conditions where you can set a whole variety of conditions of one field based on if another field is empty or not. You would set these conditions in whatever display mode you are in so in the case of a node, most likely the view mode will be full or default. (e.g. admin/structure/types/manage/[MY_content_type]/display

Alternatively, you could do some custom node template theming and set conditions there such as if one field is not empty do this, else, show the other field.

<?php if (!empty($content['field_foo'])): ?>
  <?php print render($content['field_foo']); ?>
<?php else: ?>
  <?php print render($content['field_bar']); ?>
<?php endif; ?>

This assumes there is a value with field_bar so you may need to add conditions for that field too if it's empty. With per field theming, you may need to not render the general content variable as well, it just depends on the order and where things fall in the template.


hook_apachesolr_exclude not working I am using hook_apachesolr_exclude but its not working.I have created a custom field if that field is checked i want to exclude that node I wrote the given below code:

function a10_exclude_node_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
    $result_node = node_load( $entity_id );
    if( isset( $result_node->field_exclude_from_search['und'][0]['value'] ) and $result_node->field_exclude_from_search['und'][0]['value'] == 1 ){
        return TRUE;
    }
    return FALSE;
}

even when i am writing die inside the hook, hook is not invoking.Please let me know how i can check the above hook is invoking or working.I have also tried the Apache Solr Node Exclude module, when i am checking the node to exclude it does not come inside the result but when again i uncheck the node same result come there and when i uncheck the two or more nodes they do not exclude from search result.

I have fixed the problem to exclude node from Apache Solr search by installing Apache Solr Exclude Node module. To configure this module, please follow the below steps:

Enable excluding of nodes in the submission form settings fieldset in the
content type settings (e.g. admin/structure/types/page).
Find the vertical tabs fieldset "Apache Solr exclude" in the node edit form.

Check "Exclude from Apache Solr" and save.


Cannot hide Superfish sub menu on active pages I am using the horizontal NavBar style with Superfish.  When I'm in a section, I do not want its sub-navigation bar to show up.  I only want to see the sub-pages listed whenever I mouse over the parent link.

Example:  Main section is called Products, and I have a sub-section called T-Shirts.  If I click on T-Shirts or Products, it displays the sub-navigation without having to mouse over the Products link again.  The sub-navigation menu becomes persistent when in that section.  I only want to see the list of Products sub pages if I mouse over the main Products link.

I tried setting Path Class to blank instead of "active-trail," but that jacked it up.  Also tried hiding .active-trail with CSS, but no luck there either.

Wondering if this is a Drupal issue with Menu settings or a Superfish issue?

Thanks in advance for the help!

It's both. The active trail stuff has always been, and still is, a big mess, and Superfish herited the problems. You can check this thread for some information about it, but it remains unclear.


Does a user role change remove their Profile2 fields? Say I have a user role PendingArtist, and its Profile2 fields: skills and about me.

How do I change the role of a user? And does the role change delete the PendingArtist's Profile2 fields?

Edited: Don't know why I asked this, could have tried it out myself. Please ignore this question.

If you are using Profile2 in combination with Profile2 Reg Path (which you probably do or in this case - might as well use it), then you'll find two sections when you are editing Profile2 (at admin/structure/profiles/manage/profile_name_here) :

Roles - that's where you assign which roles will have the fields from Profile2;
Assign Roles During Registration - that's where you set the roles to assign to a newly registered user if user creates a profile following the path you've set.

So, in your application you'd check "PendingArtist" and "ApprovedArtist" in "Roles" section, so that your fields show up for both of those roles. Then, in "Assign Roles During Registration" section you would check only "PendingArtist", so that only PendingArtist role gets assigned to a newly created user. In the end, when the role of PendingArtist is changed to ApprovedArtist - the data entered in profile2 fields remains as entered originally.


How to get the url of a file field of a given node? $node->field_file gives me a FileFieldItemList while the first entry seems to be a FileItem.

$node->field_file->getValue() gives me an integer (I guess the file id). How can I actually get the downloadable file uri from that?

First you need to load it with the fid :

  $file = \Drupal\file\Entity\File::load($fid);

  And after :

  $imageSRC = file_create_url($file->getFileUri());


Overriding the function of a module in another module Module1 has a function named 'function1'. 'function1' is not a type of hook, but it is a menu callback, or called inside a hook.

Module2 wants to override 'function1' using all variables which are available to function1 inside Module1.

I can call function1 using module_load_include(), but I need to override the called function.

How can I achieve this?

If you want to use a different menu callback, you can implement hook_menu_alter() to change the menu callback. Suppose you want to override the menu callback Drupal defines for search, you could use the following code.

function mymodule_menu_alter(&$items) {
  if (isset($items['search'])) {
    $items['search']['page callback'] = 'mymodule_search_view';
  }
}

From mymodule_search_view() you can call search_view() without first including the file containing it, as that is done from Drupal before calling the menu callback.

Similar code could be done if the menu callback is returning a form, with the exception that, instead of changing the page callback (which probably is drupal_get_form()), you would change the page arguments to use as first argument the callback name of the function returning the form array. Rather than doing this, you should implement hook_form_alter(), and to hide the not necessary form elements with $form['element']['#access'] = FALSE', and not withunset($form['element'])`.

As for replacing a function that is called from a hook, what can be done is removing the hook implementation that calls that function, and replacing it with a different implementation. It is possible only with Drupal 7, and it must be done carefully. (I will explain why right.)
Suppose you want to change the function called in menu_node_update() (the implementation of hook_node_update()) from menu_node_save() to mymodule_node_save(). You could use the following code.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    unset($implementations['menu']);

    $implementations = array('mymodule' => group) + $implementations;
  }
}

function mymodule_node_update($node) {
  mymodule_node_save();
}

In this way, menu_node_update() would not be invoked anymore, but mymodule_node_update() would.

Normally, modules that depend from a hook implemented by another module don't check if that hook is executed; they check the module is enabled (and assume the hook is invoked), or they add that module as their dependency. Avoiding a hook is executed could cause problems to other modules which could be difficult to track. If it is really necessary to avoid a hook implemented by another module is executed, you should first check on a test site that all is working as expecting. Bear in mind that future Drupal version could break your code, and the code you are writing should be tested on future Drupal version too (when they are available).


Drupal changes language after clicking html link Based on the internationalisation module i have my site set up in two languages.

My problem is when ever i click a link which i created with html.
e.g.

link

As soon as i arrive on my page after clicking the link, the language will change.

I have tried:

link

However then drupal changes the link to:

link

resulting in a page not found.

What should i add to my html link to stay in the selected language?

I unchecked all the options on admin/config/regional/language/configure except the url
option.
Now my links link seems to work.
Credits to drupalist:
thanks


How does Drupal display the correct time for a specific time zone? I have a custom module that displays today's date and time:

t('Today: ') . date('d F - H:i')

When I change a user's time zone on their account page the time is 'magically' outputted correctly.

How does Drupal do this?

I've never seen the code itself,  but it likely uses this: http://ca3.php.net/manual/en/datetime.settimezone.php


How can I load content on the same page from a search So the idea is to load the results of the search on the same page. I was told to look into SOLR, but it looks like we have something similar to SOLR , and we just need to know how to load new page content into our drupal site. Alternate to iFrame.

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

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

and perhaps Ajax Facets:

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

There are a few more suggestions here


Why isn't my custom region showing up? I'm trying to create a new region called 'usermenu' for my theme in Zen. I've therefore added

region[usermenu] = User menu

to the mytheme.info file, added

<?php if ($logged_in): ?>

      <?php print render($page['usermenu']); ?>

<?php endif; ?>

to the mytheme.tpl.php file and added

#usermenu {
  background-color: #fff;
  height: 35px;
}

to one of my CSS files. After clearing caches multiple times, the new region is displayed correctly and I can detect it with Firebug, but it doesn't show up in the block section.

What's going wrong and how can I solve this?

I found it! It was just a stupid typo in the .info file. I should have inserted regions[usermenu] = User menu...


3 vocabulary and taxonomies in this vocabularies I want to use vocabulary and stored in separate taxonomy vocabularies to create urls, and breadcumbs; is it possible?

Drupal 7

I want to get the schema:
a vocabulary 1
   a taxonomy 1
   a taxonomy 2
b vocabulary 1
   b taxonomy 1
   b taxonomy 2
c vocabulary 1
   c taxonomy 1
   c taxonomy 2
effect to get :

User type in 1 node
a vocabulary 1
   a taxonomy 1
b vocabulary 1
   b taxonomy 2
c vocabulary 1
   c taxonomy 1

breadcrumbs (diff vocabularies )
a taxonomy 1 >> b taxonomy 1 >> c taxonomy 1

url path for taxonomy:

a taxonomy 1 / b taxonomy 1 / c taxonomy 1 /

Your question is not well-asked but this is the answer:

Yes, you can have multiple vocabularies, multiple taxonomy terms in these vocabularies and also multiple child-terms in these taxonomy terms. It's one of the core functionality of Drupal.
Yes, the breadcrumbs can show the taxonomy hierarchy as you wanted but it depends on  the theme you use.
Yes, it's possible to show taxonomy terms in url with Pathauto module.


node_object_prepare causes profile page for non-admin users When I'm calling node_object_prepare in a module to create a user profile type node Drupal 6 kicks the user out unless they have admin permissions.

How can I make node_object_prepare run regardless of the users role?

thank you,
George

I solved this by ripping the guts out of the node_object_prepare function, pasting it into the module and editing it appropriately so it served my purpose.


l() is not being called correctly in menu.inc I had been getting this error message:

  PHP Fatal error:  Unsupported operand types in /var/www/www.ruv.is/pressflow/includes/common.inc on line 1588

So I did a backtrace and this is what it returned:

    array (
      'file' => 'pressflow/includes/menu.inc',
      'line' => 1614,
      'function' => 'l',
    )

It points to this function:

/**
 * Get the breadcrumb for the current page, as determined by the active trail.
 */
function menu_get_active_breadcrumb() {
  $breadcrumb = array();

  // No breadcrumb for the front page.
  if (drupal_is_front_page()) {
    return $breadcrumb;
  }

  $item = menu_get_item();
  if ($item && $item['access']) {
    $active_trail = menu_get_active_trail();

    foreach ($active_trail as $parent) {
      $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);  // line 1614
    }
    $end = end($active_trail);

    // Don't show a link to the current page in the breadcrumb trail.
    if ($item['href'] == $end['href'] || ($item['type'] == MENU_DEFAULT_LOCAL_TASK && $end['href'] != '<front>')) {
      array_pop($breadcrumb);
    }
  }
  return $breadcrumb;
}

Or more specifically, this line:

$breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);

I'm assuming there is a contributed module that is causing this, but it is happening on several pages that don't use any menu altering module. Do you have any idea on how to troubleshoot this?

I can't reproduce this myself, so my only chance of debugging is on a hight traffic live site.

According to my experience, this happens when the third argument passes to l() is not an array and you are using PHP 5.3. See http://api.drupal.org/api/drupal/includes%21common.inc/function/l/6 as to how the third parameter $options is being used.

Then it is time dwelve into what is causing your $parent['localized_options'] not to be an array.


Empty node workflow state on node after programmatically saving I have saved a node programmatically, in the following way:

  $node_storage = \Drupal::entityManager()->getStorage('node');
  foreach ($entity_ids as $id) {
    $node = $node_storage->load($id);
    if (!$node) {
      continue;
    }
    $node->set('field_tags', $new_tid);
    $node->save();

After saving the node I am trying to edit it and I am getting the follow error upon submit.

InvalidArgumentException: The state '' does not exist in workflow 'draft' in Drupal\workflows\Entity\Workflow->getState()

I believe that this means that my node has no state.

How could I set the node's state?

There's a code for creating a node and indicating its status, maybe it would help:

<?php
// add node properties
$newNode = (object) NULL;
$newNode->type = '{NODE_TYPE}';
$newNode->title = '{NODE_TITLE}'
$newNode->uid = {USER_ID};
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;

// add CCK field data
$newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
$newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

// save node
node_save($newNode);
?>


How can i move a secondary level Tab to the parent Tabs I use the Profile2 module and i get in the user edit view the secondary tabs with the extra profile information. How can i move it to the parent tabs and hide the child tabs: "Edit | Info".

Well, for each page, the type of tab is decided my a parameter 'type'. So you can do a hook_menu_alter() on the specific page to change that. Please have a look at the "Rendering Menu Items As Tabs" section of the documentation for hook_menu() to gain idea of what options do what.


How to pass node queue id in views contextual filters I a list of node queues and nodes associated with them. Now I have created a block using views. This block should list the nodes in a specific node queue based on the node queue id.

I have used node id in contextual filters, but not sure how to use node queue's id in contextual filter.

Any help would be widely appreciated.

You can give a try to nodequeue_extras module

  Provides 2 pieces of helper functionality specific to Nodequeue and Views:

  Contextual nodequeue edit links for views that include a nodequeue relationship.
  A special Views nodequeue relationship and subqueue argument that let you build views based on a subqueue without requiring that all result nodes in the view exist in the subqueue.


Set another page.tpl.php if a parameter is set i want to use another page.tpl.php file, if die fb parameter is set.
The File is located in my theme folder and has the name "page-fb.tpl.php"

My Function in template.php

function THEMENAME_preprocess_page(&$vars) {
/** Facebook Output */
    if ( isset($_GET['fb']) && $_GET['fb'] == 1 ) {
        $vars['template_file'][] = 'page-fb';
    }
}

The function is called, but the new page-fb.tpl.php is not loaded.
I'm doing all of this on Drupal 7.

Any advices?

Rename page-fb.tpl.php to page--fb.tpl.php and then modify your code to use $vars['theme_hook_suggestions'][] = 'page__fb'; instead of what you got currently. For further information you can check out the Drupal 7 Template Suggestions page.


Correct usage of hook_user_login and hook_user_presave for saving data to user I have a custom module that syncs LDAP-data to custom user fields (every 24 hours, depending on when the user logs in). Everything seems to be working, but I'm not an expert on PHP and Drupal hooks so I want to be sure I'm not doing anything silly.

My understanding is that when user account is saved in hook_user_login, hook_user_presave is run and the values are saved (values are located in the $edit variable). Am I saving the values correctly? Have I missed a critical check that could lead to errors?

Here's my code:

// runs everytime a user logs in, checks if ldap attributes need to be updated
function company_ldap_user_login(&$edit, $account) {

      // If the user is user 1 or guest, then do nothing
      if ($account->uid <= 1) {
        return;
      }

      // don't update data if it's less than 24 hours ago
      if (isset($account->data->ldap_sync) && $account->data->ldap_sync < time() - 3600 * 24) {
        return;
      } else {

        // load custom LDAP configuration
        require_once('custom_ldap.inc');

        $ldap = new ldap();

        // get LDAP data
        $data = $ldap->get_info();

        // do nothing, since user does not exist in LDAP
        if($data["count"] == 0)
        {
          return;
        }

        $data = $data[0];

        $first_name = trim($data["givenname"][0]);
        $last_name = trim($data["sn"][0]);
        $fullname = "$first_name $last_name";
        unset($data['mailaddresses']['count']);

        // load the user that has logged in
        $account = user_load($account->uid);

        // save LDAP data to an array
        $edits = array(
          'first_name' => $first_name,
          'last_name' => $last_name,
          'fullname' => $fullname,
          'emails' => $data['mailaddresses'],
          'ldap_sync' => time(),
        );

        // save the user with the data provided above
        user_save($account, $edits, 'company_ldap');

      }
}

// when user account is being saved or updated
function company_ldap_user_presave(&$edit, $account, $category) {

  // make sure to only update ldap-attributes when needed
  if ($category == 'company_ldap') {

    // if there is no data to save, don't save
    if (isset($edit['fullname'])) {

      // save ldap-data to custom user fields
      $edit['field_company_fullname'][LANGUAGE_NONE][0]['value'] = $edit['fullname'];
      $edit['field_company_first_name'][LANGUAGE_NONE][0]['value'] = $edit['first_name'];
      $edit['field_company_last_name'][LANGUAGE_NONE][0]['value'] = $edit['last_name'];

      // loop through all mail addresses and add them to the custom user field
      foreach ($edit['emails'] as $i => $email ) {
        $edit['field_company_emails'][LANGUAGE_NONE][$i]['value'] = $email;
      }

      // save serialized data of last ldap sync to users.data table
      $edit['data']['ldap_sync'] = $edit['ldap_sync'];
    }

  }

}

IMO you don't need the implementation of the hook_user_presave(), I see that in the implementation of hook_user_login() you have all the values that you need to create the user.


Remove a block in preprocess I'm working on a Drupal 6 site made by other people, and I need to remove some block on the homepage for my language only.

I'm trying to use a Context and, by use of hook_context_init(), check if the context is active and remove the undesired blocks.

But i have a problem: How can I remove block in a hook function?

I hope my question is clear.

I don't want to hide the blocks with CSS because of the dirty markup..

[RESOLVED]
I did a preprocess like:

function wfp_homepage_context_preprocess_block(&$vars, $hook) {
    $to_delete = array('block_delta_1', 'block_delta_2')

    if(in_array($vars['block']->delta , $to_delete)){
        $vars['template_files'][0] = 'block-empty';
    }
}

and i add an empty block-empty.tpl.php in my theme.

You can use hook_page_alter() to do this. For example, if you wanted to remove the system navigation block from the "sidebar_first" region, you would do something like this:

function MYMODULE_page_alter(&$page) {
  if ($my_condition) {
    $region_name = 'sidebar_first';
    $block_name = 'system_navigation';

    if (isset($page[$region_name][$block_name])) {
      $page[$region_name][$block_name]['#access'] = FALSE;
    }
  }
}


Form API file upload field default value implementation using AJAX/AHAH Apologies for the long explanation.  I have a form built using the From API that is used as a profile for users. It allows users to upload a CV/resume type file for themselves and it is mandatory to upload a file or the user cannot complete the form.

Uploading and saving the files are no problem, but I run into problems when the user tries to update their form.  The file input type in the Form API doesn't have a #default_value option (understandably) which means that when the user comes to edit the form, there are two problems.

The first is that it shows a blank file upload field and the user is expected to upload a file again (as the field is mandatory).  This is confusing for the user and means that more than one file can be assigned to a user.  The second is that the user does not have an option to remove their file and add a new one to replace it.

What I would like to do is write a function that checks to see if the form is being accessed by a logged in user, checks if that user has a file associated with them and displays the field appropriately.  If a file exists, display the name of the file and a link to remove it instead of showing the file upload field.

I could do most of this no problem, but the extra part I would like and can't do is for the "Remove file" link to be an AJAX call that would delete the user's file and then display the file upload field dynamically.  Has anyone done something like this before?

Unfortunately, depsite the vast amount of answers posted to this question, there was no easy way to do this.  In the end, I had to check when the form was being displayed if the form already had content, and if so, if the form had a file attached.  I then displayed a different value rather than the form field and made a validation workaround due to the fact that the file upload was mandatory.

My advice to others with similar problems: if you're using this as an user profile field, avoid FAPI and stick to CCK and Content Profile.  Although it can be a pain sometimes, all of this functionality is already taken care of.


How to output child links based on the current page When landing on a page which has a menu item that is a parent to other pages menu items, I would like to be able to show a list of those child menu items. I am using the following code.

$trail = menu_get_active_trail();
menu_build_tree('main-menu', array(
  'expanded' => array($trail[1]['mlid'])
));

However, the returned array looks like this (with a lot of unnecessary removed).

array
'49950 PKY Truck Beauty 312' =>
array
  'link' => &
    array
      'menu_name' => string 'main-menu' (length=9)
      'mlid' => string '312' (length=3)
      'plid' => string '311' (length=3)
  'below' =>
    array
      '49952 Seminars 314' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '314' (length=3)
              'plid' => string '311' (length=3)
      '50000 HDMA Breakfast 316' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '316' (length=3)
              'plid' => string '311' (length=3)
      '50000 MATS Concert 315' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '315' (length=3)
              'plid' => string '311' (length=3)

Notice how 314, 315, and 316 are 'below' 312? They are siblings in my menu structure, and that seems to be verified by each one having the same value for plid (311).  Obviously I can fix this by passing the array through another function, but I can't help but think I'm just missing something.

Just wanted to follow-up. I came back to this question and found the following: https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal which is exactly what I needed.

The code, copied from the above-mentioned link and modified to fit my needs (mainly to use the current path to build the menu tree from, rather than using a hard-coded value:

$parent = menu_link_get_preferred($_GET['q']);
$parameters = array(
  'active_trail' => array($parent['plid']),
  'only_active_trail' => FALSE,
  'min_depth' => $parent['depth']+1,
  'max_depth' => $parent['depth']+1,
  'conditions' => array('plid' => $parent['mlid']),
);

$children = menu_build_tree($parent['menu_name'], $parameters);

return '
' . drupal_render(menu_tree_output($children)) . '
';


Show users a different page (depending on their role) after logging in In my site I have two different roles for users named recruiter and candidate. when they register their account they can choose their role (recruiter or candidate). And when they login my site I will check user is recruiter or candidate. after this check I will show them a different page (recruiter page and candidate page).

How to proceed with this?

Have a look at the Front Page module. Module description:

  The Front Page module allows for customised home pages dependant on
  role. The pages can be of the following types:

  Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
  Redirect - Allows you to redirect users to a local or remote URL.
  Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
  Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

One of the options should fit your need.


Modifying a views organic groups exposed filter I have a view with an exposed filter of organic group id's (ie: gid). I wanted to convert it to be a dropdown with the actual group name. I did so with a form alter. The filter works fine, however I'm having an issue with the filter when trying to view all groups. I tried adding 'ALL' to the dropdown, but that doesn't match a particular gid, so it doesn't work. How can I fix my code to allow content of all groups to show?

/**
 *  Implements hook_form_alter().
 */
function tma_views_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] === 'views-exposed-form-event-list-page') {
    $form['field_event_type_tid']['#type'] = 'hidden';
  }
  elseif ($form['#id'] === 'views-exposed-form-page-event-calendar-page') {
    $form['og_group_ref_target_id'] = array(
      '#type' => 'select',
      '#options' => tma_views_get_chapters_list(),
      '#default_value' => 'ALL',
    );
  }
}

/*
 * Retrieves an associated array list of all Chapter nodes
 * return - a list of nids
 */
function tma_views_get_chapters_list() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'chapter');
  $results = $query->execute();
  foreach ($results['node'] as $node) {
    $nids[] = $node->nid;
  }
  $nodes = node_load_multiple($nids);
  $options['ALL'] = 'Select Chapter';
  foreach ($nodes as $node) {
    $options[$node->nid] = $node->title;
  }
  return $options;
}

EDIT:
One more thing to note: when no filter is set at all (for the organic group filter), I get a drupal error message on the screen:

An illegal choice has been detected. Please contact the site administrator.

I obviously would like to be able to fix that as well.

It would seem to me that you would want to modify that filter in the Views UI. Is required checked? Also, a standard practice that I've seen for Drupal select is having all actually keyed with _none rather than ALL.


Creating a node using Services 6.3 REST I am trying to create a node using the rest service. I am hitting /myendpoint/node using a post. My header is application/json. I am not sure what I need to post as the data.

Something along the lines of this, &node[title]=testnode&node[type]=story&node[field_test][0][value]=testtting

Also, if you are ever unaware of what to send, just look at the tests.


Restrict text format use to a particular node/edit URL I have a custom text format that i use in the Wysiwyg profile with ckeditor. Using Drupal 7.
I want to restrict that text format use to a certain node/edit URL.

What would be the best option to achieve that either Programmatically or using custom modules?

Any advise is appreciated!

You can't achieve that in config, since text formats are configured per field instance, but not as granular as for to get to the node level.

You'll need too implement a hook_form_alter(), and then check the url to find out if you want to allow the format or not. Something like this:

function mymodule_form_alter($form, &$form_state, $form_id) {
  if ($form_id == 'node_type_form_to_alter' && (current_path() == 'node/%nid/edit')) {
    // Enforce desired text_format here, by altering $form array.
  }
}

That's what I would do for that case. You can take the opposite approach, and implement the same form_alter, but instead of enforcing it on a particular URL, just making sure that it's not available unless the url is the one you want to target.

Hope it helps.

EDIT: To enforce the format, you need to find the field you want to alter, inside the $form array. Wysiwyg fields use the 'text_format' when declaring the field through Form API (example here).

So, you have to find the desired field, and change the '#format' property (as in the example), to the machine name of the text format you want to use. Also, you'll see a 'format' propery in the element array. You might want to change that too if you want avoid certain formats from appearing in the dropdown widget.

I recommend you use xdebug to see the structure of the $form variable inside the hook_form_alter() implementation. Alternatively, enable the devel module, and stick a "dpm($form);" in that function, to render the structure on screen when visiting the node form.


Views Filter on a subquery custom field I've defined a global table, like this:

  $data['custom_test']['table']['group'] = t('Custom: Test');
  $data['custom_test']['table']['join'] = array(
    // #global is a special flag which let's a table appear all the time.
    '#global' => array(),
  );

Next I added a custom field:

  $data['custom_test']['test'] = array(
    'title' => t('Test'),
    'help' => t('Show test field'),
    'field' => array(
      'handler' => 'custom_test_handler_test_field',
    ),

With this I could now make a field handler; This field handler adds a subquery:

$this->query->add_field(NULL, "(QUERY)", '(FIELD)');

And with this I can output the result.

However, when I add a filter, (using a default filter handler), the query looks something like:

AND (.test BETWEEN '20' AND '30') ))

So what it does is that it tries to prefix a table, however there are no tables (since it's a subquery).

Is there someway I can fix this by configuration, without having to say build my own filter?

I ended up creating a filter class, since I use a subquery I needed to use HAVING rather than BETWEEN.


Can't use core/jquery I created my libraries.yml as shown in Drupal 8 CSS/JS.

.libraries.yml

 general:
  version: 1.x
  css:
    theme:
      css/materialize-custom.css: {}
      css/main.css: {}
  js:
    js/materialize.min.js: {}
    js/main.js: {}
  dependencies:
    - core/jquery

My problem is that my main.js need jQuery to work.

main.js

$( document ).ready(function() {
  // Initialize collapse button
    $(".button-collapse").sideNav();
});

I get this error.

I don't understand why I have this error. What is wrong with my code?

Drupal doesn't provide you with an alias for jQuery, because these days it'll inevitably interfere with another library sometime later.

If you want $ as an alias, you'll need to create it yourself:

(function($) {
  // your code...
})(jQuery);


Displaying a Value while linking a Key with the Linked Field Module I am using the linked field module to try to display a particular field as a link on a content page (I am not working within a View).  The field is a select list with associated urls in the key.  For example, the Value "Accounting Department" may have a key of "/drupal/accounting".  I want the link to show "Accounting Department" but map the link to what is in the key.  If I map to the field with this module, it tries to go to "/drupal/Accounting Department".  Has anyone else attempted something like this or is there another module that will allow this?

You need to configure the "token" view mode for the content type in question.

First, ensure you're set up to configure the "tokens" view mode separately from your other view modes.

Click to go to the "default" view mode:

Near the bottom, click "Custom display settings" and check "tokens", then save.

Now you will see "Tokens" in your list of view modes to configure:

Go to that page, find the field that contains the key you want and, in the drop-down in the format column, change it to "key".


How do I create new content type with editable fields? I want to create another content type similar to the basic page. I've designed a simple html layout with a block of copy on the left hand side and an image with a caption floated next to it on the right hand side.

I want to be able to add this as a template to the Drupal UI so that a user can pick this template and enter their copy, choose/upload an image, enter an image caption and possibly show a widget below the content based on what the page is about.

How would I go about configuring this so I can add this page template as a content type into the Drupal UI?

Based upon the mentioned requirement, to me it seems either of the following situations:

For Drupal 7:

Theming the node add page: page--node--add--[content type].tpl.php
Theming the node edit page: page--node--edit--[content type].tpl.php

For Drupal 6:

Theming the node add page: page-node-add-[content type].tpl.php
Theming the node edit page: page-node-edit-[content type].tpl.php

More info about the same you can get from here:
https://drupal.org/node/1092122
https://drupal.org/node/1089656
https://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/7


How to force a specific user in the Author textfield in Rules Create Entity I created a rule which creates an entity. I would like that every created entity has a specific author.

for the moment, it's look like I can only put the currently logged-in user in that textfield.

You will have to fetch a user entity first. There's an action called fetch entity by id, which will allow you to select user as type and specify the user id.

At the bottom you can assign label and machine name for the variable that will be made available.

make sure to do the fetching before creating the new entity, else this variable won't be available.


Problems with permanent caching My requirement is to update some params in the script for a some specific nodes. If a set of nodes is attached to an X content type, it should take some params in a script. For this purpose I am running a cron job every 10 min as new contents can be attached to that X content type. In this cron job, I am fetching all nodes belonging to X content type and also from these nodes, I am getting set of nodes attached to each X node. I am storing the corresponding param value for a node in the cache using the function cache_set().

cache_set(node id, X node id, MY_CACHE_NAME, CACHE_PERMANENT)

But the problem is that some nodes are not taking the param sometimes. I think that it is setting the cache, but in the cache table something wrong is happening. But when I run 3 or 4 times the nodes which were not taking param started taking. I am not getting what is happening that cache table.

I am not getting where it is writing to the database. How can we test the problems related to these caching?

I am clearing the corresponding MYCACHE  before every cron runs.

hook_cron {
  cache_clear_all('*', MY_CACHE, TRUE);
  take_params();
}

What am I doing wrong?

Your use of the functions cache_set() and cache_clear_all() does not look right.

First let us look at cache_set(). It stores some serialized data in some persistent cache bin.

Its arguments are:

$cid - a string that identifies the stored data.  The same string is stored in the $cid field in the database table named by the $bin argument.
$data - the data to cache.  This is stored in the data field identified by $bin and $cid, usually as a serialized object.
$bin - The name (a string)  of the cache bin to use.  This corresponds to a database table with that name.  It should either be 'cache' or start with the string 'cache_'.
$expire - when should the item expire. If set to CACHE_PERMANENT, the item can only be expired by calling cache_clear_all().

You want to cache some parameters attached to some node.  To do that, you may use:

$cid = 'mymodule:node_' . $nid;
$data = ...; // Set it to hold whatever object you want to cache.
$bin = 'cache';
cache_set($cid, $data, $bin, CACHE_PERMANENT);

Note that $bin need to be set to the name of one of the bins (i.e. cache database tables) that are already defined.

Now, to clear out this particular item, you need to call cache_clear_all() with the same $cid and $bin as was you to set the cache.  The final parameter to cache_clear_all() can indicate that $cid is a wildcard (in your case, it is not). I.e.:

cache_clear_all($cid, $bin, FALSE);


Is there a module or configuration that logs PHP mail errors? On shared hosting. We're having strange mail problems... mails do not get sent to various domains or are delayed. It seems to happen more in Webforms than in Notify_message actions in Rules.

Is there a way to log the PHP mail() error messages without hacking the MimeMail module? The Drupal log only shows that there was an error... nothing more specific.

Have a look at maillog and Mail Logger. They both log all mail activity handled via drupal_mail. See what they have to offer as far as mail errors go.


How to create a view of hierarchical taxonomy terms and their nodes? I'd like to create an HTML sitemap viewable by a human. I mention that I'd like to keep the hierarchy (tree structure of categories with subcategories) like the following:

- TERM_A
  - Node a
  - Node b
- TERM B
  - TERM_B1
    - Node c
    - Node d
  - TERM_B2
    - Node e
    - Node f

For example, is it possible to display the results as grouped categories and sub-categories, by managing the order or results (relate to taxonomy term, sort by term weight and nesting level)?

You can do it using the grouping fields feature inside Views.

Create Views listing your nodes (titles), add a Field showing terms they're tagged with (sub-term).

Then add a Relationship for that same Field (the Taxonomy term reference Field). Add another Relationship to introduce Parent term, use the first Relationship here.

Now add another Term name Field and set it to use the second Relationship, this way the Field will show the first level Taxonomy hierarchy for a node.

Now edit your Format settings and set the Grouping field Nr.1 to use the Parent Field, and set the Grouping field Nr.2 the usual (sub-term) Field.

If you need further control of the output you can overwrite to change HTML, and use CSS to emphasize the hierarchy visually.


Is it possible to hide a menu item using menu blocks in context based on user roles? I am using the Menu block module to create menu blocks and have them attached to the menu in Drupal 7.  I am also using the Context module to display the menu and items on different pages.

I have a certain menu item that I want only to be visible with certain user roles.  I have created a context for the page (based on "path") that linked to the menu item and have selected the administrator role as a condition and selected require both (path and user role).

Using a non-admin test user I can still see the menu item (It should be hidden).  When I click on it the page content doesn't show but the menu item is still visible to the user.

How do I use Context to hide the menu item as well.

Thanks in advance

you could hide it programatically

function YOURTEMPLATE_menu_alter(&$items) {

 global $user;

  if (in_array('anonymous user', $user->roles)) {
  unset($items['user/%user/profile']);   // example link
  }

 }

This will hide that menu item for anonymous users.


How can I generate custom XML for a SOAP client? Im building a SOAP client that consumes from a SOAP web services in a Drupal 8 module.

I need to generate this final XML:

$inpunt_data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qual="http://websoap.com/">

                           <soapenv:Header/>

                           <soapenv:Body>

                              <qual:myMethod>

                                 <!--Optional:-->

                                 <qual:xmlMethod><![CDATA[

                                <Tag>
                                </Tag>
                               </qual:Method>';

How do I generate soapenv headers?

I'm using simplexml:

$getXML = new SimpleXMLElement($input_data);
             $urlTarifa = 'http://soapurl.com?wsdl';
             $client = new SoapClient($urlTarifa);

This is how I've done it:

some-feed.html.twig

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <atom:link href="{{ some_variable_set_in_preprocess }}" rel="self" type="application/rss+xml"/>
      /* -- rest of feed omitted */
  </channel>
</rss>

Then hook_theme() to register the template:

function hook_theme() {
  return [
    'some_feed' => [
      'render element' => 'elements',
      'template' => 'some-feed',
    ],
  ];
}

You can then generate a response with that theme:

$build = [
  '#theme' => 'some_feed',
];

$response = new \Symfony\Component\HttpFoundation\Response();
$xml = \Drupal::service('renderer')->renderRoot($build);
$response->setContent($xml);
$response->headers->set('Content-Type', 'text/xml');

You now have a Response object to work with. Depending on where you are working, you can return that, or set it as a response.