Set mod-rewrite to forward everything accept for one subdomain I am trying to set up mod rewrite to forward the site example.com to www.example.com. This is fairly easy, because there is a line in the built in .htaccess file that I just have to uncomment. The problem is, I can't figure out how to set it so that all domains of example.com forward to www.example.com, accept m.example.com which I want to keep the same. These are the line's I'm using right now:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How can I set it to so that only m.example.com stays the same?

Something like this should do it:

RewriteCond %{HTTP_HOST} !^(www|m)\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Download file after filling a form On my site, the visitors can download whitepapers as pdf. I would like to gather some information before handing over the file.
Updates: the downloads should be open to unregistered users

What I tried:
I looked around for modules. Some of them seemed to do something like this but were Drupal 7 only, like Webform Protected Downloads.
On the site I can make use of the Webform module as per this question. I could make a form with a redirect page where the file can be downloaded. However, as there are many whitepapers, for each one there should be made a separate form and download page.
Update: in Webform it is possible to stay on the same page and output a thank you message with download link, so that will limit the effort somewhat.

Is there a simpler way to solve this?

Instead of creating different webforms for each file, you could just have one form that can handle this. Here is my suggestion:

Make all links to your whitepapers to load a webform and pass the filename as a parameter for your webform. You can then store that on a hidden field on the form.
Create a custom submission handler for your webform to trigger a download upon submission (use the filename from the hidden field on the form).


How to fix "Hook implementations should not duplicate @param documentation."? I am using PhpStorm to experiment with cleaning up my code in a custom module.  For the following function, I'm getting this warning:

  Hook implementations should not duplicate @param documentation.

/**
 * Implements hook_field_widget_form_alter().
 *
 * @param array $element
 * @param array $form_state
 * @param array $context
 */
function mymodule_field_widget_form_alter(&$element, $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_mymodule_remove_textarea_help';
  }
}

What should I do to fix this? I thought I needed to delete the @param comments, but when I do that, PhpStorm complains that I don't have any param comments.

The problem is that if you're implementing a hook and you don't need to write more than this:

/**
 * Implements hook_field_widget_form_alter().
 */

Because you will have all the information in the hook_field_widget_form_alter() definition, so just write always in the hooks implementations only this:

/**
 * Implements hook_hook_name().
 */

In your case:

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_mymodule_remove_textarea_help';
  }
}


Display summary of paragraph text field in twig I have a paragraph type called News. In this paragraph type I have a text field (field_news_intro ) with a summary. How do I display the summary in a twig template?
content.field_news_intro.summary seemed logical, but it doesn't return anything.
My template is called paragraph--news.html.twig

  {{ content.field_news_intro.summary }}

  {{ content.field_news_intro }}

you can get the summary with summary attribute in field level.
{{ content.YOUR_FIELD_NAME['#items'][0].summary }}

in your case answer will be :
{{ content.field_description['#items'][0].summary }}


Show link based on role In page.tpl.php I'm displaying a link for user page. For an example:

<?php echo l(t("My offers"), 'user/' . $user->uid . '/offers'); ?>

So when a user clicks on the link it goes to user/uid/offers.

Now I want to show this link only based on a role.
Let's say we have a role "Seller" that has unique ID 5 in the database.
How can I set

<?php echo l(t("My offers"), 'user/' . $user->uid . '/offers'); ?>

to be visible only when a user has a role "Seller"?-

I've got answer from drupal.org and this is the right solution:

<?php
if(isset($user->roles[5]))
{
  echo l(t("My offers"), 'user/' . $user->uid . '/offers');
}


Trouble with the menu Block module I am trying to build pages with the main menu displayed in multiple locations. A "main navigation" with top-level items A,B,C,D,E; and each of these has children a1,a2,...b1,b2,... etc.

There is a drop-down navbar menu in the header that is on every page (that displays A B C D E and when you click on any one of them, it shows its children); if you click on any child (say a2), it takes you to a url .../A/a2. That page still has the "main navigation" in the header, but also in the left sidebar it has the sub level menu of A (a1,a2,a3...) with a2 highlighted.

Someone directed me to try the menu block module, but i am not able to get it to display just A's children while in A. Depending on the options I choose for depth etc. I can either show all links (A B C D E a1 a2...e1 e2...) or all the children from all the parents (a1,a2,...,b1,b2,...,e1,e2...).

Using twig debugging, I see it's using the same template as the navbar drop-down menu, so I can't write a separate template either (or can I?)

Ok, I sorta figured this out. It might be a hack, but if I start with initial menu level: 1, maximum menu levels to display: 1 and fixed parent item to be the menu who's children i want displayed, then it sort of works.

Only caveat is I need to make a separate block for each separate child of the menu. Plus, it is still using the same template to display the menu in both places (header + sidebar). Perhaps using custom blocks and changing its name will generate a new template?

I'd love to hear a better answer if there is one.


Restrict permission to custom modules in drupal I am using drupal 6, and I have created a custom module. This module consists of a form that can be used for adding records to the database.

But I saw that the link to this form (http://localhost/drupal/my_module/form) is accessible to all the users, even anonymous users.

I want to restrict the access to this module and form from all the normal users. I want  only the administrator to access it.

I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.

How can I restrict the access to my custom module ?

Declare a permission with hook_perm(). It is recommended to somehow use your module name in the permission or something unique to your module to avoid conflicts (there is no namespacing, permission names are global).
In your hook_menu() implementation, add 'access arguments' => array('permission name here'). Since the default access callback is user_access(), the menu system will call user_access('your permission name') to check if the current user has access to that menu item. See hook_menu() documentation for more information. You can also use user_access() directly in your code, if you want to check permissions somewhere else; for example for blocks, you can use that function directly.
Then, you can create whatever roles you want to and give them the permissions of your module at admin/user/permissions. The important distinction here is that permissions are controlled in modules (which can be more or less generically written) while roles and the permissions they have are site-specific.

Then, make sure to rebuild the menu (by using devel.module or saving the modules form) and you should be good.


Views - Excluding a nid screws up "More" link I have a view for my news overview in which I'd like to show 5 latest items. This works perfectly. Until I want to exclude the NID i'm on right now.

I exclude the NID by using the contextual filter and exclude the current Nid.

However; this screws up the More link attached to the view. It wants to go to the excluded NID now(Because of the contextual I think).

How do I get the More link to go to my news overview(As it is without the contextual filter) but still exclude the current NID?

Add "Content: Nid (Nid)" field and mark it 'Exclude from display'.
Now add "Global: Custom text" field, in its configuration add 'More link' into text box and then select "Output this field as a link" under REWRITE RESULTS and provide node/[nid] as a link path.


Add Node Content Before A view? What's the best approach at adding a node above a view. Right now i'm using the views html (before) to add 3 links to pdf's and some text.

I'm not interested in using panels; primarily, because the content has to appear below the view header.

Would it be best to add each file as nodes and join the view with a relationship?

Change the page view to a block view and add the block to the nodes in the content region.


Define form for field_attach_form I have an custome made entity

  function sbsl_order_entity_info() {
    $entitys = array();

    $entitys['sbsl_delivery_information'] = array(
      'label' => t('Delivery information'),
      'controller class' => 'EntityAPIController',
      'base table' => 'sbsl_delivery_information',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'delivery_information_id',
        'bundle' => 'bundle',
      ),
      'bundle keys' => array(
        'bundle' => 'bundle',
      ),
      'bundles' => array(),
      'load hook' => 'sbsl_order_delivery_information_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Full content'),
          'custom settings' => FALSE,
        ),
      ),
    );

    return $entitys;
  }

I want to attach a form to my widget with field_attach_form

but can't figure out where i should define the form elements

You need to do more than simply declare the entity.  The Entity Examples in https://www.drupal.org/project/examples will walk you through each step in the process of declaring the entity, defining the form, and adding menu hooks to be able to manage the entities and the field structure for both the form and display.


How to specify type of script I need to specify the type of script in my theme.info
I add the script in my theme.info like this scripts[] = js/file.js
In the head it look like this

<script type="text/javascript" src="..."></script>

but i need to change the type to

type="application/ld+json"

Can someone help me please

Drupal core adds the text/javascript as default type.

You may include the file using drupal_add_js

drupal_add_js('file.js', array('attributes' => array('id' => 'my-template', 'type' => 'application/ld+json')));


filter view by parent of a taxonomy term In drupal 7, how can I filter content of node type by the parent of a taxonomy term, such that if the content has a child of this taxonomy term it will come out if the parent is chosen as the filter ?

I want to be able to add children without having to modify the view each time as to which terms are in the filter, having it rely only on the parent as the filter by term.(can be done using depth level from the parent term)

There is a view filter as Content: Has taxonomy terms (with depth) which describes as -

Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.

You can select one of the parent term and set the depth of its child terms too.


Clean url for custom query parameters I have a custom filter form in my site and the form submitted by the filters adds 2 Get variables to the url. However, the variables appear in the form of:

http://example.com/newpage?param1=a%2Cb&param2=c

instead of:

http://example.com/newpage/param1/a%2Cb/param2/c

I have Global redirect clean url enabled and I have pathauto module in my installation and clean url test to checl mysite.com/user/login works fine.

I have tried a couple of plugins eg. query_parameters_to_url but they are not working for that page and I tried adding hook_url_outbound_alter and hook_url_inbound_alter in my custom module but they overwrite all the urls.

Can anyone suggest a way to implement clean urls for somehting like this with affecting the urls for other pages in the website?

Are you using Views? If so, you could try using Views arguments for exposed filters: https://www.drupal.org/node/54455


