Elegant way to retrieve nodes by content type? Of course I can do something like:

$results = db_query("SELECT * FROM {node} WHERE type = '%s'", $content_type);

while ($node = db_fetch_object($results)) {
    // ...
}

But is there a more elegant way maybe?

You can just use the Views module and add a filter on the content type.


Visibility rules if field is filled in We made a visibility rule to display a field when a second field has been filled, and display another field when the second field is empty.
It works well, but since we updated Ctools and some Drupal modules, it gives false output.

What I did is:

Adding a field with a visibility rule to display the field based on another field value
(I left the value empty to display the field when it is empty.)
Duplicating that field, and adding the same visibility rule, for which I then selected "Reverse" to display the field when it contains any value

The problem is that the visibility rule doesn't apply for the case when the field is empty, but it works well when the field is not empty, even if I disabled the second rule.

How does the plugin (for the visibility rule) know about empty and non empty fields?

I know that it could be solved with PHP code, but I need to know what I am doing wrong.

Probably it is the difference between if field['und][0]['value'] is set or not. Even if field['und][0]['value'] is empty, it's different with not instancied field.

Try a default value on this field and add an other visibility condition on this default value


Is there a reason I need to unset CSS files provided by contrib modules if I have CSS aggregation enabled? As this question makes clear, stylesheets provided by modules can be unset.  Some themes, such as Adaptivetheme 3.x, also provide a GUI for unsetting the stylesheets provided by modules.  My question is this: if I have CSS aggregation enabled, is there any benefit to unsetting CSS files of modules I do not use?  Or is Drupal's CSS aggregation sufficiently efficient that I do not need to bother with unsetting any files?

As I understand it unsetting CSS stylesheets is to:

reduce the final size of the aggregrated css file(s)
more easily override / implement custom CSS rules

Beyond these 2 reasons, your site probably "uses" all css files defined in the modules you have activated. Unless you need the performance boost from cutting out the extra bloat of X css files, or want to hand-theme certain things completely .... I see little need to unset style sheets.

I've only unset style sheets once .... and it's probably because i'm not making use of drupals multisite capabability where i have 1 site resolving from 2 url domains: http://www.foo.com and https://secure.webhost.com/foo.com/page depending on the domain I use a hook to unset/set a CSS files that fixes image paths in CSS when i'm on a secure url.


Set parameter for internal or external traffic based on IP We want to block external traffic in Google Tag Manager and I am trying to do something like shown here.

I created this:

/**
 * Implements hook_init().
 */
function myfunction_init() {

  $internal_ips = [
    'x.x.x.x',
    'x.x.x.x',
  ];

  $internal_traffic = 'no';
  if (in_array(ip_address(), $internal_ips)) {
    $internal_traffic = 'yes';
  }

  $data_layer = [
    '#type' => 'markup',
    '#tag' => 'script',
    '#markup' => "<script>
                    var dataLayer = [];
                    dataLayer.push({ 'internalTraffic': '$internal_traffic'});
                  </script>",
    '#weight' => 100 ,
  ];

  drupal_add_html_head($data_layer, 'data-layer');
}

It would work but the problem is I have cached pages so this will not be correct.  I did try hook_boot but that did not work because drupal_add_html_head() is not a valid function (I'm assuming it wasn't initialized yet).

To request the uncached client IP I recommend providing a JSON endpoint that has   drupal_page_is_cacheable(FALSE) set. Then get the IP from there with an Ajax request and do whatever you need to do now with JavaScript.

First, provide a route.

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['myip'] = [
    'page callback'   => '_MYMODULE_myip_callback',
    'access callback' => TRUE,
  ];

  return $items;
}

Second, provide the endpoint that returns the result of the IP comparison. (Bonus points for getting the internal IPs from an admin settings form. More bonus points for checking the user role as well.)

/**
 * Callback to provide an uncached JSON response.
 */
function _MYMODULE_myip_callback() {

  $internal_ips = [
    'x.x.x.x',
    'x.x.x.x',
  ];

  $data = [
    'internal_ip' => in_array(ip_address(), $internal_ips) ? TRUE : FALSE,
  ];

  // Mark this page as being uncacheable.
  drupal_page_is_cacheable(FALSE);

  drupal_json_output($data);
}

Third, add the JS.

/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/scripts.js', ['scope' => 'footer']);
}

Fourth, the Ajax request and DOM manipulation in the JS file.

(function ($, Drupal) {
  'use strict';
  Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {

      $.getJSON('/myip', function (result) {

        if (result.internal_ip) {
          function_to_call_if_internal_ip();
        }
      });

      var function_to_call_if_internal_ip = function () {

        // Do whatever you need to do.
        // ...

      };

    }
  };
})(jQuery, Drupal);

Note

One thing to mention. I adjusted the sample to follow your sample flow "do something if internal IP". In the original snippet I do the opposite "only add Google Tag Manager if external IP" to never have the tag manager script added at all if the request comes from an internal IP and it works just fine.

$.getJSON('/myip', function (result) {

  if (result.add_scripts_by_client_ip && result.add_scripts_by_user && result.add_scripts_by_host) {
    _add_google_tag_manager('GTM-XXXXX');
  }
});

var _add_google_tag_manager = function (gtmid) {

  if (!!gtmid && gtmid !== null && gtmid !== '') {

    $('html').once('myBehavior').each(function () {
      $('body').prepend('');
      $('head').append("");
    });
  }
};

If you use Varnish, Memchached or some other server-side caching strategy, don't forget to exclude /myip from them.


Anonymous view while developing without quit maintenance mode I have a live website with 200 active users per hour, I put the site in maintenance mode for make some changes. You know the admin view is pretty different than the anonymous view of my website or other user roles views.

I need to know how to see how the anonymous and other roles will see my website after the changes I did "for see if everything is ok". I know you are going to answer "use local enviroment and then use backup and migrate" well I already use it but if preffer to ensure that everything is ok in the live site before take off the maintenance mode.

Thanks for your advice.

This is exactly what the Maintenance Exempt module was built for. From the project description:

  This D7+ module allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.

  Exemptions can be added by:

  Specifying a list of IP addresses (individually or by CIDR notation)
  Specifying a query string variable


Last hook to be called after entity save? Of the various hooks called during the entity save process, which is the very last to be called?

Is there a way to trigger an event after the entity has been created, after all fields have been saved, after caches updated, etc? So that, when a user saves the update form, this action is the very last thing to happen before the redirect page is loaded?

If it's not strictly part of the save process, that's fine. What matters is: it's called after everything to do with an entity being saved. If there's a way of hooking some form function and reliably identifying from the data in there that a save process has been completed, or defining some callback, that's fine by me.

(context: I've got a problem where field caches are being created that caused newly created nodes, and other fieldable entity types, to load as if they are blank and as if they have no field data - but all attempts so far using cache_get and cache_clear_all don't find the cache - it's being created late in the process. So I'm looking for the latest possible hook which will definitely get it)

(Relevant info: hook_entity_postsave doesn't exist, and is one of those core issues that got stuck months and months ago)

The various wrapper functions (node_save(), user_save(), etc.) are responsible for resetting the entity cache after the save method has been invoked on an entity controller.

If you take the user_save() function as an example, this cache reset happens after the function invokes the various entity hooks (same goes for node_load())

That in mind, I think the question then becomes "What is the last hook to be called during an entity save"?...and the answer is hook_entity_update() / hook_entity_insert(). But, they are called before the cache is reset (for obvious reasons).

The entity_save() method just invokes the save handler for that particular entity type, and doesn't invoke any hooks of its own, so really your only options are:

Roll your own entity controller for the various entities you need to intercept, changing the save() method to invoke a hook after the cache has been cleared.
Hack/patch the existing entity controllers with the same code.

Neither are particularly attractive options but unless there's a solution available at a higher level that I'm not seeing, I don't think you've got much choice.


No visible files in DIR (site/default/files) throught the IMCE I have a problem with IMCE manager:

I upload my files throught CONTENT -> FILES, all files are visible there (sites/default/files).
I check (Home » Administration » Configuration » Media » IMCE) for sites/default/files path and permissions. It's all OK.
But when I use IMCE "Add Link" button to link an uploaded file, and choose to pick it up from server... I see nothing (except 0 files using 0 bytes of unlimited quota) in file browser. Navigation tab also shows: /sites/default/files

Files folder has 0777.
Uploaded files can be also opened by ULR.

Thanks!

Filefield sources applies a filter to the file list. It won't list files that can not be used in file field.

https://drupal.org/node/1099994

If you are using File Field sources that's your problem.


process form in popup window I have a custom module in Drupal and I also have a custom table for storing the details of seminars, such as name, description, date and location.

I am showing the names of the seminars in a left sidebar block; when the user clicks on a seminar name, I want to show its other details (description, location, etc.) in a form (which include a "Submit" button) in a popup modal box.

When the user clicks on the submit button, the user will be joined in the seminar (inserted into database).

How can I use JavaScript/AJAX for this scenario and process form in popup, without refreshing the page?

I have included the jQuery library in my module file using drupal_add_js(); I also installed the Chaos Tools Suite module.

I would suggest you to have a look at Chaos tools suite; the module brings an example for a modal form inside a modal window right with it (AJAX example).
It should be not to hard to integrate that, if you're already working on a custom module.

All I've said is valid for Drupal 6; I haven't looked into cTools in Drupal 7.


Auto login to LinkedIn I have installed HybridAuth module. I can login from my website using LinkedIn. But my question is, how can I login automatically into LinkedIn when I login from my website using LinkedIn login?

I have gone though various APIs but could not get proper information.

Got something closely related to your case and I won't say this is not possible, you can have some workaround by following these threads:

Login to Drupal using LinkedIn

This feature is not available right now, to login into Linkedin while using its credential on your site. But it seems that, this thread is in knowledge of Linkedin Officials as well and there may be some work is going on to provide you create app feature just like Facebook.

Here is something to elaborate the same:

http://developer.linkedin.com/forum/how-create-linkedin-application-tripit-or-slideshare


Panels for Node Types I need to control the layout a particular, pre-existing node type using panels.  However unless I'm not mistaken, creating a panel for a node type allows you to manipulate the layout for every node of that type, whereas what I want is a default panels layout - which I can change if I need to - but free reign over adding new content elements for each node I create (of that type).

I could override the nodes individually by entering the un-aliased path for each node, e.g node/123.  However it's not very clean or intuitive, has to be done manually for each node, and I lose some useful information in my template pre-processing.

I could use the panels_node module, but this creates a new node type called "Panel", and while what I want is similar, the node type already exists - and I'd need the option of creating a new node type that uses panels later.

...or am I missing something really obvious?

Any help would be appreciated.

(Drupal 7, Panels 3)

If I clearly understand your question You want to create something like this:

Different layout based on Node Type

Go to Structure --> Pages and enable Node Template (/node/%node)
There should be only one variant - go to Selection Rule. From drop down menu choose Node Type: and then choose Variant for Node Type being viewed.
Create as many varants as you need for any Node Type


Does "Maximum image resolution" resize before saving on the site? I am building a site using Drupal 7, in which users can upload content and images.

When I set the "Maximum image resolution" (on the core image field settings) to be, for example -  800x600.

Is that mean that the pictures will first be resized and weight reduced, and only then will be saved on my Drupal site?

I don't want to have many pictures that weight a lot on my server. I prefer to save only the images that has been resized, in order to have more space on my server.

that setting means that you can't upload an image with max resolution of 800x600. If you upload an images with a size more than that set, it will be not imported and drupal will return an error alter.


Module listing page leading to php timeout I am noticing that when I open the Modules listing page - admin/modules/ it leads to php timeout.
There was no problem in listing out all the modules with drush. On opening the Modules listing Form in the core.
\Drupal\system\Form\ModulesListForm

I traced the problem to the following loop in the form.
$form['modules']['#tree'] = TRUE;
foreach ($modules as $filename => $module) {
  if (empty($module->info['hidden'])) {
    $package = $module->info['package'];
    $form['modules'][$package][$filename] = $this->buildRow($modules, $module, $distribution);
    $form['modules'][$package][$filename]['#parents'] = ['modules', $filename];

  }
}

If I do a break; the page loads up correctly with just one module and no errors. I believe its due to the sheer number of modules and the data that needs to be processed before generating the page.
So there is no bug but simply due to the data size in the loop. Has anyone faced this issue before  and know how to speed up things?
P.S I am using the lightning installation profile.

The solution to this was to increase the RAM in the server. We were using a container and the container was very restrictive in the amount of available RAM.


How to change field label name in a view programmatically I want to change the views field label name programtically? I have written a views-view-field.tpl.php. but dont know to change the $output variable.

You can use hook_views_pre_render() for that.

Add this function to your template.php file:

function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view':

      // do some logic for your label
      $label = 'My dynamic label';

      // define the label value
      $view->field['fieldname']->options['label'] = $label;
      break;
  }
}

Now, the label value will be always as the logic result. No matter whether the label is defined via Views Ui or not, it will be altered by your logic anyway.


Drush Enable a module and all its submodules For example when I enable coder  module, I also want to enable coder_review, coder_sniffer and coder_upgrade modules.

There is nothing out of the box to automatically enable submodules, but it is, in fact, possible to specify similarly-named modules via a wildcard:

drush en 'coder*'

As previously mentioned, this is only useful in certain niche situations.  I have never used it in any practical situation.  If you happened to need it, it would be just the thing, though.


Conditional Fields module not working when OR operator is used Using conditional_fields 7.x-3.x module
having two fields "category"(list containing a,b,c,d) and field "total rooms".

I have placed a dependency to show the total rums when category is "a" (OR) category is "c".

                      field_category       field_total_rooms is visible when field_category has value "a".
field_total_rooms                     OR
                      field_category       field_total_rooms is visible when field_category has value "c"

total rooms is being displayed when  category is "a" but
total rooms is not getting displayed when category is selected as "c".
Any suggestion

The dependency should be like below:

 field_total_rooms  field_category     field_total_rooms  is visible when field_category has at least one of the values: a, c.


Custom template file for custom view mode on site front page I'm trying to style a view a certain way on the front page (using a custom front page, page--front.tpl.php) of my site, and here are the steps I've taken using Entity View Types and Views modules:

1.) Created content type called 'Recipe'
2.) Created View Mode called 'Front Small'
3.) Created a view and called it 'Front Feature One'
4.) In the view settings, I've set the format to 'Content', and selected 'Front Small' view mode for display
5.) In my template.tpl.php file I've put in the following:

if ($variables['view_mode'] == 'front_small') {
    $variables['theme_hook_suggestions'] = 'node__' . $variables['type'] . $variables['view_mode'];
}

6.) I tried creating a file called node--recipe--front-small.tpl.php to style the node in a custom way but it never gets used. The standard node.tpl.php file is being used instead.

Can anyone tell me if I'm naming the file incorrectly or if something else might be wrong? When I spit out the $view_mode variable in my node file it shows "front_small" only. I've also tried removing 'recipe' from that file name to see if it would make a difference, but to no avail.

Note: I am using a custom front page styled in the page--front.tpl.php file. The view mode above that I'm trying to style should be appearing on this front page, so I'm not sure if there are other things I am missing.

Any help is greatly appreciated. Thanks in advance!

First of all, tell me where do you put that code? what is its function? node_preprocess?
besides that It doesn't make any sense to define a specific view mode for your view then trying to theme it using views! I recommend you to define fields as view mode, select your fields and theme it in the theme hook suggestion.


RSS Icon at browser's address bar I m not using Drupal 7 with its default way. I don't publish in front page, since I use a view for the front page.
I produce an RSS feed from a view.

How I can make the RSS icons appear at browsers' address bar?

If you have a custom module, you can use drupal_add_feed, should work for both D6 and D7:

function CUSTOM_preprocess_page(&$vars) {
  drupal_add_feed(url('path/to/feed'), 'Feed Title');
  $vars['head'] = drupal_get_html_head();
}


Have a profile field item from user registration show on a users page I have created a new checkbox field through the core module 'profiles' called Billing Terms. It is visible on the user registration form.

I'd simply like an asterisk * next to the users name on their profile page if the Billing Terms checkbox is ticked. Actually it doesn't have to be an * but rather anyway to signify that the Billing Terms checkbox was ticked.

Any help or helpful links would be greatly appreciated.

One way you can do this is if you have a custom template in your theme for user profiles. Creating a custom user profile template

Basically, you can overwrite the entire layout of the user profile this way. And then, you can output profile fields however you like by simply printing them. For instance:

<?php print $account->CHECKBOX_FIELD_NAME; ?>

This will allow anyone visiting the profile to view the results.

If you wish to display this to only users of a specific role, you would want to wrap the above code in an if and check what the viewing users role it.  For example, something like this

// Check to see if $user has the administrator role.
   if (in_array('administrator', array_values($user->roles))) {
    CHECKBOX_FIELD_NAME; ?>
   }
  ?>


how to set a webform field value in my custom module drupal 7 webform 7-3.18

My webform has a hidden field used to store an unique id. This id is generate from custom logic.

my code is to set this field value.
'webform_client_form_1' is my webform id

function webform_custom_form_webform_client_form_1_alter($form, $form_state, $form_id) {
  $form['submitted']['test_id']['#value'] = 'COURSE_ID-123456';
}

When the form is submitted and view the submission result and this hidden field value is empty

Ok, try not to confuse Webform module stuff with core drupal FAPI stuff.

You cannot set $form['submitted']['test_id']['#value'] = 'COURSE_ID-123456'; in the form_alter because $form is not passed in by reference and the submitted key values is set after the form is POSTed to my knowledge.

So you're trying to put stuff into the form in the wrong time and place. If I was just using FAPI and not webform. I would not use a "hidden" form value (which isnt really hidden on the page), but use Form build_args or $form_state['MYMODULE_temporary'] to hold my custom course_id in the FAPI form lifecycle so that the client never sees these values, but they are passed along through form validation and submission.

You can probably do the same technique I describe above and then implement hook_webform_submission_insert(), or hook_webform_submission_update() (if your form supports Drafts) to perform submission logic and look at your custom course_id stuff ...


How to fetch image from database in drupal Let me know how to fetch image from database. actually i am trying to fetch image from database using this question.
I am try to fetch image from database using following code.
$fid is my $row['column_name']

 $fid=$r['field_upload_photo_fid'];
 $image = theme('image_style', array(
'style_name'=> 'small',
'path' => $file->uri,
'alt' => 'user picture'
 ));
 print $image;

Actual file url is http://example.com/sites/default/files/styles/Style_name/public/Chrysanthemum.jpg

but now it shows http://example.com/sites/default/files/styles/small/public/styles/Style_name/public/Chrysanthemum.jpg.
 thats why image not fetching from database.

Also what is a style in $variable.

The style is an image style which is described a bit in Working with images in Drupal 7 and 8. I believe that you need to use Style_name as the 'style' in your code instead of 'public':

 $fid=$r['field_upload_photo_fid'];
 $file = file_load($fid);
 $variables = array(
 'path' => $file->uri,
 'style'=>'Style_name'
 );
 print theme('image_style', $variables);

But also, what is the data in $file->uri? If you start with bad data then the result is also going to be bad.