JSONP requests not working in REST server This is related to a bug report I filed just moments ago. If there's someone who has successfully used the REST server in the Services module with JSONP requests (cross-domain), I'd be happy to hear about it.

I'm currently trying to get cross-domain JSONP requests in services working. However, it seems that I'm out of luck. I have created a sandbox Drupal installation with just the service (and dependent) modules installed. The endpoint for testing is setup as follows:

name: api
server: REST
debug: disabled
authentication: session

The REST server is setup as follows:

response formatters: json, jsonp
request parsing: application/json, application/x-www-form-urlencoded, multipart/form-data

All resources provided by default are turned on. What I'm trying to achieve now is to get the user logged in, in order to be able to access other, permission based ressources such as node etc.

The test request is as follows:

url and params: http://d7.sandbox/api/user/login.json?callback=test&username=test&password=test
http header Content-Type: application/json

The response returns a 401 HTTP header and the following message:

401 (Unauthorized: Access denied for user anonymous)

It seems that this is not the desired behavior. JSON requests (e.g. a POST request to api/user/login.json) work fine. However, these cannot be used for applications running on other domains or devices to retrieve data from Drupal over the REST server.

Any ideas?

P.S. I went through the tests in the services package. It seems that tests for the JSONP functionality are missing as well.

Try POST method instead of GET. Drupal won't allow authentication through GET method due to security reason.


User group / user access to files Drupal 7 Is there an easy way (as in with some module) to restrict file downloads to certain user groups or users in Drupal 7? Tried to search and found only questions with no proper working answers.

I know about private files however that seems to restrict files only with logged in users not with certain user groups or individual users. I also know about content access module, but that does not restrict file downloads at all if user knows the direct url to the file.

Drupal supports this natively.

Use private file access and content_access to support granular access to your content.

Due to some bugs here and there I had to rebuild the permissions (/admin/reports/status/rebuild) after configuring content_access a usual clear cache wont work here.


Alter Commerce Line Item Order Edit Form I would like to add a column on the line item table on the orders edit page. I've tried to use theme_registry_alter($theme_registry) to override the commerce line item theme_commerce_line_item_manager, but it seems like it's not working. Below is my code:-

function MODULE_theme_registry_alter($theme_registry) {
  if (isset($theme_registry['commerce_line_item_manager'])) {
    $theme_registry['commerce_line_item_manager']['theme path'] = drupal_get_path('module', 'MODULE');
    $theme_registry['commerce_line_item_manager']['function'] = 'MODULE_commerce_line_item_manager';
  }
}

function MODULE_commerce_line_item_manager(&$variables) {
  return 'Print something';
}

Am I missing something? Or is there any other way to alter the display or add a new column on the table?

I've also created a patch, but I don't feel it's the solution to alter the display. Please help. Thank you in advance.

If you want to add an editable column, you cannot do that just through the theme layer (though I think the same would hold true even for a non-editable column). Instead you need to alter the form element that gets created, even if it's just through an order edit form level alteration. First you need to create the elements you need in the form array and then you can override the theme function to ensure they get rendered into the table in the right column.

You should also look up documentation on how to override theme functions in general. You shouldn't need to alter the theme registry, just place the theme function in your theme's template.php, copy the functionality of the default theme function, and alter it to your need.


MedialEment.js module not seeing the installed library I've just installed the MediaElement.js module and downloaded the corresponding library but in the modules page it won't turn on because it's not finding the library.

i have other libraries running so i know it's in the right place.

the Media Module version is 7x-1.2 and the on the webpage the version is
2.15.1

i've cleared the cache, run Cron and renamed the folder to mediaelement

how the freak do you trouble shoot something like this? this should take like 10 mins to do and now it's going on 40mins trying to troubleshoot.

The easiest way to debug something like this is to look at the MediaElement module itself.

Its implement of hook_library() contains the following:

$libraries['mediaelement'] = array(
    'title' => 'Media Element',
    'website' => 'http://mediaelementjs.com/',
    'version' => '2.1.6',
    'js' => array(
      // The mediaelement script detects the path to itself to call other files
      // in the same location. With preprocessing this is problematic as the
      // script is no longer in the same directory as its other assets. There
      // is an option that can be passed into the script with its location.
      // @todo Update all calls to mediaelement to pass in the assets location.
      $path . '/build/mediaelement-and-player.min.js' => array('group' => JS_LIBRARY, 'preprocess' => FALSE),
    ),
    'css' => array(
      $path . '/build/mediaelementplayer.min.css' => array('group' => CSS_SYSTEM),
    ),
  );

So it would appear the module is looking for

sites/all/libraries/mediaelement/build/mediaelement-and-player.js
sites/all/libraries/mediaelement/build/mediaelementplayer.min.css

If you make sure those files are in the right place, you should have no more issues.


Rendering a module's template contents in the page body I've been digging through the Drupal docs and haven't found a solution for this:

What I'm trying to do is to create a module with a URL using menu hooks. I've got that far. When this URL is viewed, I'd like to insert some HTML and JS code in the body but I haven't managed that. I've been trying to use templates.

This is what my module looks like:

<?php
  function hello_menu(){
    $items = array();

    $items['nodes'] = array(
      'title'            => t('My Nodes'),
      'page callback'    => 'helloworld_output',
      'access arguments' => array('access content'),
    );

    return $items;
  }

  function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'file' => 'timeline.tpl.php',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }

  function helloworld_output() {
    header('Content-type: text/plain; charset=UTF-8');
    header('Content-Disposition: inline');
    return theme('timeline', array());
  }
?>

..and this is what I want rendered in the body.

If I place this code into my timeline.tpl.php, it doesn't get rendered in the page but before the whole content. Do I need to wrap this in PHP tags?

How can I get the onLoad() function to fire once my Drupal page is loaded. I a normal HTML page, I could use the body onload= callback.

(It looks really simple when you've worked with Drupal but for a first-timer, it's been a nightmare.)

The best way to add the JavaScript in Drupal is to have an external JS file like helloworld.js in your module/theme and include it using the function,

  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
   );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

For more info see drupal_add_js()

  How can I get the onLoad() function to fire once my Drupal page is loaded. I a normal HTML page, I could use the body onload= callback

jQuery(document).ready is similar to your onload function that you are trying to call in your HTML body.

UPDATE:

Add the "template" instead of file in your  hook_theme for using templates like,

 function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'template' => 'timeline',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }


create a custom node token I want to create a new token form the selected item in the list box of currently submited node and set it as url alias of the node.

unfortunately, I need keys of select box as token but default tokens do not have this item(it just has labels of listboxes). so I decided to create it's token programmatically.

this is the code but I do not know how to set selected item of list box in $value

function cool_token_token_info() {

  $info['tokens']['node']['key1'] = array(
    'name' => t('My cool token'),
    'description' => t('A token I use to show that I am cool.'),
  );
  return $info;
}

function cool_token_tokens($type, $tokens, array $data = array(), array $options = array(),$node=array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  if ($type == 'node') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'key1':
          // Work out the value of our token.
          if (isset($node)){
                $value= "here I want to have key of the selected item in the listbox of current node";
          }else{
              $value="not working";
          }
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

I tried

field_get_items('node', $node, 'field_parent')

and many many other ways but it does not print anything

Check this example code:

/**
* Implements hook_token_info().
*/
function yourmodulename_token_info() {
  $info['tokens']['node']['city'] = array(
    'name' => t('Venue City'),
    'description' => t('Returns the Venue city (Location)'),
  );
  return

$info;
}

/**
* Implements hook_tokens().
*/
function yourmodulename_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    if (isset(

$tokens['city'])) {
      $replacements[$tokens['city']] = pathauto_cleanstring($node->field_location['und'][0]['city']);//here I retrieve the value of the city in the location field.
    }
  }

  return $replacements;
}


image in newsletter does not apply image style (defaults to original size) I'm using a simplenews template (simplenews-newsletter-body.tpl.php) to output with mimemail in html.

Everything works as it should except that the image in my newsletter is always taken from the original size (/sites/default/files/blogs/blablabla.jpg) instead of the smaller "image style" that I created.

In my template, I use the token: [node:field_image], as it's the only available choice I found.

Do you guys have an idea of what I should try?

Thanks

Disclaimer: I've not personally tested this in detail...

To apply specific formatting to an image token (thus applying an image style to the URL) I think you'll have to define a "token" view mode for relevant node content type. Once this view mode is setup you should be able to configure display settings on your field_image field (within this view mode) which should used when the token is rendered.

Some instructions on that are available here.

To get full field token support, and therefore this feature, I think you have enable the actual token module. It looks like core's token support does not fully cover field tokens in this way.

It may also be worth looking into the imagecache_token module. If I'm not mistaken it would allow you to declare an image style on your token directly via chaining, something like [node:field_image:style_name]. However, that module is not available as a stable release yet, and it's compatibility with field tokens is not totally clear.


How to limit flagging of articles to users with sufficient userpoints using Rules? I am using User Points and Rules. Users earn points for publishing and commenting but are deducted points for flagging their articles for announcement on the front page (a kind of a fee). The fee per announcement is say 150 points.

Obviously, if they don't have at least 150 points, they should not be able to flag. So I need a rule that would check if the author has at least 150 points and if not - block the flagging action with an error message: Sorry, you don't have enough.

Yet, I just can't figure out how to set up such a rule. Any help would be highly appreciated.

Here are the headlines of a possible solution to answer this question:

Step 1 - Create a designated role

Create a new "role" corresponding to users with (say) 150 points, assume you name the role UsersWith150Points.

Step 2 - Limit access to the flag

Secure the access to the flag to users with role UsersWith150Points.

Step 3 - Create some Rules logic