Filtering contents in Views I've got content-type with 3 integer field. I use Views module to display contents. I've got search. I'd like to create input in that search. After filling that input and entering I want to display contents whose at least one field is equal given value. How can I do it?

Sounds like exposed filters are what you're looking for. Just check for the "Expose" control when you're edited any filter item in your view.


Sort entityQuery by date published I'm attempting to perform a query to retrieve only the three most recent nodes of a certain content type.

$query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post')
    ->sort('field');
$nids = $query->execute();

I understand that I can use sort to specify the field I want the results to be sorted by. But how would I sort by the dates the nodes were published?

$query = \Drupal::entityQuery('node')
                ->condition('status', 1)
                ->sort('created' , 'DESC');


How do I get the form submitted data in a custom module? I have create a webform in Drupal 7. I want to access the submitted data in a custom module.

I used my_module_form_submit($form, &$form_state) but no data has been found.
Please Help.

You have to get submitted data based on sid, I think below code will be helpful for you

 function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'WEBFORM_'){
module_load_include('inc','webform','includes/webform.submissions');
$sid = 10;
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;

$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');

print $output;
}


Drupal 6 - Using node_view and display comments i'm using node_view to print nodes in a custom page. But the problem is that i need also the comments and the form comment to be shown under the node view.

How can i achieve this?

You probably need to use the node_show() function instead; it outputs the node as well as its accompany comment thread and comment form. node_show() relies on node_view() to print the node itself, but also calls comment module's code to build the rest.

One good rule of thumb for tracking down these scenarios is to visit the api.drupal.org site, look up the function that you're using to output a portion of the information you need, and look at the functions that also call it in Drupal core.


How to perform entity validation on code level? I have an entity that has a field attached to it and the values that user types into the field has to be globally(website) unique(compared to other entities).

I have added validation to the entity form but what if I create this entity programmatically? How can I prevent the entity to be saved into the storage?

I've noticed there is a validate method in ContentEntityBase, though not in ConfigEntityBase.
Is this the place for it? If so, I could use some examples.

Fields have constraints defined on them and as everything is a field on an entity, that's that. See Comment::baseFieldDefinitions does ->setConstraints(array('CommentName' => array()));. Then there's appropriate plugin in the Drupal\comment\Plugin\Validation\Constraint namespace in a class called CommentNameConstraint. The logic is in CommentNameConstraintValidator.

So the chain is

setConstraints in basedFieldDefinitions setting a list of plugin ids (CommentName) and their arguments (empty array in the example
A plugin in the Drupal\modulename\Plugin\Validation\Constraint namespace with the appropriate plugin id. The classname is not magic, the plugin id is what's important. Using the plugin id plus Constraint as classname seems to be best practice.
Whatever classname you picked in the previous step, append Validator to it, make it extend Symfony\Component\Validator\ConstraintValidator and put your validation logic in validate.


Rules module user/register I keep getting spammed/attacked looking at reports/db. Anonymous users keep trying to go to /user/register (but I disabled registering). So being annoyed by anons still trying to going to that url, I decided to write a rule:

{ "rules_anon" : {
"LABEL" : "Anon",
"PLUGIN" : "reaction rule",
"WEIGHT" : "-10",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_view" : [] },
"IF" : [
  { "user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "1" : "1" } }
    }
  },
  { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/register" } }
],
"DO" : [ { "redirect" : { "url" : "node\/39" } } ]}}

Context: Node 39 is Page Not Found

I tried it and it did not work, gives me do not have access message. So I tried the rule for a different url (/about) and it worked. I am guessing that url /user/register has a special case where Rules can not override it.

My question is: is there a way to redirect anonymous users from /user/register ?

Whatever you want to happen via Rules module when some link is clicked, if you're using Rules Event 'Content is viewed', you'll probably be too late:

the content (or whatever the clicked link is about) is already being shown, so if the Rules Conditions are satisfied, the Rules Actions will be performed. That is what 'Content is viewed' is all about.
if you didn't want to content (or whatever the clicked link is about) to be visible at all, well sorry, but you're too late.

If however you did want something to happen BEFORE showing the content (or whatever the clicked link leads to), then you should use Rules Event 'Drupal is initializing'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this.

Attention: Rules Event 'Drupal is initializing' gets triggered on every (repeat: every) page load in a Drupal site. So for performance reasons, you really want to limit the number of active Rules that use this Rules Event to an absolute minimum, i.e. as your last resort (if anything else fails).


Administer menus and menu items I've given my newly created user the permission to "Administer menus and menu items " however, when I log in as the new user I cannot administer the menus... Why might this be? The user doesn't have the permission to administer blocks, if that makes any difference?

Based on the comments, I think the issue is that your user needs the "Use the administration pages and help" permission, under the System category.


Create a list of figures, equations and other items I run a website that is like an electronic book http://www.pveducation.org Presently there are equations, images, mini-calculators that are included in the body of each page. How do I get Drupal to automatically create a list of links to,for example, the equations?  I also thought of making the equations a Content Type and use Views to make a page of all the equations but then I can't figure out how to use the new type in the body of each page. Should I use entities instead?

This is a typical use case for views.

If I understand your requirements correctly, you need to do the following:

create a block in views (see http://www.inmotionhosting.com/support/edu/drupal-7/views-module-tutorial/create-block-display)
assign that block to the region you want it to appear in your default theme (Structure -> Blocks), see https://drupal.org/documentation/modules/block

You can also restrict the pages on which the block should appear.


Can taxonomy tags/terms be more than one word? I've created a view that filters content based on the tags I associate with each page. It works great when my tags are single words.

In this case, posts containing any one of the above tags appear on my page.

However, I want to create and select tags for posts that contain multiple words (e.g. movie titles) such as Eternal Sunshine of the Spotless Mind, Garden State, The Aviator.

Currently, I apply tags via checkboxes (in case that's relevant), not using the autocomplete.

When I do this, the views filter only displays content containing the FIRST tag. For example, Only content using the Eternal Sunshine of the Spotless Mind tag is displayed, but content containing the other two tags is absent.

Any idea why this might be? Are my tags just too long? If so, how can I get around this? The following are the contextual filter settings.

I found Only works with first taxonomy term views3 D7 which is about the same issue you have.

This is what comment #18 and #20 say. You might also look at comment #28.

  This works very well, but it only works with the first tag/taxonomy term applied to a node. For instance, if a post was tagged Cheese, Recipe, Tomatoes, and Pasta, it would show other posts tagged with Cheese, but not those tagged with Recipe, Tomatoes, or Pasta. Is there a way to get it to consider all taxonomy terms, not just the first one?

  I just tried this solution and it seems to work. Just select "Reduce Duplicates" then under "More" select "Allow multiple values." That's it, you should have all the things being printed out and not just things related to the first term. Let me know if this helps.


Frontpage module redirecting to /user/uid not correct url on login The frontpage module redirects to /user/uid on login, not the specified redirect URL. All config looks correct. I have all redirects set to node/1 which is where I want it to redirect.

You can create a rule for this. when user logged in site then it will redirect on node/1 site.


Letting users remove webform submissions they've made earlier I have a website where people can sign up for events. The client now wants the users be able to delete their submission for the event, by entering their email address, displaying a list of events they're attending, and choose which event they want to remove themselves from.

Is there any module that adds this functionality, or is it something that can be done out of the box?

Implement sign ups as nodes instead of as webform submissions. Then you can grant the delete own [node type] nodes permission to allow users to cancel the sign up.


How do I let end users create and manage arbitrary connections between their user account and an entity I have an event content type and I want to allow users to 'add' themselves to it the same as Facebook users would join an event. Any ideas?

With Entity reference, this isn't very easy, because references are fields, and the permission management you need here is hard to do on a field level. You could still do it, but it would require a significant amount of custom work.

Consider using Relation or Flag instead.

You'll most likely get a better "out of the box experience" with the Flag module, but you will get better flexibility with the Relation module.

I've tried to convince one of Flag maintainers that the Flag is a special case of the Relation module and so should be based on it, but he didn't want to add a dependency.


How to Filter view by comparing 2 fields. If field-a < field-b I have a product content type that has 2 price fields.

I want to create a view that shows all products where price-A is less than price-B.

I was hoping I could just add a filter and select price-A then choose operate less than and set the value as price-B, however you can't do that.

I have looked into using a views hook, mainly hook_views_query_alter but haven't had any luck.

I've also tried using the Views PHP module and been unable to get it to work.

Does anyone know the best way to achieve this?

What you're looking for is the filter criteria Global: Fields comparison:)


field_widget_form call as a custom form I want to call my custom field_widget_form with the use of drupal_get_form()
Is it possible to do that?
simple requirement .. I want to build a form where user enter the field value and that value should be store with the node but only one field value instead of all 30 fields.

Now i have created the field with custom code so how can i call this function field_widget_form() in that or any other help full alternative.

When you define a widget form, you can change it from another module with hook_field_widget_form_alter(), which requires Drupal 7.8 or higher.

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}


Is there a way to make image and text alternate between rows? In Drupal theme, the content would have image and title which will have image on left and text on right in Display Suite under view in each row.

The client wants:
In first row, the image will be on left and text will be right. Next row, text on left and image on right.

Is there a module that can alternate between rows? Or display suite can do that?

Thanks

Create a custom module as follows:

In sites/all/modules create a directory: ds_odd_even

Add a file ds_odd_even.info under that directory.
Add the following text in that file:

name = "Display Suite Odd Even Output"
description = "Display Suite Odd Even Output."
core = "7.x"

Add a file ds_odd_even.module under same directory.
Add the following text to that file:

<?php

function ds_views_row_adv_past_client($entity, $view_mode, $load_comments) {
  static $i = 0;
  $custom_view_mode = ($i++ % 2) == 1 ? 'left_client' : 'right_client';
  return render(node_view($entity, $custom_view_mode));
}

Install the module as usual. Note the function name above. It is based on the pattern: ds_views_row_adv_YOUR_VIEW_MACHINE_NAME. This is the view name from the admin/structure/views UI page, not the display name from the right hand advanced column on a view. Hence the view that this is based on has a machine name of past_client. If you add more pages and blocks to this view, the view's machine name still stays the same. Each page or block will get a display name in addition. IT IS NOT THE DISPLAY NAME that you add to the function.

Create two view modes in Display Suite.
1. left_client
2. right_client

Add two column layout to both, with alternating image and body placement.

In your view (machine name past_client) set to show Display Suite as format, and in setting select under Advanced View Mode 'Use the advanced view mode selector'.

Clear your cache for good measure. And that is it.

There is no way I see to differentiate on different displays on the same view, unfortunately. You may explore CSS as an alternative, and use the nth-child() selector to alternatively float the display suite regions left or right (make sure you have greater specificity in the cascade or use !important)


buildForm runs before ajax button's submit handler on first click First of all, here is some working example code for the classic "Add more" AJAX button (complete module available as a gist):

public function buildForm(array $form, FormStateInterface $form_state) {

  if (!$form_state->get('number_of_fields')) {
    $form_state->set('number_of_fields', 1);
  }

  $form['#tree'] = TRUE;
  $form['container'] = [
    '#type' => 'container',
    '#id' => 'replace-me',
  ];

  for ($i = 0; $i < $form_state->get('number_of_fields'); $i++) {
    $form['container'][$i] = [
      'my_text' => [
        '#type' => 'textfield',
        '#title' => $this->t('Any text'),
      ],
    ];
  }

  $form['add'] = [
    '#type' => 'submit',
    '#value' => t('Add another'),
    '#submit' => [[$this, 'addTextFieldCallback']],
    '#ajax' => [
      'callback' => [$this, 'ajaxReplaceMeCallback'],
      'wrapper' => 'replace-me',
    ],
  ];

  $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
  ];

  return $form;
}

public function addTextFieldCallback(array &$form, FormStateInterface $form_state) {
  $form_state->set('number_of_fields', $form_state->get('number_of_fields') + 1);
  $form_state->setRebuild();
}

public function ajaxReplaceMeCallback(array &$form, FormStateInterface $form_state) {
  return $form['container'];
}

Now I want to save more things in the form storage. For example, I would want to generate a unique id for the container, so I can include my form more than once per page:

if (!$form_state->get('unique_id')) {
  $form_state->set('unique_id', Html::getUniqueId('replace-me'));
}

// ...

$form['container'] = [
  '#type' => 'container',
  '#id' => $form_state->get('unique_id'),
];

// ...

$form['add'] = [
  '#type' => 'submit',
  '#value' => t('Add another'),
  '#submit' => [[$this, 'addTextFieldCallback']],
  '#ajax' => [
    'callback' => [$this, 'ajaxReplaceMeCallback'],
    'wrapper' => $form_state->get('unique_id'),
  ],
];

However, this does not work. Using xdebug and phpstorm, I found out why:

When I load the page containing the form, buildForm runs. It generates a unique ID. First time round, the ID is replace-me. All good.

The first time I click on "Add another", the following functions run, in this order:

buildForm
validateForm
addTextFieldCallback
buildForm
ajaxReplaceMeCallback

The first time buildForm runs, $form_state->getStorage() is empty, which is unexpected! Consequently, a new ID is generated, e.g. replace-me--62or3gVN0K0. This means that the AJAX won't find the right node to replace next time, since the button still points to the old ID, replace-me.

The second time I click on "Add another", the following functions run, in this order:

validateForm
addTextFieldCallback
buildForm
ajaxReplaceMeCallback

This time, it works as expected, and the ID stays the same, but functionality is broken because the ID shouldn't have changed in the first place.

Questions:

Is this normal behaviour, or have I discovered a D8 bug?
What am I doing wrong?
Why would buildForm run twice on the first click?

Yes, this the normal behavior. In D7 and earlier in Drupal 8, having a form with at least one #ajax element forced the form to be stored in "cache", which quickly resulted in a huge amount of data there (we had GB of data in key_value_expire in an very early D8 site and it was growing almost faster than we could keep deleting it)

Now this only happens on the first Ajax request, when the form actually needs to start storing data.

The only thing you can do is depend your key on something that is more or less stable, you're possibly editing something that has an ID or you have a loop displaying multiple forms, then you can pass in an index. In Simplenews where we display multiple forms in blocks and we generate a unique Id (or allow the user to provide one) that we can then use to identify the forms.

Note that you need a unique form_id anyway to be able to use the same form more than once per page, see Generate unique form ID based on context.


feed from view doesnt work I made a view which works fine in the page view, but clicking on the feed icon or going directly to the path for the feed gives a  http 500 internal server error on IE 11.

And on firefox it simply has a blank white page.

Why arent the feeds working?

I had to enable the RDF module and now it works.


Download entire drupal contrib repository I would love to download (or, preferably, clone via git) the entire drupal contrib repository (6 for now, but 7 also). That way I can do cool stuff like search the repository via grep for hooks, examples, and implementations that I can reflect upon, improve, copy or steal. Is this possible? Is there a native way to do this via drupal.org or github.com/drupal? Do you have a current-ish copy of said repository. Please. Don't be greedy.

http://drupal.org/sandbox/greggles/1481160

  This project provides one way to help solve the issue Provide a way to download the entire git codebase for all projects.


How to show first X items and add and ellipsis [...] if there is more items? I have a View that displays books and authors of each book.

BOOK 1

Author 1, Author 2, Author 3, Author 4, Author 5

BOOK 2

Author 6, Author 7

What I want to do is to show only first 3 authors of each book and add an ellipsis [...] if there is more authors. It's easy to display first 3 items (Multiple Field Settings) but how to add an ellipsis to it?

BOOK 1

Author 1, Author 2, Author 3 ...

BOOK 2

Author 6, Author 7

How can I do that?

I have not tested this, so consider this an educated guess:

Go to /sites/all/themes/yourtheme/ folder and in template.php add the following code:

function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    if (isset($vars['fields']['field_example'][3]->raw)){
      $vars['fields']['field_example']->content = $vars['fields']['field_example'][0]->raw . ', ' . $vars['fields']['field_example'][1]->raw . ', ' . $vars['fields']['field_example'][2]->raw . '...';
    }
    else {
      $vars['fields']['field_example']->content = $vars['fields']['field_example']->content;
    }
  }

replace yourtheme with the actual name of your theme
replace view_name with the name of your view.
replace block_1 with the machine name of your view.
replace example with the name of your field.


anonymous voting using poll module invalidates cache I am not sure if this is a common problem. I use drupal 7 site with caching enabled. One of my pages is a simple poll. After anonymous voting, all cached pages are invalidated for current user. The cached pages remain in database so after clearing browser cache, current user sees cached pages again. Does poll use some sort of cookie that invalidates cache? How can I avoid such behavior? Thank you

After hours of testing, it looks like the Advanced Poll module does the job. Here is an excerpt about it from the module's project page:

... a replacement to Drupal's poll module and provides multiple voting systems, decision-making tools, and management options.

Voting systems: Basic polls, Approval Voting, Borda Count, and Instant-Runoff Voting.
Vote management: view each user's vote, delete all votes, or restrict the poll to a list of users.
Time management: schedule when to open or close the poll, and choose when to show results.
Choice management: write-in choices, and support for HTML (or other input filter).
Usability: fast Ajax interaction and customizable default settings.
Migration: convert regular Drupal polls into Advanced Polls.


Form is not submit handler is not called I have this code for calling a form and than submit it..

<?php
// hook_menu
function pricepackages_menu()
{
    $items = array();
    $items['membership/packages'] = array(
        'title' => t('Manage Membership Packages'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_form'),
       //'access callback' => TRUE,
       'access arguments' => array('access administration pages'),
    );
    return $items;
}
// FORM SHOW HOOK
function pricepackages_form($form, &$form_state)
{
    $form = array();

    $form['packagename'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Name',
        //'attribute' => array('class' => 'package'),
        '#required' => TRUE,
    );
    $form['packageDescp'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Short Description',
        //'attribute' => array('class' => 'package'),
        '#required' => FALSE,
    );
    $form['price'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Price',
        //'attribute' => array('class' => 'package'),
        '#required' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    $form['submit'][] = array('package_get_form'=> array());

    return $form;
}

function package_get_form($form, &$form_state)
{
    drupal_set_message('working');
?>
    <script language="javascript">
        alert("aaa");
    </script>
<?php
return;
    }
?>

but this one is not wokring proerly and form is not being submitted on the specific form...
neither its showing alert or message...

please help me...

Change this:

$form['submit'][] = array('package_get_form'=> array());

to this:

$form['#submit'][] = 'package_get_form';

btw.

function package_get_form($form, &$form_state)
{
    drupal_set_message('working');
?>
    <script language="javascript">
        alert("aaa");
    </script>
<?php
return;
}
?>

This looks really messy. Try that instead:

function package_get_form($form, &$form_state) {
  debug('test');
}

But the best option would be to use standard submit handler instead declaring your own name convention:

function pricepackages_form_submit($form, &$form_state) {
...
}


How to keep multiple drupal websites up to date I do a lot of web consulting and drupal is my preferred tool of choice. But as I grow, it seems like drupal gets more and more needy. At least once a week, if not more, my inbox gets messages that drupal needs updating, and I have to go and update the dev server, verify nothing broke, and then update the production server, and again verify that nothing broke.

I'm using drush to help me with this, but this is still taking considerable time away from my business, time I could be billing to the customer.

Does anyone have a solution to this? Some way to automate the updates and then a regression test, and if successful, do the same on production?

You could write scripts to do this.  You'd probably want to tie in to the Drupal unit testing module as well.

I can't provide you with any actual examples, because I'm not sure how it would be done reliably.

In my opinion, you're looking at a business problem that can't be fixed with a programming solution.  If I were in your shoes, I would start charging customers an ongoing maintenance fee for upgrades.


Wizard for generating a dynamic legal document I have been tasked with investigating options for developing a Drupal module that would serve as a Wizard for helping users create a customized legal-agreement template based on a series of interview questions.  Please note, I have had no experience with Drupal before last week, so I need specific answers that do not assume any knowledge on my part.

Essentially, this new tool would ask the user a series of questions on a variety of topics (and follow-up questions based on a decision tree), and when the interview is complete, the tool would produce a text document containing only those (pre-written) paragraphs relevant to the project.  Alternatively, more experienced legal staff could bypass the interview and simply select the paragraphs desired by clicking on items in a list -- much like the way someone with tax experience can bypass the "Guided Tour" in TurboTax to select and manually complete the appropriate IRS forms.  Other requirements:  Our user interface for our interview must be intuitive to the average technophobe, and the user must be able to send the output into a MS-Word document (additional formats are a bonus).  Our office is developing other web-based tools using Drupal 7; we have limited resources available for programming this tool, so simpler solutions are preferred.

Has anyone done anything like this, or know of tools/modules that we could adapt?  What other advice do you have for us?

Thank you all in advance for your advice.

For the longer list, you can add a content type (Structure -> Content types) and add checkbox fields for each question, where the text of the question is the value displayed by the checkbox when it is selected (the "On" value). An alternative way would be to add a Checkbox field with multiple values. I suggest this because by default, just the value of the checkbox(es) is shown on the resulting content when you save and view it.

For the list of questions, it depends on how many questions we're talking about. A slightly tedious but straightforward way is to use the Rules module along with another content type that contains the questions.

This installs itself to Configuration -> Workflow -> Rules.

For each question, you add a triggered rule that checks the response and sets the value of the other content type (let's call it Template) to whatever it should be. You could probably do this one with one rule as well. In this case, I'd set the stored values in the database for the Questions type fields such that they match or somehow contain information about the names/values of the fields in the Template content type. It would basically be a mapping of sorts, and the rule could set the value of the Template based on this.

You may also need to store a reference to the Template content corresponding to the set of questions in the Questions type. The easiest way to do this is to install References and add a Node reference field to the Template content type. Then, you can have a rule that creates a new template and associates it with the Questions content when you save a new Questions content item, for example. The other rules would then have some saved content for which to set field values (otherwise, you'd wind up creating new Template content every time or something).

These are some thoughts on this. It's not the most elegant, but it might get you started or at least on the right track.


How do I add a custom style to node by its type? I've tried following the instructions on http://drupal.org/node/1089656, but I somehow can't get it right.

How do I apply custom layout/style to a node based on its type?

If the content type of the node is Article, then the template file Drupal looks for is node--article.tpl.php.
If the content type name contains underscores, those are replaced with hyphens. If the content type machine name is snippet_code, then the template filename is node--snippet-code.tpl.php.


get taxonomy term aliased path when its a referenced field in a $node entity what I have is a $node and know how to get its aliased URL but I also have a field field_category that I know how to get the name but how do I get the url alias for it

$nid = 1;
$node = \Drupal\node\Entity\Node::load($nid);
$options = ['absolute' => TRUE];
$nodeurl = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
$categoryname = $node->field_category[0]->entity->label();

Sure enough I could use the tid or target_id in entity reference lingo and use it to find the URL fromRoute using as route_name entity.taxonomy_term.canonical

    $tid = $node->field_category[0]->target_id;
    $categoryurl = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid], $options);

find other taxonomy route_names

might also need to see the Url::fromRoute definition


How to disallow flags to get triggered if one of the user fields is empty? I have a user flag "Status" and I have some fields for that user like name, phone etc.

How do I not let moderators trigger that flag if any of that user field is empty?

Use the Rules module to implement what you're asking for, as detailed in the blueprint below ...

Step 1: Create a custom rule

Create a rule like so:

Event: after updating an account.
Conditions:

user does not yet have role (say) "abc".
check that none of those user fields are empty.

Action: grant access to a role (say) "abc".

For an example of a rule (in Rules export format) that is pretty close to what you need, have a look at my answer to "How to implement admin verification for selected user profile fields?".

Step 2: Tune the configuration of the flag

Adapt the configuration of your "Status" flag, so that you only authorize it to be used by ... euh ... indeed, users who have access to role "abc".

Happy flagging with Rules!


What does xmlrpc.php do and how can I use it? I have seen xmlrpc.php but I haven't found much documentation out there. Is it possible to use this directly without any additional modules? Where is the canonical documentation for it?

Is xmlrpc.php what is refered to here as "drupal's xmlrpc"? If that statement is correct xmlrpc.php would be only for the blog module in core.

You should be able to use it for other RPCs. Example xml-rpc post for user.update shows an example of a user.update method call.

<?xml version="1.0"?>
<methodCall>
   <methodName>user.update</methodName>
   <params>
     <param>
       <struct>
         <member>
           <name>uid</name>
           <value><int>38</int></value>
         </member>
       </struct>
       <struct>
         <member>
           <name>name</name>
           <value><string>diana.ruiz12</string></value>
         </member>
         <member>
           <name>mail</name>
            <value><string>ndy.r@eeuwkern.org</string></value>
         </member>
         <member>
           <name>pass</name>
           <value><string>candy9223</string></value>
         </member>
       </struct>
     </param>
   </params>
</methodCall>

It doesn't look like a widely used feature, and it will be moved out of core in Drupal 8.

See also Services Tutorials and Examples.


How to create dependent exposed filters in a view I have three drop-down boxes just like ex:

1. class list (ClassI, ClassII...)
2. subject list (Hindi, English...)
3. chapter list (H-ChapterI, H-ChapterII, E-ChapterI, E-ChapterII...)

When a user clicks on class list drop-down, there will be two option (ClassI, ClassII and so on...). When I select ClassI in a subject list (Hindi, English and so on...) will become as same. When I select on Hindi in chapter list related to Hindi (HChapterI, HChapterII) all chapter will come. This is what I want in my view filter.

I think you should use Simple Hierarchical Select, this also works with views and exposed filters out of the box.


How to set page-specific CSS classes on the page callback build array? I have a page callback like this:

function example_page() {
  $build = array();

  $build['#attributes'] = array('class' => array('example-class'));

  $build[] = array(
    '#markup' => '
My text here
',
  );

  return $build;
 }

As you can see, I have attempted to add classes to the div that wraps the output of the render array in the same fashion as the form API works. I have also tried setting $build['classes'] or $build['classes_array'], but all of these tree syntaxes are ignored, and the content is simply wrapped in
, which is not very helpful.

#attributes is the correct property, but the problem is that $build itself is not actually an render element (unless make it one), it's just a collection of render elements.

To make it an actual render element, you have to set the #type property to for example 'container'. That is nothing more than a div with attributes that contains other elements. See When should the "container" form element be used? and theme_container().

You can however not affect the mentioned content div, that is outside of your control. Adding a container will add a new div inside that one.


Is there a trick to deploying Commerce Kickstart 2 When I deploy my commerce kickstart 2.0 site, it doesn't display correctly.  Namely, it doesn't seem to be using the themes.  But really, I am not sure what is going on.  I have done development using Acquia Dev.  I exported my database using the Backup and Migrate module.

This is the site
http://twelvebasketstech.com

I can't even log in, but it is accessing the database because I see some of my product categories.

I am using PHP 5.4.  The server is running the following: Server version: Apache/2.4.12 (Unix)
Server version: 5.5.42-cll MySQL Community Server (GPL)

I have set the sites/default/files folder to chmod -R 775

Missing display/designs/CSS rules are typically a symptom of missing stylesheets or other CSS style rules. If you browse to your login page, Drupal reports many errors about not being able to create files.

It looks like your intuitions are likely correct; the server is probably having trouble writing aggregated CSS files to the files dir. Try turning off CSS/JS aggregation to confirm this. If that fixes it, check ownership of the files dir/subdir to make sure it's the same owner as the web server process.


How to print render Location's sub-fields? I'm trying to print render inside my node--article.tpl.php two of Locations sub-fields: the Street address and City
so that it looks like this: 16 Fleet Street, London -- without printing all other parameters (Province, Country etc)
So far I've got

<?php
    print
        render($content['field_location'][0]['#street']) . ', ' .
        render($content['field_location'][0]['#city']);
?>

But it doesn't work. Can someone please help?

If you have devel module installed than you check the exact contents of the array as: dsm($content);
Even if you don't have the devel module installed than check the contents of array as:

echo '<PRE>';
print_r($content);
echo '</PRE>';

I guess you probably have missed the language attribute - for regular non-location fields it's: $content['field_location']['und'][0]['#street']; and $content['field_location'][0]['#city'];


Why is Pressflow not listed under Drupal.org's List of distributions? I'm curious why it isn't listed under distributions. Is it because they have made modifications to the drupal core?

Press-flow generally takes the established features of the next version of Drupal and back-ports it to the current version.

For example Pressflow-6 Takes the features(enhancements and performance improvements) from Drupal-7 and back-ports it Drupal-6. These changes generally include changing the core to considerable amount.

The only reason I think of why it is not included is that

  Since it makes changes to the core it doesn't make sense to host it on
  the Drupal.org under project.


Content Type User Permissions Is there a way to change the user permissions of a content type? As I would not like the anonymous user to access a specific content type.

You could use the Group module. All you'd have to do is:

Create 1 group (pick your name) in 1 group type (pick your name).
Give access to all users to that group.
Use the group permissions to indicate you do NOT want to give anonymous users access to the content type you have in mind.

Done.


Custom widget not rendered within field group I wrote a custom module that adds a widget. This widget consists of multiple textfields and an ajax button that sends that information to an external service and gets in return and identifier that is stored locally.

However, it is not possible to render this widget within a group. (Using the field group module)
When adding it to a content type it will never be rendered within a group (as a fieldset, a tab, div or whatever), but instead before or after it.

My custom fields within the widget are bundled together by:

$form['fieldset']['field_name1']
$form['fieldset']['field_name2']

But even when they are not put together as a fieldset, it doesn't work.

How come?

Here is a code snipped of the definition of the fieldset:

$form['b2share_fieldset'] = array(
  '#type'  => 'fieldset',
  '#title'  => t('Publish data on B2Share'),
  '#collapsible'  => TRUE,
  '#collapsed' => FALSE,
  '#tree'  => TRUE,
);

$form['b2share_fieldset']['database_field_name'] = array(
   '#type'  => 'hidden',
   '#default_value'  => $b2share_fieldname,
);

The complete module can be found here.

I want to emphasize that my widget works fine. It's just always displayed outside the fieldgroup even when it is placed within the fieldgroup. Declaring it as a container as described here doesn't work either.

I also tried the patch provided here, but without success.

Also when I remove the fieldgroup and just leave the fields in there, they are always rendered outside the parent element.There aren't any status or error messages either.

I actually want to publish this as a contributed module, so I'd appreciate any help as I want to get rid of this bug, before I do that.

The problem is also described here.

OK. I finally found the problem based on the example code here.
The problem was that I constantly used "form" instead of element. Once I had replaced that the rendering was correct.

$form['b2share_fieldset']

instead of
$element['b2share_fieldset']

However, the huge downside is that now I don't know how to access the field information as $form_state isn't working anymore.

EDIT: After applying some minor changes in the code I can confirm that this approach works. The fully functional code can be seen on github.


How do I display the last person that edited content instead of the original author? On the page /admin/content, there is a column for Author. We have a lot of people editing our content, so the original author isn't all that important. I want to change it to show the last person that edited the content, which I believe is stored in the revision of that content. How can I modify the view to show that? Alternatively, is there a hook I can implement in a custom module to do this?

I've checked out a couple other questions like this one and this one, but they weren't much help.

Adding a relationship of user (content revision) & Content (Content revision) proved to be fruitless.

Ok, time for plan B

Using Views field view we'll create a revision view, add revision user as field and then insert this view as field on the content view.

1) Create a new view

Show: Content Revision
Checkmark Create a block
Items per block: 1

2) Add a contextual filter