Any time a user gains points, use a rule to check if the user has at least 150 points. If so, have the Rules module grant access to the UsersWith150Points role.

Similarly, if a user looses points, also use a rule to check if user no longer has at least 150 points. If so, have the Rules module remove access to the UsersWith150Points role.

Sounds easy and pretty forward ... except ... there is no (easy) solution to have a Rules Condition to "check the current user points for a user" (unless you're willing to use custom PHP logic in your Rules Condition). However, the clue to make this rule work anyhow, is to use as a very first Rules Action "Load user points of a user". For an example rule, which is close that what you'd need, refer to "How to create rule to change user role based on points (using User Points module)?": you'd only have to add a Rules Action to grant or remove some role (and adapt the user points threshold to your '150').


Create a view with checkboxes per role, that generates an email to an admin I want a registered user to be able to tick rows in a table, and then submit an email to a predefined email address containing the titles of the selected rows.

VBO almost does what I want - in that there is a "send email" option, but on clicking the button it displays a form to be filled in with email address, title subject etc to send the email - I don't want that, I want it just to send a single email when the user clicks the button containing the titles of the selected rows.

There is Views Send module, you may try this.

Views Send enables you to send mass mailing from a View.

This module support tokens and Global: Send E-mail with VBO.


Is it possible to search a view of views? I have a View that is a list of users. One of the fields is an Include View field.

This field includes another View which has a contextual filter for the user, and shows the node that was created in a certain month by that user (if it exists).

These nodes have categories and I would like to have a filter on the main view where I can sort out which users have a node in a certain category. But due to the nature of included Views, I can't find a filter that works.

Is there a way to search a view that is an Include View?

Under Advanced (located on the right side), for Relationships add Content Authored

Then in Filter (located on the left side) add Content Type and expose the filter.


How to prevent subsequent Rules to be executed if a previous rule is executed? I am using Rules to get the price in Drupal Commerce and I have three different rules to apply when I am calculating product price. The problem is that if the first one is executed I don't want to execute neither second nor third. Second one is executed if first one is not executed and the third one shouldn't be executed neither. The third one is only executed if first one and second one are not executed.

Summing up, I would like prevent the execution of subsequent rules if a previous rule is executed. How can I do that in Rules?

As far as your question title says "Execution Order", rules have weight which you can set in the settings tab which you will find on rule manage page.

  Order rules that react on the same event. Rules with a higher weight
  are evaluated after rules with less weight.

As far as your query concern, it seems you need to pick up he right condition while setting up those three rules,you can also use php in the condition if your condition is quite specific.The rules automatically execute their actions based on if condition get satisfied.


Display an image from an external database I created new image database on localhost (other than Drupal original database) that has images in one column. Then I installed the Views Database Connector module; I could integrate it with Drupal to display the content of the new image database. I can easily see columns like name, email, phone number stored in this new image database as string of characters, which are all text columns. When it comes to display an image from the external database, I am stuck.
I tried saving images in two formats.

As URL linked to the path of the image file
As a BLOB

In the first case, I see the URL; in the second case, I see a string of characters.
How do I make the Views module understand that this field is an image it should display as image and not as text?

Views fields have an option to overwrite the output of the field. You can use this to add any html you want, using twig. You'll have all fields rendered before your field available as twig variables.
In your case, since you know that you're getting an image url from your external database, you can rewrite the output of your field using twig. For example:
<img src='{{ my_image_url }}' alt='{{ "Alt text for my image"|t }}'>

To access the Rewrite Results option, click Edit on your field in the Views UI. Near the bottom of the dialog, you'll see several collapsed fieldsets. Open the Rewrite Results fieldset and check the box for Override the output of this field with custom text. You'll get a text area and another fieldset, Replacement Patterns, below it that lists all variables available for your rewrite. Find your field name for your image url and write your output similar to the snippet above.


Custom token replacement I am using Notification to subscribe to different content types so that I can receive emails when a user creates/updates a particular content type.

The following is an email I generally receive from Notification.

 Greetings, ajinkya.

    These are your messages
    New content of type Blog has been submitted
    - Blog Test, Friday April 12
    Read more [node-url]

The problem is that the token [node-url] is not being replaced with a link to the node that has been created, and I am not able to find any interface that would allow me modify the token replacement behavior. Do I need to manually change the code in Notification?

The [node-url] token is a real token define by the token module. I would make sure you have the latest version of the token module. I believe this token has changed names a couple of times but I think thats the correct token.

I would make sure you're running the latest version of the token module if not update and hopefully that would fix your problem.


Will I loose this content or the content will be saved? I'm new in drupal. I have one site that is running on drupal version 7 and now needs to be upgraded. My question is: I have big content in this site, after the upgrade will I loose this content or the content will be saved?

No, you will not loose any content after upgrading the site. But before upgrading the site please take care of the following things.

Back up your database.
Back up your code.


Face detection like seen on facebook As we see in facebook, that it can detect & tag persons within a picture. Is there any way to achieve this from Drupal? any module exist?

The main purpose is to verify each user account- so everybody has only one account. Lots of country people don't have any National ID/passport. So, how can we trace their unique identification? Mobile number is a way, bt one person can have multiple numbers.

OR, is there any way, we can scan finger print as iphone6 has that built-in function........

I know i'm asking for too much,,bt I already need that kinda stuff in job :(

Any suggestions are welcome .....please

I didn't think there was a module, but I found one. Take a look at this module. From the project page:

  Face Detection module uses the jQuery Facedetection library to provide
  an image viewer jQuery plugin.

  It only has been tested on Chrome, Firefox 3-8, IE 9


How do I define checkboxes in a form? I have a form where I need to add a checkboxes field. The purpose of this form is to display some values from the database. I would like to display id from my database table as checkbox' value (when "active" = 1) and url as checkbox' labels.

The database table's structure is the following.

id | uid | hash          | url          | active

1  | 1   | myhashstring1 | example_url  | 1
2  | 1   | myhashstring3 | example_url4 | 1
3  | 1   | myhashstring2 | example_url2 | 0

How can I achieve this?

As per Drupal 8 form api you can define checkboxes like below:

$form['high_school']['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => array('SAT' => $this->t('SAT'), 'ACT' => $this->t('ACT')),
  '#title' => $this->t('What standardized tests did you take?'),
  ...
);

In your case you can update above code

$options = array();
$options[1] = 'example_url';
$options[2] = 'example_url4';
$options[3] = 'example_url2';

$form['items_selected'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#title' => $this->t('Title you want to give'),
  ...
);


How to properly delegate form error to parent? I have a form with multiple radios. I need to display the radios in a certain way(separately with additional form elements) so I had to use radio form elements instead of one radios element.

The radios are required but I have an issue with delegating the error to the parent element. I switched off the error message for the radios themselves via the #error_no_message attribute. Now the form error is properly displayed for the parent element but the error message contains the label of the first radio element instead of the parent element. So for example if I have fieldset named "Manufacturer" and it contains radios with labels like "Audi", "Mercedes" or "BMW" and I won't select any radio the form error, after form submission, will say "Field Audi is required." instead of "Field Manufacturer is required".

So how can I delegate the form error to the parent(which is working) but with making the form error to be applied to the parent itself so the proper label is displayed?

I did what I could but in the end I had to create new form element that provided me with the proper structure. The important thing about it though is mostly that it has input so the form element can be properly delegated whereas before I used fieldset which has no input therefore it would not display error properly.


CSS and JS are not showing I just started using Drupal 8 and i am already experiencing problems. In my info.yml file I've added library/ies and in my libraries.yml are those files included. And when I clear cache in Admin, the css is not showing in source code. I've even clear cache in Drush, if that would be the problem but it's not.

Here is my libraries.yml file

global-styling:
version: 1.x
 css:
  theme:
   css/style.min.css: {}

global-js:
 js:
  js/app.min.js: {}
 dependencies:
  - core/jquery

And here is my info.yml file:

name: MyTheme
description: MyTheme template for Drupal 8
type: theme
package: Custom
core: 8.x
screenshot: mytheme.jpg
libraries:
 -mytheme/global-styling

regions:
 header: Header
 content: Content
 footer: Footer
 sidebar: 'Footer2'

What am I doing wrong?

There is a space missing between the dash and the item:

libraries:
  - mytheme/global-styling

And be careful with the indendation. Better use 2 spaces for each level. One space is difficult to see and if you miss one, the whole yaml-file will be invalid.


How to make relationships between users I have the quiz module installed on my website. I have setup two user roles on my site, Student and Parents.

I want to make a view that shows the results of a parents children.

Now I have made two fields in the registration using the profile module.

The number of student
The number of parent

These two fields are now available both for parents and their children. How can I fetch the results of a parents children using this relationship?

I'm thinking I should I say:Show the result of the users were the field "profile_no" is the same?

Is there a better way to make relation between two users?

Thanks everyone!

Using the Entity reference module you can reference all entities (nodes, users, terms etc).

When you use the Entity Reference module you get a field where you can choose one ore many entities to reference. In this case it will be other users you choose (children).

This is the way it could look when you choose children in your user profile.

I suggest you read up on the Module Monday blog post by Jeff Eaton about Entity Reference. to get up to speed on relationships.


Few content types in a View I use Drupal 8 and I need to create a view with few content types. When I navigate to a specific path, I need to list all of them at the same time, but I need something like a filter so that in this view only particular content type is displayed. How can I do it?

It sounds like you're looking for a Contextual filter.

You create a Page Display with a path of your choosing that is displaying many Content types. This is your page that lists all of them, for example my-content-types.

Then you add a Contextual filter to that View called Content type from Content Category.

Configure it with these options:
    When the filter value is NOT in the URL
    Display all results for the specified field
    When the filter value IS in the URL or a default is provided
    Specify validation criteria
    Validator Content type
    Case in path Lower case
    More
    Transform spaces to dashes in URL

You can leave other options as default, although you should read them all and adjust to your needs, for example what Views should do in case your argument doesn't validate, or you need more than one content type filter on the same page.

This Contextual filter adds options to your path based on the content types you have on your system. If you add the name of a content type to your path (in your browser Location bar):
my-content-types/article the Views results will reduce the list to only show Article nodes.

If you enter a path my-content-types/page it will list only Basic page nodes.

There is also an option to override the Title if you need to correct it to name only the content types filtered out.

If you set your Contextual filter to allow multiple values (there are two places for that) you can construct the path with two or more content types to filter them out: my-content-types/page+article.

To test that your Contextual filter is working you can enter the argument for it in the Preview with contextual filters: field and hit the Update preview button if you don't have it set automatically. To view all the results without filtering simply delete the argument or enter all at the Preview or at the end of your path.


How to read testbot feedback / get more info I have created a patch for migrate_spreadsheet, unfortunately it will not pass the testbot. Instead that gives me this (to me cryptic / uninformative) message:

  fail: [run-tests.sh check] Line 0 of : FATAL
  Drupal\Tests\migrate_spreadsheet\Unit\SpreadsheetIteratorTest: test
  runner returned a non-zero error code (255).

Where/what is line 0? My first change compared to the original file was on line 7, where I corrected a class name. The only other two changes in that file where in the docs.

So what does this fail mean?
How can I get more info from the testbot?

If you click the colored patch result (above), you will get to a detailed page. On the top of that page there is a link 'View results on dispatcher'. That will get you to the test. Then go to the 'Console output' (on the left) (direct link).

The actual error appears to be:

  13:56:12 PHP Fatal error:  Class
  'PhpOffice\PhpSpreadsheet\Worksheet\Worksheet' not found in
  /var/www/html/modules/contrib/migrate_spreadsheet/tests/src/Unit/SpreadsheetIteratorTest.php
  on line 187


Are Drush configuration files compatible across all Drush versions? I've been using the same drushrc.php and aliases.drushrc.php files with Drush 6 and 7 and haven't noticed any problems; however, I also haven't used very complicated Drush configurations in the past.

I'm now using different versions of Drush (6-8) for different sites and am trying to confirm whether there are any significant compatibility issues with configuration files in different versions of Drush. I can't find a conclusive answer anywhere in the Drush documentation; anyone know?

Drush configuration files, generally speaking, anyway, only set options for use in various Drush commands.  If an unknown option is used directly on the commandline, this will result in an error; however, Drush ignores unknown options that are set in a configuration file.  This makes it fairly safe to use the same configuration file for multiple versions of Drush.  I have been using the same config file from Drush 5 to present without an issue.

If you do end up with some configuration tricks that only work with specific versions of Drush, you can always make a drush8rc.php file; this will only be loaded by Drush version 8, and will be ignored by all other versions of Drush.


Run a view's bulk operation immediately but in background. Is that possible? Is it possible to run a view's bulk operation immediately after pressing the button but in the background (in other words, without forcing the user to wait until the progress bar completes to 100%)?

I understand that this can be achieved by enqueuing the operation. But the problem of this solution is that execution is postponed until cron is run.

Thanks.

PHP needs something to drive the process, it's not multi-threaded. Drupal's queue process runs by either the client's browser making a series of calls (kind of like it emulates the cron), or by the cron itself.

Why isn't the cron an acceptable method? You can use something like ultimate_cron The control the schedule for each cron tasks.

Update

As @Molot mentioned, the CLI is an option. I believe shell_exec is subject to PHP's timeout (I could be wrong). See this blog post on executing PHP in an asynchronous fashion.


Getting a menu delivered via REST I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.

I can successfully return this example json using this function when I hit the URL.

public function get(EntityInterface $entity) {
  $result = array();
  for ($i = 0; $i < 10; $i++) {
    $temp = array(
      'title' => 'Test ' . $i,
      'href' => '#/' . $i
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.

I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.

How do I get menu item titles and paths based on the menu machine name?

EDIT

Ok, sort of figured it out.

public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $renderable = \Drupal::menuTree()->build($tree);
  $result = array();

  foreach (end($renderable) as $key => $val) {
    $temp = array(
      'menu_item' => $val,
      'route' => $key
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

Right now that will output:

[
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Home",
      "url":{

      },
      "below":[

      ],
      "original_link":{

      }
    },
    "route":"standard.front_page"
  },
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Communities",
      "url":{

      },
      "below":[

      ],
      "original_link":{

      }
    },
    "route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7"
  }
]

any idea why url or original_link are empty?

This was the correct answer:

public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $result = array();

  foreach ($tree as $element) {
    $link = $element->link;
    array_push($result, array(
        'title' => $link->getTitle(),
        'url' => $link->getUrlObject()->getInternalPath(),
        'weight' => $link->getWeight()
      )
    );
  }
  return new ResourceResponse(json_encode($result));
}


How to make an attendance form I specifically hope views can solve my issue.

My views will display the list of students in a specific class and in front of each student's name, I will like to have a button to select whether a student is present or not.

Since this page will be accessed daily(monday-friday), it needs to reset to default everyday but the record must be saved in d database so that we can send the total number of days a student is present in school.

I have tried flag but the issue with the approach is that u can either flag or unflag a user which doesn't allow for daily flaggings.

Could you give me any hint as to what next to try? Do I need to write a module for this?

Modules needed: Flag, Rules, Rules Scheduler (comes bundled with rules)

Create a user flag

Add an integer field to your user fields. Ex: Attendance (this will keep track of the # of days attended)

Create a new Rule

React on A user has been flagged
Actions: Set a data value >> flagged-user:field-user-attendance >> OFFSET : 1

So this will +1 your field every time the user is flagged.

in Rules add a new component.

Component: Rule >> Data Type: User >> Label: att >> Machine Name: att >>
Actions: Unflag a user >> USER: att >> USER ON WHOSE BEHALF TO FLAG: att >> Skip permission check

Go back to your Rule and add action of Schedule Rule Component

Select your component >> SCHEDULED EVALUATION DATE: +5 hours >> Identifier: [flagged-user:name] will be auto unflaged soon >> ATT: flagged-user

so in 5 hours all users that are flagged will be auto unflagged. (this auto resets them for you, so you are ready to flag the next day)

Update

A good solution but the date really needs to get recorded as well – J. Reynolds

Challenge accepted.
In users add a field called "Date Attended" type:text field. In settings Change number of values: Unlimited

In your rule, add Action: Add an item to a list >> flagged-user:field-date-attended >> ITEM TO ADD: click on switch to direct input mode and then put [site:current-date] >> Append item to the end.

This will auto add a new term with a timestamp when you flag a user/student.

You can then use the Field Permissions module if you want to hide this from users so they cant see it and/or edit it.
PS: I think you might know this already, but just in case. To add a flag link to your view, first you need to add a RELATIONSHIP of flag to your view. Then the flag link option will be available to add as a field in fields.
IMPORTANT NOTE: The Scheduled rule will be triggered in the next cron run.


How to add a percent field in content type Simple question. When creating a content type field, we have a float, decimal and integer number type, but how can we create a field with percentage type value, basically a range of 1-100%.

Could you not just create either a integer or float number field and just label the field as "percentage" or whatever? And also use the "suffix" option on the field options to add "%"

You can also set the min and max values of 0 to 100 to keep it within percentage range of options

Or how would you be expecting a percentage field to act different from a float/integer field?


Drupal Facets Block Show everywhere (in non search page) I use facets search and work well but i want to show block everywhere in website please for your help.

I try to create new views with my search index and add facets block in views but i get wrong url ?f[0]=field_places%3A72

Depends on what module you are using with facetapi. If you are using search_api, then when creating the view you can add a view display of type "Facets Block" (like you would add a page, block or panel display).

Using that display you can add a facet block anywhere on your site, even on non search pages. And you can also set the search_path you want to redirect to when using the facet block.


Add a column to a Views table display conditional on argument I have a custom View defined in a module which provides a table display of data which takes a Node ID as an argument.

------------------
| Col 1  | Col 2 |
------------------
| A      | B     |
------------------

I want to be able to check some data from the node that is the argument to see if a certain field is set to either 0 (no extra column) or 1 (an extra column).

Using hook_views_default_views_alter() I can add an extra column to the table using:

function MODULE_NAME_views_default_views_alter(&$views) {
  if (isset($views['VIEW_NAME'])) {
    // Add an extra field to the rider times view
    $handler = &$views['VIEW_NAME']->display['default']->handler;
    $handler->display->display_options['fields']['nothing']['id'] = 'nothing';
    $handler->display->display_options['fields']['nothing']['table'] = 'views';
    $handler->display->display_options['fields']['nothing']['field'] = 'nothing';
    $handler->display->display_options['fields']['nothing']['label'] = '';
    $handler->display->display_options['fields']['nothing']['alter']['text'] = 'Download';
    $handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
    $handler->display->display_options['fields']['nothing']['alter']['path'] = 'download/[nid]/[number]';
    $handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
  }
}

But this adds the column to all the tables regardless of the argument.

I guess there should be a way to add the column through hook_views_pre_render() but I can't figure out how.

The alternative would be to set up 2 views. One with the extra column and one without and conditionally show the correct view based on a Context/Panel visibility filter.

I don't know if this is the best way to do it, but when I've needed conditional columns I've removed them in hook_views_pre_build() (which is before the query gets built). The code would be something like this:

/**
 * Implements hook_views_pre_build().
 *
 * Removes column X on condition Y from all displays of view Z.
 */
function MYMODULE_views_pre_build(&$view) {

  // Check this is the right view.
  if ($view->name != 'Z') {
    return;
  }

  // Check if the column should be removed.
  if (!$Y) {
    return;
  }

  unset($view->field['X']);
}

The code above will affect all displays of the view. If you want to target a particular display just check against $view->current_display as well.


Simple Sitemap using default instead of website URL https://www.drupal.org/project/simple_sitemap/
I am using above module
abc.com/admin/config/search/simplesitemap

When I am generating sitemap via UI or drush simple_sitemap-generate command.
It is using
 <url>
  <loc>http://default/ja</loc>
  <xhtml:link rel="alternate" hreflang="en" href="http://default/ja"/>
  <xhtml:link rel="alternate" hreflang="ja" href="http://default/ja"/>
  <changefreq>daily</changefreq>
  <priority>1.0</priority>
 </url>

On my Website I am using only English language. Other languages are configured. But not using that.
How to remove those?

This happenes when generating the sitemap via CLI cron without --uri parameter. Either pass the Domain into the CLI
drush --uri=https://www.example.com simple-sitemap:generate

or use the web interface to generate the sitemap.


How to use tokens in node titles? For example if I've page title as "Income tax forms 2012" it should change automatically change to "Income tax forms 2013" in Y2013.

Tokens work for node body but not in title. It did not work when I tried.

Any suggestions?

If these titles are on nodes, and you have the Auto Node Title module installed, you should be able to use [yyyy] for the current year in the replacement patterns section.  However, drupal won't automagically go and redo the title for you, but rather, you will have to resave it "next year" for it to take effect.


Why would some features still show Overridden after a revert all --force? Why would some features still show as "Overridden" even after running a full features revert with the force switch? Below are the commands I am running, for the sake of clarity.

drush fr-all --force -y
drush fl

A feature or features may not revert for the following reasons as cited by some developers in the issue queue #744450:

If your feature includes a view views cache could cause it to remain changed; especially, the migrate module (#1)
Other features can cause your feature to be overridden (#10)
Adding a line in your info file (#24)
There are hooks overriding or altering your view (#36)
A view won't revert. So revert the view using the UI (#62)
When Views UI is disabled, it may cause your view to be overriden (#64)
A feature is missing an include file (#82)


Has my site been compromised? Edit
apparently they belong in the includes folder, were they also are. could it be of any use for a hacker to have these two folders in the root?

I've been checking my drupal site and noticed in the root folder were two folders, database and filetransfer:

I dont know if this is hacked or belonging to some module or stuff, does anyone know something about this?

I don't know if you've been hacked, or just accidentally copied those folders to root, but they shouldn't be in root by default.


How to register or track the views of a node per user? I'm looking for a way to count the number of times each user has viewed a particular node. I have many nodes but I need that number to give user points to the viewing user if he or she has accessed that node X number of times over a time span of 24 hours and this on a daily basis.

Is there anything that can do (track) this or is there a way that I could create this feature "without" writing my own module and without writing php code? I'm no Drupal Ninja ...

I've been looking at the node view count module but that doesn't allow the users themselves to see their view count.
The best way of displaying that number would be through Views (obviously).
I've been thinking about creating an integer field on the user account settings page but that wouldn't actually not show me which node that user has accessed.

Any ideas?

Update: The Node View Count module (suggested in one of the answers) is unstable (throws errors, breaks the site), has no documentation and simply does NOT provide a count of how many times 1 particular user has viewed each node (of a certain content type).

I think You've  missed something from the Node View Count module.

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

Note: Make sure to give permission for users to see their node view count.


How to list all the form IDs I have installed CAPTCHA module. In CAPTCHA module I need to give the machine name of a form of another module called Printer, e-mail and PDF versions. How do I find the machine_name of this from.

If I could list all the machine names somewhere, I will probably figure out the machine name of that form.

Creating a registry of all form IDs on a site is, in general, impossible because you can create dynamic form IDs by using hook_forms. If you want to add an identical button to, say, every image in a gallery you might actually want to do that.

function example_forms($form_id, $args) {
  $forms = array();
  if (!empty($args) && is_object($args[0]) && isset($args[0]->nid) && $form_id == 'example_myform_' . $args[0]->nid) {
    $forms[$form_id]['callback'] = 'example_myform';
  }
  return $forms;
}

now you can call drupal_get_form('example_myform_' . $node->nid, $node) without a problem for any node and have as many form IDs as nodes. I find this easier than putting the gallery inside a form (say, it's generated by Views...) and generating a different-named button with a button-level #submit handler.

Anyways, I am sure there are other problems making it necessary to have an arbitrary number of form IDs.


How to view blocks with Text Overlay on hover? I'm working on a Drupal 7 site and I want to achieve similar thing (view blocks with Text Overlay on hover) shown here. http://ibakatv.com/ under the following blocks (sub sections):
Basically I would like to show text upon mouse hover just like what is shown on the above website.

MOVIE TRAILERS
TRENDING MOVIES ..
LATEST MOVIES etc etc

Also, can someone help how to achieve those view blocks with the navigation as listed above? Do you know this was done? I looked at BX Slider, but I'm unable to achieve it.

Your question appears to be a variation of Create a simple Text over Image Overlay on Hover with Drupal 7 and Views. If you also install/enable the Link module, the node title shown over the image can be a hyperlink to the node also.

Especially this part in it seems to be what you're looking for (be it with some minor variations):

  Create a view 'Overlay'. Create a page which shows content of type 'overlay-image'. It shows an unformatted list of fields. Save and edit. On the edit page, add the fields 'Content: Image' and 'Content: Link' to the fields and exclude them from display.  For the last field add 'Global: custom text'. In the text field, write:

[field_image][field_link]

Curious to hear if this somehow will help ...


Where can I find the link within admin for running the cleaner module, and how to install it? I want to run 'Cleaner' (provided by the Cleaner module).

But when I go to administer > site > configuration, nothing related to  Cleaner is listed.

I have searched Drupal.org, where I learned that this is this link is what I need. Maybe this information is out of date?

Any suggestions?

Edit: I am new to Drupal. Can you tell me, how I install the Cleaner module?

The Cleaner module must be installed before you can use it.


Rebuild Workbench cache? After adding some link to menu, on which Workbench Access has its hierarchy, I cannot immediately use this one, as a section. Tried rebuilding drupal menu (menu_rebuild()), but it's something inside Workbench. Does anyone has dealt with this? To solve this, after adding some link to menu, I need to go to Workbench Access configuration page and just save it. Then it's refreshed, and new items (new hierarchy positions) are available to be set as sections.

If anyone will be looking for similar problem:

I wrote myselft a function. It fetches all the items from menu (which we use as a hierarchy for Workbench Access) and compare them with current Workbench Access items, those that aren't there yet, get inserted. It refreshes caches and it is possible to use all the items as sections, because it's synchronized now.

For now it seems to work. I couldn't find better solution so far.

function update_possible_workbench_sections($menu_name="menu-global-packages") {

$wanted = array();
$records = db_query("SELECT mlid FROM {menu_links} WHERE menu_name=:menu_name", array( "menu_name"=>$menu_name))->fetchAll();
foreach($records as $r) {
    array_push($wanted, $r->mlid);
}

$access_scheme = db_query("SELECT * FROM {workbench_access}")->fetchAll();
$existing = array();
foreach($access_scheme as $r) {
    if( intval($wpis->access_id)>0 && $r->access_type_id==$menu_name ) {
        array_push($existing, $r->access_id);
    }
}

$missing = array_diff($wanted, $existing);
$values_to_insert = array();

foreach($missing as $item) {
    array_push($values_to_insert, array( "access_id" => $item, "access_type" => "menu", "access_scheme" => "menu",
                "access_type_id" => $menu_name ));
}

$query = db_insert("workbench_access")->fields( array('access_id', 'access_type', 'access_scheme', 'access_type_id'));

foreach($values_to_insert as $value) {
    $query->values($value);
}

$query->execute();
workbench_access_reset_tree();
module_invoke_all('workbench_access_save');
return count($values_to_insert);

}


Custom Template for Comment based on node type I'm trying to add a custom template file per content type for my comments. comment--[contenttype].tpl.php is not being picked up by default. I read where this may be a d7 bug or perhaps by design. Then I also read that I can add a preprocess function to my template.php, but I'm still a bit confused. I've added this to my theme;

function bartik_preprocess_comment(&$variables) {

}

but what additionally do I have to add to this function to get it to pick up the suggestions. If someone could give me the exact code for my example it would be much appreciated, assuming that my content type is called car.

According to Drupal 7 Template Suggestions, the custom comment template for a content type should be named comment--[node-type].tpl.php. That is confusing, because the actual template you have to use for an article content type is comment--node-article.tpl.php.

Alternatively you could add your custom template suggestion inside template.php:

function bartik_preprocess_comment(&variables) {
  // Let's say you want to have a custom template like comment--custom-TYPE.tpl.php
  // e.g. for an article content type, the template file will be comment--custom-article.tpl.php
  $variables['theme_hook_suggestion'][] = 'comment__custom_' . $variables['node']->type;
}


Top 10 priorities in performance optimization of a complex Drupal site I read a lot about many ways to improve drupal site performance optimization, but I did not find a clear indication of the top 10 most relevant modifiations for optimizing the performance of a complex site.

I currently am working to optimize a very complex site that has completely grown out of hand and needs serious modification because current page load speed is about 4 to 6 seconds for authenticated users.
The website is mostly being used by authenticated users. The only access restriction is present through the Organic Groups module.

Current state:

90 node types
140 select boxes checked on the admin/modules page
63 Vocabularies
240 views (excluding the additional views displays)
30 rules,
50 rules components
130 node panel variants
10,000 lines of css (excluding the omega base theme and modules style
sheets)

What is the most important to start with, in general?

I won't talk about APC and other Apache optimization tricks.

In in experience:

Enable caching for Views and reduce use of Views
Enable Javascript and CSS compression
Minimize the modules. Disable unused ones. In production I disable as UI's .. the
following script will give you some help.
Most of bottleneck comes from Mysql. I suggest you optimize it and I found this post useful.

Disable User Interface Modules

When not developing you can safely disable Field UI, Rules UI, Views UI, dblog etc. Also I'm sure but we should also be able to disable CKEditor/FCKEditors.

This is what I use in a script:

drush dis --yes admin_menu advanced_help backup_migrate content_type_overview  dashboard diff environment_indicator field_ui help module_filter rules_ui search term_merge update views_bulk_operations views_ui vppr  field_ui  rules_admin devel site_audit  drupalgeddon l10n_client taxonomy_manager dblog


How to add CC to a webform email? I'm using Drupal 7.

Is it possible to add a CC to a webform email?

I was using

function theme_webform_mail_headers($variables) {
  $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
  );
  return $headers;
}

changing it with

    function MYTHEME_webform_mail_headers($variables) {
      $headers = array(
'CC' => 'ccmeail@domain.com', 'X-Mailer' => 'Drupal Webform (PHP/'. phpversion() .')',
 );
      return $headers;
    }

It does not work, I've cleared all the chaches and it does not add the CC.
How could I add the CC?

Thanks in advance.

Just posting this for future viewers:

You can add a hook to the theme_webform_mail_headers in your theme's template.php

function mytheme_webform_mail_headers($variables) {
    $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
    );

    $headers['cc'] = 'email@example.com';

    return $headers;
}


change node author with rules. using an array of users with specific role I am creating nodes with rules and the default author for these nodes is the user 1 (admin).

I have a set of users as 'administrator' roles.
e.g: John, Jack, Sophie

Is it possbible with rules(or custom php code in rules) to change the author from admin to one of the 'administrators' in randomly fashion.

workflow:
create node, author admin --> rule --> change author to John, Jack or Sophie --> save node

Enable Views Bulk Operations

Create a view (Table format is the easiest to manage.)
Add a relationship Content: Author (not required)
Add the author field so you can see who is the current author
Add the field Bulk operations: Content
Under Selected Bulk operations choose Change the author of the content.
Save the view.

Now on the view page you will see a table of all your nodes.

Check the select box next to the rows you need to update the author of.
Under Operations at the top of your view, choose change the author of content.
Hit Execute
On the next page, choose the user and hit next
on the next page hit confirm.
Repeat / Integrate with rules...


Get more drupal.org project usage information Choosing a Drupal module has become an art-form.  Deciding if the module is active, used frequently, growing in usage, etc. is important.

I'm a site builder.  https://drupal.org/project/usage has lot's of good information but interested in levaring the view.  What kind of URL arguments are supported?  I know that:
?sort=asc will work, but can I filter by category, change time range or make a more sophisticated query?  I can add https://drupal.org/project/usage/webform and get more granular on a project basis but would like more control and to understand the URL arguments supported.

I didn't find any Project documents that were relevant.

The usage page comes from project_usage_overview(); it's not a View.  The only parameters are those provided by Drupal's tablesort API, "sort" and "order".

?sort=asc you've already discovered, and the other parameter changes the sort column (?order=Project would sort by project name).


How can I get the english node title printed on the translated nodes edit page. Something along the lines of this

function THEME_AMENDS_form_alter(&$form, &$form_state, $form_id) {
   global $language;
   $lang = $language->language;
   $translations = translation_node_get_translations($base_node->tnid);
   $translated_node = (isset($translations[$lang])?node_load($translations[$lang]->nid):$base_node);
}

I want on the backend of the translated node above the form the english node title to be printed for reference only.

So say we have a contact page, I want on the (spanish) node in the backend above the content edit form "Page Title: Contact" to be printed above where the field for the translated title of the spanish node would be in which the user would translate the title to "contacto".

Basic layout below:

Page Title: Contact

Node title field: [Contacto] <-- input box

Soluton

if($form_id == 'content_page_node_form') {
    $nid = (isset($form['nid']['#value'])) ? $form['nid']['#value'] : false;
    if($nid) {
        $node = node_load($nid);

        if($node) {
            $lang = 'en';
            $translations = translation_node_get_translations($node->tnid);
            $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
            $translated_title = '
English Translation: ' . $translated_node->title . '
';
        }
    }

    $form['#prefix'] = (isset($translated_title) && $translated_node->title != $node->title) ? $translated_title : '';
}


How to display jQuery UI dialog in submit button's onclick and prevent form submission? I'm using Drupal 7 and jQuery Update module set to jQuery version 1.8. I have a form. In it's definition I have:

$form['#attached']['library'] = array(
  array('system', 'ui.dialog'),
  array('aat_pc_product', 'product_form'),
);

In the behavior, I use:

if(!isFormValid) {
  $('<div>' + Drupal.t('Some fields was left blank even when not disabled. Either check "skip line" or fill missing data.') + '</div>').dialog({ modal: true });
}

return isFormValid;

Now, with good old alert it worked great. But when I try do use dialog, in chrome in my console I get:

  Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'curCSS' jquery.ui.position.min.js?v=1.8.7:13

In FireFox it fails in similar way:

  TypeError: c.curCSS is not a function
  ...his,"marginTop",true))||0,v=l+p+parseInt(c.curCSS(this,"marginRight",true))||0,w...
  jquery...v=1.8.7 (row 13)

Updating to dev version of jQuery Update and seelcting jQuery 1.9 or 1.10 does not help - it does not complain about curCSS, but about lack of $.browser() that was removed in jQuery 1.9, and deprecated long ago.

My question is: Am I doing something wrong, or it's a bug between jQuery Update and Drupal? And if it's a bug, is there any version of jQuery update without it?

Is there a way to update jQuery UI to make it match jQuery, without hacking jQuery Update module or updating directly in D:\UniServer\www\misc\ui ?

when c.curCSS is not a function error occures ,just do the following
if any two js included check and remove .. after add this into script

jQuery.curCSS = jQuery.css;


How DO I store/retrieve data and display them in templates? Coming from THE MVC pattern of Django, I am unable to grasp the concept in Drupal 8. I know Twig is used for templating, but what about storing/retrieving data in Drupal 8 and displaying them in templates? Suppose I have a content type (Activity) with fields like Image, Body, Files, etc. Someone can create multiple activities with a WYSIWYG editor. How do I retrieve all these nodes and display them in a page applying my own styles (not using views). Django Views are suitable for this. Can I do this without developing a module?

One way to achieve this is using preprocess function. In your theme's '.theme' file, write a preprocess function. Example:
In bartik.theme

function bartik_preprocess_html__node__28(&$vars) {

$nids = \Drupal::entityQuery('node')
        ->condition('type','article','=')
        ->condition('status',1,'=')
        -> execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $key => $value) {
$title = $value->title->value;

}
$vars['title'] = $title;

}

(node__28 is any node page where you want to see all results, I made this basic page)

Now in html--node--28.html.twig template, retrieve title of content type = article

{{ title }}


content field user reference populated by view (views2)? Drupal-6.22

I have numerous content types where one or more users are associated with the type.  On the bottom of the field definition page there is an advanced section where it asks for the name of the view to provide the content.  I've created a view but it is not showing in the drop down in this area. What does one have to do in order to make a view available for this content field drop down?

The field area reads: Advanced - Users that can be referenced (View)

Please provide a URL where this is explained?

Thanks

The way I understand it, CCK will list all views on your site that return USERS, so, make sure your view is of type USER not NODE.


Reorder Content Types in ("/node/add") Is there a way to reorder the content types shown on node/add?

Yup! Simply edit your "Navigation" menu (at /admin/structure/menu/manage/navigation) and reorder the menu entries under "Add content". Now when you go to /node/add they'll appear in whatever order you set them in your "Navigation" menu. Example screenshot below. On /node/add they will appear as Basic Page, then Article.


How to add nodes inside admin area, e.g. for admin documentation I have an admin theme set. When I create a page in my custom module with an admin/... path it is rendered with the admin theme.

I've set up a node type for documentation and I'd like these to be inside the admin area. I've set the default menu to Management and I've given the page an alias that begins with admin/ but it's rendered in the normal (non-admin) theme.

How can I add nodes that will be considered part of the admin area, and rendered with the admin theme?

This can be done using Administration theme module:

  The Administration theme module allows you to use this theme on more pages like :

  batch processing pages
  devel node load and render pages
  coder code review pages
  pages you define yourself in the provided textarea

Emphasis mine.


Hook that runs on admin pages I'm trying to find a D7 hook that runs on admin pages (admin/people/create to be exact). I've tried many hooks, but none of them seem to be firing on admin pages. What is the best way to detect if user is on admin/people/create?

Thanks

In case other people have the same question for D7, you can always use hook_page_alter(). It will be invoked on all pages. Here's an example:

function YOUR_MODULE_page_alter(&$page) {
  // Check if the user is on /admin/people/create.
  if (current_path() == 'admin/people/create') {
    // Do whatever you want.
  }
}

However, do bear in mind that:

This code needs to be in a custom module in order to be invoked everywhere.
If you add this to your front end theme, it will not be executed unless you are using the front end theme for managing the site as well.
This way you can recognize if the user on that page, but you will not be able to alter the form. To alter the form, check out @Weboide's answer - you'll have to use hook_form_alter().


how to filter view having three group with one or and two and group? I am having a view with three group filter i want to add condition like this

Example Below:

group1

field1 (and)
filed2

AND

group2

field1 (or)
filed2

OR

group3

field1 (or)
filed2

what issue i actually face is when i change the second and  third group filter to AND automatically the first and second group value is changing to OR how to solve this

Thanks in advance.

For ease of use I would suggest looking at Views Raw SQL. While Views is a powerful query builder, it sometimes makes assumptions and in a general sense is designed to solve 80% of general types of listings and queries -- when implementing advanced logic, it can fail short.

Another option is to use the Views API Hooks (hook_views_query_alter) and alter the query using a small custom drupal module.


Is it possible to add a wildcard in template.php to apply function to multiple items I have a webform with 20 different select options under different fieldsets and they all need to have a custom drop down select field title. To achieve that you use this:

function theme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_653') {
    $form['submitted']['products']['product_1']['quantity']['#empty_option'] = t('Qty');
  }
}

Now each form is identical except the ['product_1'], so to make that custom title work on every field is that you have to copy paste 20 lines of same code and just rename the ['product_1'] to ['product_2'], ['product_3'] and the etc.

I was thinking is there some method like in CSS where you can use wildcards, e.g. (to get the idea): https://stackoverflow.com/questions/5110249/wildcard-in-css-for-classes

So you could achieve all that with just one line of code and apply it to all quantity fields in the webform.

So instead of spamming:

$form['submitted']['products']['product_1']['quantity']['#empty_option'] = t('Qty');
$form['submitted']['products']['product_2']['quantity']['#empty_option'] = t('Qty');
$form['submitted']['products']['product_3']['quantity']['#empty_option'] = t('Qty');
And so on...

You could do something like

$form['submitted']['products']['*']['quantity']['#empty_option'] = t('Qty');

But it doesn't work.

This seems more like a general PHP question, but I'll answer it anyway with some Drupal context.

You usually loop through the array in these instances. You'll find looping as you code in Drupal more and more common.

Consider the following structure:

$form['submitted']['products']['product_1']['quantity']['#empty_option']

Assuming that you're editing the ['quantity']['#empty_option'] of each [product_x], you loop through your array like so:

foreach(element_children($form['submitted']['products']) as $key) {
  $form['submitted']['products'][$key]['quantity']['#empty_option'] = t('Qty');
}

element_children gives you the keys for the array which don't start with a hash #. Whether or not it's suitable for your particular array is a different matter. You can inspect your variable using var_dump($variable) or through Devel module's dpm($variable, 'label'); function.

You may find that you may need to run some if statements to test if $key starts with product_ if you have more than product_x keys under $form['submitted']['products']

foreach(element_children($form['submitted']['products']) as $key) {
  // Only proceed if array key starts with product_
  if (substr($key, 0, 8) == 'product_') {
    $form['submitted']['products'][$key]['quantity']['#empty_option'] = t('Qty');
  }
}


Price before/above add-to-cart button Have struggled with this for a couple of days and find no easy solution (TWIG?)
Drupal commerce 2.X (D8)

I need to move the price before/above add-to-cart button
Like this:
Color:
Red
Size:
Medium
Price:
$ 49,00

Add to cart

I need to do this because the price of the product changes when you choose variation.

Thanks!

Yes indeed. a major frustration and it just makes no sense the way it is. i asked this same question a year ago and it has still not been solved. if you solve it please put the solution here.

meantime, you can use jquery appendTo() to solve it in a very ugly way. the price will initially load above the attributes and then jump down to the correct place above the cart button. it is not a pretty site but at least it works.


Create Custom Select Webform Element I asked this last time with 'Select Other', but I am still not understanding how to change custom element's type. In this scenario, I am attempting to build a Select type webform element. I am reusing the Webform Example attached to the webform module. But my issue is that I can not change it from an <input> to a <select> type.
Inside, \webform_example_element\src\Element\WebformExampleElement.php I have tried:
  public function getInfo() {
    $class = get_class($this);
    return [
      '#title' => $this->t('Facility'),
      '#type' => 'Select',
      '#input' => false,
    ...
   }

AND I have tried:
  public static function processWebformAssignedBy(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#tree'] = true;
    $element['#type'] = 'select';
    $element['#input'] = false;
    $element['#options'] = [
      '1' => 'One',
      '2' => 'Two',
    ];

Using X-Debug, when the page is loaded I get:
$element = {array} [48]
 #type = "select"
 #title = "current_facility"
 #multiple = false
 #access_create_roles = {array} [2]
 #access_update_roles = {array} [2]
 #access_view_roles = {array} [2]
 #webform = "generate_system_number_form_1_"
 #webform_id = "generate_system_number_form_1_--current_facility"
 #webform_key = "current_facility"
 #webform_parent_key = "net_new_process_information"
 #webform_parent_flexbox = false
 #webform_depth = {int} 1
 #webform_children = {array} [0]
 #webform_multiple = false
 #webform_composite = false
 #webform_parents = {array} [2]
 #admin_title = "current_facility"
 #webform_plugin_id = "facility"
 #webform_submission = "121"
 #access = true
 #webform_element = true
 #allowed_tags = {array} [78]
 #element_validate = {array} [1]
 #pre_render = {array} [1]
 #after_build = {array} [1]
 #_webform_access = true
 #_webform_states = {array} [0]
 #theme = "input__webform_example_element__webform_generate_system_number_form_1__form__current_facility"
 #theme_wrappers = {array} [1]
 #formdazzle = {array} [3]
 #process = {array} [3]
 #input = false
 #value_callback = {array} [2]
 #defaults_loaded = true
 #tree = true
 #parents = {array} [1]
 #array_parents = {array} [3]
 #weight = {float} 0.007
 #processed = false
 #required = false
 #attributes = {array} [1]
 #title_display = "before"
 #description_display = "after"
 #errors = null
 #id = "edit-current-facility"
 #name = "current_facility"
 #value = ""
 #options = {array} [2]

But after returning, I still get an <input> field. Any suggestions how to alter the input type to be select? Thank you

After long research about Webform elements, I have finally figured out the solution. Extend the Select Element. :)
use Drupal\Core\Render\Element\Select;

class Facility extends Select {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $properties = parent::getInfo();
    $class = get_class($this);
    $properties['#process'][] = [$class, 'processMyCustomSelect'];

    return $properties;
  }

 public static function processMyCustomSelect(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add and manipulate your element's properties and callbacks.
    return $element;
  }
}

this post really helped me out a lot: Webform Custom Radios/Checkboxes Element does not get rendered in webform : Drupal 8


If one block has content do not show other block I have a region in my page.tpl.php file called "seminars", and it has two blocks (views) assigned to it, one is called "view_upcoming_seminar" and the other is called "testimonials". The content shows up great for both blocks (views) in the region. What I'd like to do is only show "testimonials" if there is no content in "view_upcoming_seminar".

I'm just not sure what the best approach is, and any pointers in the right directions would be grand!

Open the "Advanced" section on the "view_upcoming_seminar" View settings page, and add a "No results behavior" of type "Global: View area". Point it to your "testimonials" View.


Pull webform submissions in different webistes to one end-point hypothetical example:

website1 has 2 webforms, I need to access the submissions of the 2 webforms in another website2

So if an user send the webform in website1 I need to log in as admin in website2 and see that submission. In few words, pull the webform submissions to one endpoint website (without the necessity of click a button or run a command), Master-Slave where the slave is the endpoint website that is only going to show results of webforms.

is this possible?

My use case: I have a lot of surveys in different websites hosted in different servers, I need an endpoint where to collect all the results and show it to my users, so I need have the submissions stored in my endpoint website for show results to my users.

Thanks

Ultimately, there are several ways to accomplish a 'sync' across multiple sites.
However, without more technical information the options are generic at best.  Webforms that include uploads or images may require additional work to configure.

Bottom line, the webform data lives in a table in the database, on each site.  The best solution may not be a module but rather a cron job pulling that data and serializing it on a collection site.  This would be a custom script collating and creating webform content on the collection site.  As such, the webform Node ID would not necessarily be preserved.

Another approach, if the cron job is not preferred... might be to use the built-in mail function from webform, or to create a Rule to send the webform data to a mailbox.  The collection site can be configured to create node content processed from that mailbox.  One benefit is that this could be a non-webform content type.  As such, you can add fields and act on that data in a way to manage it and you could also in this way preserve a record of the original Node ID so that a reference to the source site is possible.  Other fields might be the site URL, notes, if action is required... and so forth.

Here are some references that might be useful in the latter approach:

Add content to your site via email using https://www.drupal.org/project/mailhandler - Mailhandler
http://drupal.stackexchange.com/questions/69134/send-mail-to-email-addresses-from-webform-when-a-content-is-saved - Send mail to email addresses from webform ...
https://www.drupal.org/project/webform_rules - Webform Rules module

Of course, it matters if you're using D6 or D7.  Mailsave & Mailhandler are both included in one popular approach using D6 and Mailsave doesn't have a D7 version.


How do I load entities with Null values? The following fails with an exception.

\Drupal::entityTypeManager()->getStorage('foo_module_division')->loadByProperties(['enabled'=>TRUE, 'parent_code'=> NULL]).

How else do I specify I want to load entities whose parent_code field is NULL?

The example of getting articles that has empty body:

  $entityStorage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $entityStorage->getQuery();
  $query->condition('type', 'article');
  $query->notExists('body');
  $nids = $query->execute();
  $nodes = $entityStorage->loadMultiple($nids);


Redirects within hook_user_login I'm writing a module that redirects the user on login and am having trouble getting anything to work. Here is what I tried within hook_user_login:

submission.info

name = Submission
description = Handles Redirect to node/add/page on Login
core = 7.x

submission.module

function submission_user_login(&$edit, $account) {
  //$_REQUEST['destination'] = 'node/add/page';
  //$GLOBALS['destination'] = 'node/add/page';
  //$edit['redirect'] = 'node/add/page';
  drupal_goto('node/add/page');
}

Try to change drupal_goto with $_GET['destination'], e.g.:

function submission_user_login(&$edit, $account) {

   // Redirect user to to desired location.
   $_GET['destination'] = 'node/add/page';
}

Hope this will work.


Add an HTML file in a custom module I have an external application I have to add in my custom feature of Open Atrium. There is some JavaScript files I have already added to the module, and some CSS files.

To implement the application, I need to include an HTML file in the module's output. In which way can I do this?

You can simply add <?php print file_get_contents('my_file.html'); ?> in your module's template file, or even do that inside your module's callback function, and return it as output.

It's a little bit messy, but including off-site files or scripts is always a little messy.


Output the width & height of an image using a particular image style In Drupal, you can use the following in a field--field-image.tpl.php file to output an image as a URL using a particular image style:

<?php foreach ($items as $delta => $item): ?>
<?php echo image_style_url('thumbnail', $item['#item']['filename'] ); ?>
<?php endforeach; ?>

This will output all images as a URL with the Thumbnail style.

I would like to get the width and height values of that image (with the thumbnail style). How can I do it?

I would like to do it without having to install any extra modules.

image_get_info() is the function that will get you the details. But it accepts uri as the param (Not sure about url). You can try passing the argument.
If you manage to get the path of the images then this function return the following ,

"width": Width, in pixels.
"height": Height, in pixels.
"extension": Commonly used file extension for the image.
"mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
"file_size": File size in bytes.


How to check where in a menu tree a node is & then display a portion of the tree? How can I check where in a menu tree a node is, and in particular how can I determine what its ultimate parent is? And how can I display a portion of a menu tree? Here's an example menu tree to illustrate:

m1
-subm2
--subsubm3
-subm4
m5
-subm6

If I were on the pages linked to from items 1-4, I'd want to find out that the ultimate parent of these items is m1, and then display only the portion of the menu below m1, ie:

m1
-subm2
--subsubm3
-subm4

I am pretty sure Menu Block will do what you need. I have used this module to display portions of menus only under one parent item as you mention and it worked great. It's for Drupal 6 & 7 as well.


How to get the CID number of comments from comment table? If you check the comment table, you can see taht each comment has a CID number.
For each article I need to have the CID number of all the comments for that article.

So I have written the following in node.tpl.php file:

 $result=db_select('comment', 'c')
 ->fields('cid')
  ->condition('nid', $node->nid,'=');

  $record=$result->execute()->fetch();

But I get error. So what is my mistake?

$result=db_query('SELECT cid FROM comment WHERE nid = :nid',array(':nid' => $node->nid));

Hope this helps you.


Added a secondary link through code. Why is my href URL getting decoded? Added the following through code:

// $uri = custompath?type=All&field_id=2&storage=3

$secondary_links['menu_custom_item'] = array(
                      'attributes' => array( 'title' => $label ),
                      'alter'   => 1,
                      'href'    => $uri,
                      'title'   => $label,
                      'language'  => 'en'
                );

Why is it that when drupal renders the link the URL it links to is something like:
http://mydomain.ca/custompath%3Ftype%3DAll%2526field_id%3D2%2526storage%3D201110

Literally it links like that and obviously returns Page Not Found. As soon as I manually change the %'s in the path we're good again. Is there a way to prevent this? Do I need to deconstruct the URI and pass the variables in one by one?

Try using urlencode ...

$secondary_links['menu_custom_item'] = array(
                      'attributes' => array( 'title' => $label ),
                      'alter'   => 1,
                      'href'    => urlencode($uri),
                      'title'   => $label,
                      'language'  => 'en'
                );


Update query is not working In a Drupal 7 custom module, I am updating a record in the database using a form, and I am using the following code to update, but for some reason it is not updating. Can anyone tell me why? I tried like 3 hours to change every possible thing but no luck.

function edit_job_form_submit($form, &$form_state){
  $id = $form_state['values']['id'];
  $job_title = $form_state['values']['job_title'];
  $description = $form_state['values']['description'];
  $cat_id = $form_state['values']['cat_id'];
  $job_type = $form_state['values']['job_type'];
  $company_id = $form_state['values']['company_id'];
  $description = $form_state['values']['description'];
  $location = $form_state['values']['location'];
  $Salary = $form_state['values']['Salary'];
  $benifits = $form_state['values']['benifits'];
  $Nationality = $form_state['values']['Nationality'];
  $Age = $form_state['values']['Age'];
  $join_date = $form_state['values']['join_date'];
  $date_added = date("y-m-d", time());

  $join_date_mod = gmdate('Y-m-d',strtotime($join_date));

  $num_updated = db_update('echelon_jobs')->fields(
    array(
      'job_title' => $job_title,
      'cat_id' => $cat_id,
      'job_type' => $job_type,
      'company_id' => $company_id,
      'location' => $location,
      'Salary' => $Salary,
      'benifits' => $benifits,
      'Nationality' => $Nationality,
      'Age' => $Age,
      'join_date' => $join_date_mod,
      'date_added' => $date_added,
    )
  )
  ->condition('id', $id)
  ->execute();

  //dpq($num_updated, $name);
  drupal_set_message(t('Vacancy Updated Successfully..  '));
}

As a matter of debugging, if you have the Devel module installed, try executing the query at devel/php with hard-coded data. That will help understanding if there is an issue with the  db_update(). Also, when you run the query and an error occurs, the error log at admin/reports/dblog on your site should show you any error message about that query.

In case you need to update or insert values on a table, db_merge() should be used instead of db_update(). db_update() doesn't insert new rows, but updates the existing ones; db_merge() updates the existing ones, or creates new rows.

Once you are ready with a working query, debug the $form_state values; there might a mismatch between database table column type and the data you are trying to put there.


Version numbers of dependencies in testing If I'm submitting a test to the qa.drupal.org testbot, and my module requires a dev version of another module in order to function properly, is it adequate to declare the version in my module's .info file, or do I need to also specify version numbers in the test DrupalWebTestCase::setUp() where dependencies are declared for the test itself?

From the module.info file docs: ( quite long, but informative )
dependencies
An array of other modules that your module requires. If these modules are not present, your module cannot be enabled. If these modules are present but not enabled, the administrator will be prompted with a list of additional modules to enable and may choose to enable the required modules as well, or cancel at that point.
The string value of each dependency must be the module filename (excluding ".module") and should be written in lowercase like the examples below. Spaces are not allowed.
dependencies[] = taxonomy
dependencies[] = comment

In addition, test_dependencies[] can be used to indicate dependencies which are optional but recommended. At this writing they are supported only by Drupal.org's automated testing system. They cause the testbots to check out the projects suggested.
test_dependencies[] = autoload
If you need to specify that a certain module's version number is required Drupal 7 provides a way for this in the dependencies[] field. Version numbers are optional and only necessary if the module absolutely requires another module's specific version or branch.
The syntax for the dependencies[] field(s) is:
dependencies[] = modulename (major.minor)
Where major is the numeric major version number and minor is the numeric or alphanumeric minor version number. x can be used to denote any minor version. Some examples follow.
name = Really Neat Widget
description = An example module
dependencies[] = exampleapi (1.x)

test_dependencies[] = autoload (>7.x-1.5)
...

In the above .info code, the "Example" module requires an "Example API" module with the major version of 1 and any minor version.
dependencies[] = exampleapi (1.0)
This means that the module requires the 1.0 (and only the 1.0) version of the Example API module.
dependencies[] = exampleapi (1.x)
The above module requires any minor version of the module in the 1.x branch (1.0, 1.1, 1.2-beta4, etc.)
The dependencies[] property in the .info file can also optionally specify versions:
= or == equals (optional: equals is the default)
> greater than
< lesser than
>= greater than or equal to
<= lesser than or equal to
!= not equal to

dependencies[] = exampleapi (>1.0)
The above module requires any version greater than version 1.0.
You can optionally specify the core version number as well:
dependencies[] = exampleapi (>7.x-1.5)
The above module requires a 7.x version compatible version of the module and a version greater than 1.5.
Additionally, multiple version dependencies can be specified as comma-separated values within the parentheses:
dependencies[] = exampleapi (>1.0, <=3.2, !=3.0)
This facility can be used to specify a minimal core version by using system as the module name:
dependencies[] = system (>=7.53)
This makes the module require at least Drupal 7.53.
More info: http://drupal.org/node/542202#dependencies


Drupal 7 log-in form doesn't react Out of the blue I'm unable to login into my website:
http://karlssonwilker.com/dev_v2/kw/user

I type my username and my password and upon clicking "log-in" or pressing RETURN nothing happens.
Could it be something related with the database? Disabling javascript, css, removing any custom functions, or clearing the cache tables on phpmydamin seems to have no affect.

No idea what the problem is.

I had a test user created before I started having this problem. You can use it if you care to try.
user: test
pass: test

Anyone came across a similar problem?

Thanks!

There is something wrong with your HTML:

<div id="node_container" <form="" action="/dev_v2/kw/user" method="post" accept-charset="UTF-8">

This is definitely not interpreted as form.