Originally I tried with Revision ID, but there is a bug, this contextual filter does not work.
So instead use ID (which is the node id)

When filter not available, hide view

3)

Remove the changed & title fields
Add Revision User

4) Add a Sort of Changed

Select Descending sort

5) Save your view

Now go to the Content View (/admin/structure/views/view/content)

1) Add field of ID

Checkmark, exclude from display

2) Add field View

Select the view you just created and for contextual filter use {{ fields.nid }}

and that's it!


How to pass seperate contextual filter values to a view and get results programatically? I've a view having two (separate) contextual filters, say node id and taxonomy id. We can pass separate contextual filter values with a "/". example: 12,13,14/8,9 as URL arguments.

But how can we get the view results by passing the dynamic contextual filter values to the view?

Here we go.

 $nodes_str = implode(',', $nids); // $nids is an dynamic array.
 $args[] = $nodes_str; // First contextual filter argument. 12,13,14.. etc
 $args[] = $tag; // Second contextual filter arguments 8,9.. etc
 $view = views_get_view('view_machine_name');
 $view->set_display('display_name');
 $view->set_arguments($args);
 $view->pre_execute();
 $result = $view->execute();
 $output = $view->result;

If need futher details of the view parameters. You can debug the values using the hook_views_pre_view()

function YOUR_MODULE_views_pre_view(&$view, &$display_id, &$args) {

}

Hope this helps someone.


How to print render each term in a vocabulary? I kinda feel ashamed to ask this but I really did not find any answer on this...

How can I print each term in a given display mode, for instance 'teaser', anywhere I have loaded a vocabulary's terms?

<?php
    $vid = taxonomy_vocabulary_machine_name_load('finder_items');
    $tax = taxonomy_get_tree($vid->vid, 0);

    $tids = array();

    foreach ($tax as $key => $value) {
        $tids[] = $tax[$key]->tid;
    }

    // ?? causes exception
    $tvm = taxonomy_term_view_multiple($tids, 'full', 0, 'de');

    print $terms;

?>

I want to fully render them, with all their fields.

You might be seeing Exception as

  EntityMalformedException: Missing bundle property on entity of type
  taxonomy_term. in entity_extract_ids()

Reason being:

  In taxonomy_term_view_multiple($terms,..)
  $terms: An array of
  taxonomy terms as returned by taxonomy_term_load_multiple().

    $vid = taxonomy_vocabulary_machine_name_load('finder_items');
    $tax = taxonomy_get_tree($vid->vid, 0);
    if (!empty($tax)) {
      foreach ($tax as $term) {
        $tids[] = $term->tid;
      }
    }

    // Get the term obj by passing array of term ids.
    $term_details = taxonomy_term_load_multiple($tids);
    $terms = taxonomy_term_view_multiple($term_details, 'full', 0, 'de');

   // Render the return array
   foreach($terms as $term) {
     print drupal_render($term);
    }


How set node access for guest? for example I have a url like:

/node/add/feature

when I go there as guest, I get 'access denied', the access should be changed in the code or in the admin panel? but how can I find the exact place where to make changes by following this url?

The admin panel under /admin/people/permissions. The /node/add/$CONTENT_TYPE access is controlled under the Node section as the ContentType: Create new content permission.


How to Add Multiple Values to Prefix for Currency field as a Drop Down I have a custom Decimal field, Salary, for one of my custom content type. How do I add multiple prefixes that I can display as a drop down in the node add/edit form for users to select their respective currencies while updating the salary field?

I have tried the currency module, however, I didn't find any option in it to add a decimal/ integer value in it.

Also tried Field Collection Module, it does give the option for combining multiple fields, but, the result looks a bit crude. The Fields come one above the other rather than alongside each other.

Is there any option for me to add Multiple prefixes in the Field and display the same as Drop Down List in the Node Add/Edit form?

Please advice.

Thanks

Found the Solution in this post. Used the Measured Value Field in Conjunction with Units and Currency. Got a pretty neat solution.


RSS item elements not being not being read by XML Reader I am new to stackexchange and don't know if i am asking this correctly but plz help me.

I am using Drupal Views to display RSS for my site. I am using the 'Views RSS: Core Elements' module to map the RSS fields with the custom fields added by me in the views. All works well. But a requirement forces me to add custom item elements in the RSS display. I am implementing the hook_views_rss_item_elements() to add custom item elements. When i view the RSS page i get the see the custom items but when i try to read the RSS using a RSS reader, the items are not being read. What am i doing wrong, or am i missing something?

Here is my code to add custom items to the 'SHOW ITEM ELEMENTS : CORE' for RSS display:

function Mymodule_views_rss_item_elements() {
  $elements['blogs_title_image'] = array (
    'title' => t('Blogs Title Image'),
    'description' => t('Blogs Title Image'),
  );
  $elements['blogs_additional_tags'] = array (
    'title' => t('Blogs Additional Tags'),
    'description' => t('Blogs Additional Tags'),
  );
  $elements['blogs_short_desc'] = array (
    'title' => t('Blogs Short Description'),
    'description' => t('Blogs Short Description'),
  );

  return $elements;
}

After some research i did manage to find my way out:
I implemented hook_views_rss_namespaces to add a custom namespace and the custom items under the namespace:

function Mymodule_views_rss_namespaces() {
  $namespaces['blogs'] = array(
  'prefix' => 'xmlns',
  'uri' => 'http://base.google.com/ns/1.0',
);
return $namespaces;
}

Note: Use the same 'prefix' and 'uri' as given in the above code or else namespace uri error will arise.


I forgot the password to the admin account A few month ago I have make a web-page using drupal. I had some break due to phd thesis. Now I want to push the subject foreward and finish the page, but I have forgot the admin's password. Is there a possibility to get it, or change it?

I tried the method described on http://drupal.org/node/1023428, but I got the following errors:

  PHP Warning:
  include_once(/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/password.inc):
  failed to open stream: No such file or directory in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 83   Warning:
  include_once(/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/password.inc):
  failed to open stream: No such file or directory in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 83   PHP Warning:  include_once(): Failed opening
  '/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/password.inc'
  for inclusion (include_path='.:/usr/share/php5:/usr/share/php') in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 83   Warning: include_once(): Failed opening
  '/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/password.inc'
  for inclusion (include_path='.:/usr/share/php5:/usr/share/php') in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 83   PHP Warning:
  include_once(/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/bootstrap.inc):
  failed to open stream: No such file or directory in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 84   Warning:
  include_once(/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/bootstrap.inc):
  failed to open stream: No such file or directory in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 84   PHP Warning:  include_once(): Failed opening
  '/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/bootstrap.inc'
  for inclusion (include_path='.:/usr/share/php5:/usr/share/php') in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 84   Warning: include_once(): Failed opening
  '/var/www/localhost/htdocs/26_05_2012/zipshop/scripts/includes/bootstrap.inc'
  for inclusion (include_path='.:/usr/share/php5:/usr/share/php') in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 84   PHP Fatal error:  Call to undefined function
  user_hash_password() in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 87   Fatal error: Call to undefined function
  user_hash_password() in
  /var/www/localhost/htdocs/26_05_2012/zipshop/scripts/password-hash.sh
  on line 87

Is there a possibility to change the password just through mysql-cient?

If the email you used to register the account is still active, or you still have access to it, then the easier way to change the password is using the "Request new password" link that appears in the login block, or the login page.

If you don't have access to the email you used to register it, you could change it in the "users" database table, and then request a new password.

If you don't have access to the database, but Drush is installed, then you can use the following command.

drush user-password <username> --password=<password>

Alternatively, you can use this command, which allows you to login as a user for once; once you are logged in, you can change the password for that account.

drush user-login <username>

The command return a link that can be used in the browser to access the site. If the username is omitted, the link is for the user #1.

If Drush is not installed, then you need to write a PHP file to change the password for the account. For Drupal 7, the following code works.

$account = user_load_by_name($username);
$edit['pass'] = $newpassword;
user_save($account, $edit);

Place the code in a file with extension .php, in the same directory containing the index.php file that comes with Drupal. Replace $username, and $newpassword with the username of the account you need to change the password, and the new password.

The following code work with both Drupal 6, and Drupal 7, but it requires you to know the user ID of the account.

$account = user_load($uid);
$edit['pass'] = $newpassword;
user_save($account, $edit);


Code for "All pages except those listed" in Show block on specific pages While editing a block I want to use "Pages on which this PHP code returns TRUE (experts only)" at the same time support the URL's entered in "All pages except those listed" plus my own custom conditions.

Where can I get the standard code to match those URL using PHP code?

For example as in figure initially "All pages except those listed" is checked on but now I want to choose the Experts only(3rd one).

In this Experts only mode before adding my custom code I'd like to check for exclusion of those same URL's first then proceed.

I made this stuff copying from Core's block.module:

//This block will not show pages when these pattern match
$pages = <<< EOT
adsense/*
node/add/*
adsense/*
contact
privacy
tags/*
terms
about
check-for-expired-job
taxonomy/term/*
EOT;

$pages = drupal_strtolower($pages);
$path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
$hide_block = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
    $hide_block = $hide_block || drupal_match_path($_GET['q'], $pages);
}
if($hide_block)
{
return false;
}

//Now do other processing stuff


How can I add pager to the comments of advanced forum in drupal 7? I use the drupal 7 core forum with advanced forum module.

This works perfectly except the forum topic page show only post comments what number is defined on the content type, and no pager on the comments, therefore the users can't jump to the next few comments.

My question: how can I add pager (first, prev, next, last, etc.) to the advanced forum post comments?

I didn't found any solution until yet.

In your style directory, you should have a *.topic-header.tpl.php file. Make sure the following is where you want the paging to display:

<?php print($pager); ?>

Then, in *sites/all/modules/advanced_forum/includes/theme.inc*

Approximately line 446:

  pager_default_initialize($variables['node']->comment_count, variable_get('comment_default_per_page_forum'));
  $variables['pager'] = theme('pager');


How can I fix site UUID does not match error during config import? I'm getting this error below whenever I try executing the commands drush config-import staging on the CLI. I'm basically in the process of migrating a drupal 7 DB to Drupal 8 and currently following this guide since I'm still new with migration.

https://www.youtube.com/watch?v=_z2FH0efd_g

Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization. in         [error]
Drupal\Core\Config\ConfigImporter->validate() (line 728 of
/Applications/XAMPP/xamppfiles/htdocs/drupal-eight-iom/core/lib/Drupal/Core/Config/ConfigImporter.php).
The import failed due for the following reasons:                                                                [error]
Site UUID in source storage does not match the target storage.
Entities exist of type Shortcut link and Shortcut set
Default. These entities need to be deleted before importing.
The core.extension configuration does not exist.
Can not uninstall the Configuration module as part of a configuration synchronization through the user
interface.

$databases['default']['default'] = array (
  'database' => 'drupal-eight-iom',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['upgrade']['default'] = array (
    'database' => 'drupal-seven-iom',
    'username' => 'root',
    'password' => '',
    'prefix' => '',
    'host' => '127.0.0.1',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
  );

$settings['install_profile'] = 'standard';
$config_directories['staging'] = 'sites/default/config';
$config_directories['sync'] = 'sites/default/files/config_zB_DnNUK68i5Owp5a8FzTiClQfp3d3jrwcy0_HuS1hNCGv9Y_Iva2Ahm8LCH-P0j0M2jwmQAsA/sync';

Site UUID in source storage does not match the target storage.

Make sure you've system.site.yml on your staging site, see: Site UUID in source storage does not match the target storage.

To check the current UUID, run:

drush config-get "system.site" uuid

to change it, run:

drush config-set "system.site" uuid "xyz"

See: How can I import the configuration on a different site?

  Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing.

Try removing these entities manually before the import as it says.

  The core.extension configuration does not exist.

Make sure you've core.extension.yml file in your config folder, otherwise generate one via config-export.

  Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.

Most likely it's related to the missing core.extension.yml.

Few hints:

You can also try to import the config using Drupal Console using config:import.
For debugging purposes, try to import one file at a time. See: Import a single yml configuration file. For example:

drupal config:import:single --directory=$PWD/config/sync --file=file.yml

If you're using different config dirs per environment, consider using Config Split.


Show file field as thumbnail if file is an image? I've added a field to comments to allow users to upload files. I want users to be able to upload different types of files, but if it's an image then show a thumbnail. Can this be done while just using 1 field?

I could also create a template for the comment, or the field and then insert an "if".


Drupal 7 how can I alter page content generated with module? I have one module:

function MYMODULE_menu() {
    $items = array();
    $items['mymodule'] = array(
      'title' => t('My Module'),
      'page callback' => 'MYMODULE_view',
      'access arguments' => array('access content'),
      'page arguments' => array(1),
      'type' => MENU_NORMAL_ITEM,
    );

    return $items;
}
function MYMODULE_view() {
   return array(
        '#theme' => 'my_module_theme',
        '#variable' => 'some variable'
    );
}

In the other module I want to alter this content to change the theme and add some variables. How can I do it?

You can change the variables of the page content implementing the template_preprocess_page() function in your module or theme. As of Clive's comment, I want to update that you can preferably use hook_page_alter(), which is called earlier than preprocess function.

function YOURMODULE_preprocess_page(&$variables) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($variables)
}

or

function YOURMODULE_page_alter(&$page) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($page)
}

Additional Reference:

Render Arrays in Drupal 7 See the section "Creating Content As Render Array"

  A page callback should return a render array, as should hook_block_view()'s $block['content']. This allows your module and other modules to treat the content as data for as long as possible in the page generation process.


Redirect user back to the private page after they have logged in On my site I have a private page that can only be accessed when the user is logged in. If they aren't logged in they are directed to the login page.

I want to redirect them back to that page after they've logged in

I've tried a lot of solutions already listed on here including: logindestination and logintoboggan.

Every time the person logs in they are always directed to their user page no matter what I change in logintoboggan/logindestination

I tried creating a rule but was getting a 404. I'm not sure what to put in the PHP Evaluation field in the redirect action.

I've added this to my template file

global $user;
    if ($user->uid == 0){
        print l("Login","user/login",array('query' =>     drupal_get_destination()));
    }
else{
print l("Logout","user/logout",array('query' => drupal_get_destination()));
}

And then in logindestination I added

$destination = drupal_get_destination();
print $destination;

What am I doing wrong??

For logindestination to work properly all you need to do is add an entry using <current> as the redirect location.  Leave the "Redirect to Page" option as Internal page or external URL.  This configuration will send a user back to the page they were trying to access before being sent to the login page.


Combine Token title with url in an email I send emails automatically to users. There is a link in these mails, which points to a node. But I want to use the node title as an alias for this link, so that the link is not directly displayed in the mail.

Currently I use a 'text_format' form element, where I wrote the content of the mail with the corresponding HTML code for the link:

[node:title]

Because this just works with 'full html format', it might be possible to accomplish it in another way?

I would welcome every advise!

Thanks, Daniel

Have you tried the token_replace function?


How to remove Analysis button from Webform results tab I am trying to located the template file or function that outputs the following buttonson the webform results tab

Secondary tabs

Submissions(active tab)
Analysis
Table
Download
Clear

Can anyone advise how I can tweak/remove/hide some of these

The best way to hide menu item from the secondary tabs should be to alter the access callback of the menu item.

function yourmodule_menu_alter(&$item) {
  // This hides the analysis item. Others should work simillary.
  $item['node/%webform_menu/webform-results/analysis']['access callback'] = 'yourmodule_webform_result_access';
}

function yourmodule_webform_result_access($node, $account = NULL) {
  // You can put here any custom logic of your needs.
  return FALSE;
}


why is admin not bypassing restrictions at views? I have a problem of admin not having full access to content nodes.
I wanted to create a view so that a user can see nodes he created and cannot see other users' nodes. However, 'admin' should be able to see all available nodes without any restricts, even if made.

My problem is that, when it comes to restricting the users to see only their nodes posted. Strangely the admin was included to see only his own posts as well!
(even though the settings where telling me that whatever setting I make, the admins will not be affected) but that doesn't seem to be the case.

Does any one have any idea or suggestion?

I have gone to permissions, and checked ALL values to be selected. I rebuild the permission. Yet, this is happening.

Just in case I thought some module might be interfering, I had NodeAccessdisabled and some other modules, but the result is the same! The admin is not getting a full view as supposed to when restricting!

Here's a screen shot of a user view and admin, currently as an admin (aziz here), this is what I see (3 nodes created by admin):

and those are the setting:

While on the other hand, when I created another view WITHOUT restrictions, it shows all nodes:

and here are the settings for it:

Anyone has any idea why the admin is included in restriction?

Let me know if you think there's anything wrong here. Because based on my other question is the post " how to view data row table related to user only?"
I was advised to follow these setting  (as in image, and the user who advised is working very well with him). But I think that there's something interfering with my admin role for not letting it bypass restrictions made (at least, even when I do restrict the view for users, admin shouldn't have been included).

My last hope in the admin restriction is creating 2 views for every content type, which is quite troublesome.

I hope I gave clear picture.

In your 2nd screenprint, within "filter criteria", the last line of it is says "Content: Author uid (=aziz)". That doesn't seem to be correct ...

Make sure the filter criteria only has "Content: Author uid" without "Author user: current". And keep the ID blank for the author uid, because specifying the user will only refer to the nodes published by THAT user only.


How to change the HTML output of link to image file? With Manage Display of image field, I set 'Link image to' to File.

so when user clicks the styled image, will link to original file, I want to change the html output of the link. How may I do so?

Install the devel themer module. After enabling it you can point to whatever you want to change. It will tell you which theme method is actually called what options you have to implement your own one.


Dynamically fetch feeds and html content from other website and show Is there any module that pulls data from external feed or html link and displays in drupal. It should not create any corresponding nodes in drupal. It should just go and scrape data or feed and display in a page or block.

Feeds is the way to go. It includes an HTML parser and can fetch data from existing URLs.

Here are some links to parsers for Feeds that can suit your needs.


Can't login after migration I moved my website from my computer to another one, I moved drupal folder and the database with backup & migrate, I used to do it every day and now on the first call, The website worked, but after login with admin, I can't acces the website.
I tried changing $cookie_domain, but it was already commented, also rewrite_module is enabled on apache, I'm workin on localhost. help me guys, thank you

Use drush upwd to reset your password

drush upwd --password="givememypasswordback" "admin"

If you don't have drush installed do it via MySQL. Here is a related article.


URL and GUID values from Feed import When you import RSS items via Feeds, where are the URL and GUID target values stored in the node?  How do you get these out?  I am not seeing anything close to these when I dump the $node.

This shows the Mappings screen with the values that I am talking about:

They are stored in the feeds_item table in the database. They are used by the feeds module to control updates of imported items.


How does module_hook() function work? I need to check whether a hook is implemented in a module, so I chose module_hook function. In the documentation it states that the Return Value will be:

  TRUE if the module is both installed and enabled, and the hook is
  implemented in that module.

Now, I named a callback function (not a hook) in my module as "my_module_abc()"

Note: my_module is the name of my module.

  If I test this function in module_hook like below:

module_hook('my_module', 'abc');

  It returns TRUE.

I thought It would return TRUE only for registered hooks and not for any function callbacks. Does module_hook know the difference between a function and a hook?
Is there any function like hook_information($hook) which returns information about a hook?

Is this right? Am I missing something?

It's important to understand that a 'hook' is literally a function that's named in a certain way.

If you have a function

function my_module_abc() { }

That is, by the nature of the hook system, my_module's implementation of hook_abc().

Whether hook_abc() was ever intended to be a hook is a completely different matter. The fact that the hook system works entirely on a naming convention means that it's inevitable. In fact it's working exactly as designed.

Hooks are very loose, they are not structured; they don't have meta data, beyond what the module author may choose to document in MODULE.api.php. The 'information' you're looking for doesn't exist, and until someone changes the way Drupal's hook system works, it can't and won't.


Why is the third level not showing in my superfish menu? I'm having a super fish menu wih three layers of menu points but my second layer links do not seem to be expanding even tho "Show as expanded" is checked for the individual menu points (2nd level) that is selected as "Parent item" for the 3rd level page.

Some links:
menu point with submenus: http://www.lslib.ca/content/skwlax-daycare
Third level page(hidden from the menu): http://www.lslib.ca/content/admin

How can I get the third level to display?

EDIT 1

I don't exaxctly know how Superfish binds into the configration either. Maybe a link to the page would help: http://www.lslib.ca/
Under Blocks, I only see Content assigned to a Region. I'm officially confused here... :o

EDIT 2

The name of the theme is Nexus Theme, under admin/appearance it says: Nexus Theme is a premium Drupal 7 theme. Developed by Devsaran.com.

In page.tpl.php I have the following:

<nav id="navigation" role="navigation">
  <div id="main-menu">
    <?php
      if (module_exists('i18n_menu')) {
        $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
      } else {
        $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
      }
      print drupal_render($main_menu_tree);
    ?>
  </div>
</nav>

I would give this a try:

  In the drupal bloc configuration just disable "Slide-in effect"

Quoting the last comment from this thread:
https://github.com/joeldbirch/superfish/issues/30

Hope you get lucky with this, that whole github thread could be also interesting/relevant to your issue.

Update: This is apparently a theme specific superfish implementation, the respective theme being (most probably) Nexus

In order to deactive the effects that could be causing the error, you should edit the file sites/all/themes/nexus/js/custom.js at about line 7, commenting out the animation options:

//  animation:   { opacity:'show',height:'show'},   // fade-in and slide-down animation

Hope this does the trick!


How to solve this PHP fatal error after installing module? PHP Fatal error:  Cannot redeclare _field_info_field_cache()
  (previously declared in
  C:\xxxx\wwwroot\xxxxx\modules\field\field.info.inc:16) in
  C:\xxxxx\wwwroot\xxxxxxx\sites\all\modules\easy_booking-7.x-2.4\modules\field\field.info.inc
  on line 32

So I got this error notification after turning on Error debug in my IIS Server because previously it only showed a 500 page error.

It seems it's calling two times the same function? Anyone can help?

Edit: I guess it's better I just delete the module but then I get a require_once error:

  PHP Fatal error:  require_once(): Failed opening required '

Put the module back. Check its code. Delete the problematic function named in the corresponding error message from it. Go to admin page. Uninstall the module.

Try to reinstall the module in a proper location. Don't name the folder easy_booking-7.x-2.4. Simply name it easy_booking. If the error still occurs, file a bug at https://www.drupal.org/project/issues/easy_booking?status=All&categories=All


Node::load() with specific revision ID I want to load the node details for a specific revision. I tried using the following code.

use Drupal\node\Entity\Node;
$nid = 1171;
$vid = 9423;
$rev_node = Node::load($nid, $vid, TRUE);

I also tried the following code.

$rev_node = node_load($nid, $vid);

It always loads the latest version, irrespective of the revision ID passed to the method/function call.

Is there a way to load the data for a specific revision?

Try with this code:

\Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);


file as field node block I am building a site in which authenticated users may upload files.  When such a user is viewing URLs of a certain content type, I would like the left sidebar to contain, among other things, a file control.  The right column of an unauthenticated user holds the login controls, and that column must hold something else for authenticated users who have not accepted the required condition.  My goal is to have the user perform the upload while also reading the content.  Hopefully, this improves retention.

At any rate, I need a block which contains a file field.  I have been trying to do this with Node Fields Block.  So far no success.

I added a hidden file field to my content type, installed and enabled node_fields_block, and added a Node Fields Block which is enabled for pages of my content type and which contains the File.  I've created a 'Node Fields Block' display mode for the content type in which the file is supposed to appear, but nothing shows  up.  I've looked at the generated HTML and the block isn't being generated.

I'm at a loss.  Any help greatly appreciated.

The last time I tried node fields block, some of the fields doesn't really show. So I just switched to using the views blocks. it's just the same. Just insert the fields you wanted to show. If you want users to upload files on the current page you could try Block upload - it's a simple module, which allow users to upload images/files into field without node edit page.

Did I understand your case correctly?


How can we find the js file is included before or not in drupal I have some functions in template.php file that inside some of them, some js files must be included to the template.

Now, I want to check at first whether a specific js file [for example jquery.min.js] is included before or not. (in order to avoid) duplication.

Is there any way to check this issue in drupal 6??

A. You should not be including jQuery manually in Drupal. Also, jQuery is always loaded on every page. If you need to include a different version of jQuery than the version that is included in Drupal core, you should utilize the jQuery Update module.

B. Secondly, you should be adding your javascript files using the drupal_add_js() function. Utilizing this function will take care of a lot of potential issues involved in managing many javascript files across many pages on your site.

C. drupal_add_js() returns an array of all javascript files. You could load a javascript file conditionally based on the presence of another javascript file, like this:

  $scripts = drupal_add_js();

  if(!isset($scripts['path/to/script.js'])) {
    drupal_add_js('path/to/script.js');
  }

D. Be sure to thoroughly read the Drupal.org documentation about using javascript in Drupal. This will answer many of your questions and solve many of your issues regarding javascript in Drupal.


how to create hook for send email to profile2 type user In my project there are two types of user.Using profile2 module i creates 2 profiles.
1) normal user
2) Lawyer

So i have to send promotion email to lawyer after registration.
i created following rule.

1) Event
 - After saving a new profile

2) condition
 - user has roles

a]After selecting they ask for  Data selector. i don't know what i select for my lawyer account

b]i select "lawyer" Roles

c]match roles - all)

3) Event
 In event i select send-email

a]email function $to - how i can put current user registration email

b] body is static

c] subject is static

I am really confuse. Can i create hook for send email to lawyer after registration.

In condition add data comparison instead of user role if want to send mail only basis of profile type as below.

Edit:

In Action Section
Select Send Main or Send Html Mail under System and follow as below png file.

This may help it..