How to make Dynamic Term Link based on content type? My web site has three content types ( Event, Course, Video) and 2 taxonomies(city and schools)
All of them have same taxonomy referenced field.
Eg:New York City events or New York City courses will be listed seperately.

Problem:
How can I make term links dynamic based on content type .

All new york city contents are listing(3 content type contents) if I clicked newyork city term on event content.

I need only event type contents to be listed if I came from an event type content. It should be changed according to  event,course or video content type.
Any help with this would be awesome . Thanks

The easiest way to achieve this is by using Views.

The links rendered in Taxonomy fields (Entity reference fields) are set to go to Taxonomy term pages. The links are constructed with Taxonomy term ID in the URL: taxonomy/term/[TID].

Taxonomy term pages are created using Views, so you can easily Edit the relevant Views to adjust it to your needs. The modification you're after is adding a Contextual filter that filters out only one content type.

With that modification you could type, for example, taxonomy/term/10/article in the browser address bar, and the usual Term page for term 10 would list only results of the Article Content Type.

The other part of your question is how to make the Taxonomy reference link on the node View be sensitive to the Content type it's on, so when it's clicked it goes to the filtered list, and not the general term page that shows all results.

The easiest way to do that is to hide that field from displaying and replace it with a Views Block that would output a similar link, only Contextually sensitive to the term, and to the Content type.

Here are the steps on how to achieve this:

Make term pages sensitive to Content types

Duplicate the Taxonomy term View (it's better to keep the default ones as they are, so you don't mess up the original features and it makes updates more straightforward). Rename it to make sense (Taxonomy term-Content type)
Add a new Contextual Filter Content type from the Content Category (keep the one sensitive to the taxonomy term that is already there, we need it) and 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
Override title
Content tagged with {{ arguments.tid }} of type {{ arguments.type }}
Specify validation criteria
Validator Content type
Validate user has access to the Content type
More
Transform spaces to dashes in URL
Edit the Path to add another % to react to the Contextual filter we just added, so you end up with the Path: taxonomy/term/%/%
Go to the other Display in the same View called Feed and edit the Path there to read taxonomy/term/%/%/feed
Save the View. You can test it by entering the relevant arguments into Preview inside Views (for example 10/article) or by typing the URL into your browser addressbar (example.com/taxonomy/term/10/article).
Optional but good UX: add No results behavior Text area No content of type {{ arguments.type }} tagged with {{ arguments.tid }} has been found. on your Page display and override for that Display only This page (override).

Create taxonomy links on Nodes sensitive to CT

To create links sensitive to the context we need Views Display Block of type Content. We can add it to the Views we created above (because that View is of type Content), or create a completely new View for this. Since this Block Views will be sufficiently different it's better to create a new View for this. Here are the steps for adding a new  Views to accomplish this:

Create a new Views of type Content showing Fields, add a Block Display to the View, change its name to something meaningful you can recognize later on Blocks page: Taxonomy term link sensitive to CT
Add a Filter to limit to your desired Content types (event, course, video)
Under Format option Show settings choose to Hide empty fields
Add a new Field City (or whatever your field is called), Exclude from display, and don't tick Link label to the referenced entity
Add a new Field Content type, Exclude from display and set Formatter to Entity ID (so you get CT machine name so the contextual filter later works correctly)
Add a new Relationship Taxonomy term referenced from field_city and Require this relationship
Add a new Field Term ID (it will use the Relationship from previous step), Exclude from display and set Formatter to Unformatted
Add a new Field Custom text from Global Category and configure it:
Create a label just tomake it easier to build, enter Taxonomy link sensitive to CT
In Text area enter {{ field_city }} (type { type }})
Rewrite results
Output this field as a custom link
Link path: taxonomy/term/{{ tid }}/{{ type }}
Replace spaces with dashes
No results behavior
Hide if empty
Add a new Contextual filter ID from Content Category and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
[your CTs video course event]

Now when you enter a node ID into Preview it will show the link to taxonomy term page that has content type argument added to it at the end.
Set Pager to Display a specified number of items to 1 item
Remove the Title field so you end up with only the Custom text visible and Save the View
Place the Block in Content region, don't Display title, set Content ID to Node from URL, limit which Content type to show the Block on
Edit your Content types (all three) Manage Display to hide the City Taxonomy Field (drag to Disabled)

And now you have the relavant Taxonomy term link that has the added Content type at the end to call on Views term page that will filter out only that content type.


How to save and append comment form without refresh the page in drupal 7 I have a form with comments but this page have counter to cout views of this page.

but every time when comment added on this page that page loaded and my counts increasing
  after comment added.

but i want to count views when page load first time not by comments module  in drupal 7.

One option would be to use the AJAX Comments module:

  Provides ajax comments to Drupal sites. Features:

  Makes AJAX submits
  Allows replies to comments on the actual thread page
  AJAX comments deleting
  Works with CAPTCHA
  Cool jQuery sliding
  views integration

It will allow users to submit comments without a page refresh, bypassing the extra view count.


setting template file using template_preproccess_page not working I have a list of pages with url

?q=value/abc/1
?q=value/abc/2
?q=value/abc/3
?q=value/abc/4

for which i require a specific template.I have written a template_preprocess_page function,but it does not call the required tpl file.But if i set the test variable as
$test = array("value/abc/1");
the template file is being used.Could someone tell me what i am doing wrong..??

function template_preprocess_page(&$var){
 $test = array("value/abc/%");
        if(in_array($_GET['q'], $test)){
            $var['template_file'] = 'testing';
        }
}

Assuming D6 then, in template.php:

/**
 * Implements hook_preprocess_page
 */
function THEMENAME_preprocess_page(&$variables){
 if (strpos($_GET['q'], 'value/abc') === 0) {
   $variables['template_file'] = 'testing';
 }
}

Clear theme registry, or all caches at admin > config > performance to apply.

More info:

  There are two special variables that these hooks can set:
  'template_file' and 'template_files'. These will be merged together to
  form a list of 'suggested' alternate template files to use, in reverse
  order of priority. template_file will always be a higher priority than
  items in template_files. theme() will then look for these files, one
  at a time, and use the first one that exists.
  https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme/6


How can I remove javascript from everywhere but the front page? I tried using this in template.php

function MYTHEME_js_alter(&$javascript) {
  if ($!is_front) {
    unset($javascript['path/to/script.js']);
  }
}

but it doesn't work. Performance wise, would it be as good to have the javascript that's on every page in theme.info, then use drupal_add_js on the front page instead?

You need to update. Below are the update :

if (!drupal_is_front_page()) {
      unset($javascript['path/to/script.js']);
    }

function drupal_is_front_page

Reference Link : Click Here


How can I limit a views_pre_render() to a specific display of a view? I have a views_pre_render() hook that I want to limit to a specific views display.

So far, based on this code, I have this:

function MYMODULE_views_pre_render(&$view) {
  if ($view->name=='VIEWNAME') {
    // ...
  }
}

However, I want to limit execution not to a specific view but to a specific display within that view.  I know the machine name of the display, but how do I incorporate that into the if statement?

Like so:

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAY_NAME') {
    // Do your thing here.
  }
}


Archive using date other than "created" I have a custom content type of "Press Release." I would like to make an archive listing of the press releases, based on a "release date" field in the content type. The archive view built into views uses the "content: created" date, and I can't figure out how to make it work with this other date instead. (This is Drupal 7.)

Any help would be appreciated. Thanks.

You have to install the Context module and make sure the the Date Views and Date Context modules are also enabled. Then your date fields will appear in the format:

Field: Date (field_machine_name)

Contextual filters based on these fields have the same formatting options as those based on node creation date.


Ajax problem on node edit page trigger whole submit I'm facing a very strange problem on one website.

First of all with the module media (I'm using the last version of the module). When click on "Remove" an image, an ajax request is triggered and seems to go through the entire form submit, displays a message above the field but doesn't remove the image.

If I click on "Remove" again then it works normally.

Now when I click on a "Add more" button like for a multiple field_collection, it works fine the first time for the field I click. If I click on an other multiple field (an other field_collection) then nothing happens. I don't know if both problems are related.

When I look into the network, I see Ajax queries with all the datas (some differences like the form token), the response is just not the same.

I'm on jQuery 1.4.4 on admin pages and using the Shiny theme. Drupal is 7.41 and hosted on NGINX 1.6.2-5

I've looked into all the "form_alter" I had, to see if something got altered. I even deactivated all my custom modules, but the problem is still there.

Any clue would help :-)

The problem was due to the contrib module admin_language not handeling properly the ajax callback url on node edit page.

I had to add these url to be included in the config "Use administration language on only the listed pages." :

system/ajax
media/ajax
media/ajax/*
media/*/ajax


Extra include files for hooks I'd like to organize a .module file better by putting related hooks in other .inc files.  So for example, I'd like to take a bunch of imagecache preset definitions (via hook_imagecache_default_presets) out of custom.module and put them in custom.imagecache.inc.

Where in custom.module should I include custom.imagecache.inc?  I assume I'll be using module_load_include()?

If I put it in a hook_init wouldn't that include these hook definitions on every page request?

Current answer is not 100% correct for Drupal 7. In Drupal 7 there is a hook called hook_hook_info. In core this is implemented with the token module via system_hook_info. That means that for tokens the hook can be located inside of module_name.tokens.inc. So yes you can put hooks in related files by groups. Just remember that hook_hook_info must be inside of your .module file.

An example using blocks

<?php
/**
 * Implements hook_hook_info().
 */
function mymodule_hook_info() {
  $hooks['block_configure'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_list_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_save'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view_alter'] = array(
    'group' => 'blocks',
  );

  return $hooks;
}
?>

You should be able to then use a mymodule.blocks.inc file to hold all your blocks information as long at the above code/hook is inside of your .module file.


Hooks and preprocessor confusions. A few important questions I've been using Drupal now for a pretty long time, but this whole hooks and preprocessor thing still gets me confused. And I can't seem to really find a structured documentation to help.

Intuitively it feels like changing a contrib module is not part of theming, but more of module extending / modifying, but it is also theme-specific, so it's confusing to know if this topic is indeed related to the above or not.

Here are some of my questions that I am still left with:

1. are function hooks used in modules the same as theme hooks used in the theme?

2. if a contrib module uses a "hook" is this something i can override or extend in my theme?

*3. if a contrib module uses a hook, say: hook_block() can I then hook the hook to change the module's output?*

example:
inside the contribmodule.module file:

contribmodule_block() { $variables['foobar_item'] = 'foobar item'; }

can this be overriden by the following in the template.php file?

contribmodule_preprocess_block() { $variables['foobar_item'] = 'new item'; }

Is there a guide for all the fundamental concepts? All i can find is the API for hooks, but that says really nothing at all about it other than giving a list of available hooks; zero theory there.

4. if a contrib module has a function which I can NOT override with a hook onto a hook, then how do i change what the contrib module does for my theme? am I forced to hack the code of the contrib module?

Not quite. Generally speaking, normal hooks are used to control the behavior (functionality) while theme hooks are used to control the appearance of your site. If you want to understand more about hooks, you may want to read What are the different types of hooks?.
Since Drupal 7, you can implement hooks in your theme. That said, the best practice is to put alterations to the site behavior in a custom module, and use your theme only for alterations to the appearance.
That depends on the hook. The output of a block can be altered by implementing hook_block_view_alter.
All modules that are built 'the Drupal way' should use theme hooks and render arrays to generate their output. You can always implement a preprocess function in your template.php to alter variables before they go to a template, or override a theme function or template to make it do what you want. See the Theme guide, more specifically Overriding themable output to learn more.

I hope that answers your questions.


How can I download code from Github? I'm still running some Drupal 6 sites (because I'm waiting for the Migrate module to work properly in Drupal 8), and I notice that there are some modules in rupal D6 (like Views) which are still bringing out security releases. However, since the code has been moved off drupal.org, these new releases are not getting downloaded by Drush when I do a pm-update to install security releases.

Is there any way to tell Drush to look on Github for certain modules? Alternatively, is there a git command to do this?

The git command is git clone. You would type:

git clone <repository-url> path/to/modules/module_name


Include View In Node That References Other Nodes Based On Joined Field I'm getting a little confused trying to get this one, thought I'd get some help.

I have two content types (A and B) both with the same list field (My List). I want to include a view in content type A that finds all nodes of content type B with the same My List value.

I've looked through Context, Entity Reference (which I didn't really get) and Views Relationships and Contexts but couldn't make much sense of it.

What's the best way to accomplish this?

Edit:

I've added an image of my desired output (from actual site) and the current fields of content type's A and B.

An important note is that the Views block/whatever showing content type B needs to be shown in the normal node page of content type A.

I know this isn't the best way to do this, but this feature wasn't planned and the client just wants it to work as fast as possible

Content Types Fields:

I've excluded irrelevant fields such as path and meta tags.

Content type A:

Title - text
Body - HTML (w/ text inside)
Department - List

Content type B:

Title (name) - text
Description - text
Department - List

Desired Output:

Create a View to show nodes of Content Type B, add a Contextual Filter for your field My List and save the view.

Install the Views Field View module and then in the Footer region of your View of Content Type A add the  Global: View (Views field view) and configure under the View settings the Name and Display of your B View and the token for the Contextual filters.

To use the value of the My List field as a token, you must have in the Fields of your view this field selected.

Edit after your comment ("I'd prefer to keep using the regular node page.")

You can use the EVA module, it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity, in your case the node of Type A. In the contextual filter of the view you need select the My List field in the Entity Content Settings of the View using a token.

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.


How to have no more than 20 Entity references to another content type? I have a content type with a entity reference to another content type/view. The current possible relations could be 1,2,3 .... until 10 or unlimited. These are given in the field attributes screens.

I need 20. After that the user is not allowed to add another field in the gui.

Any solutions how to do this?

You should select unlimited as possible relations. Then, using a custom module, you can alter the node edit form to don't allow more than 20 items.

To do this, implement hook form alter:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  // do magic.
}

Inside you have to:

Check the if the relations field has 20 item; if yes
delete the element widget that adds another one (so user don't get confused because it seems more items can be added).
Add a new validate handler to check related items are less than
21.


Access denied error after login When i log in to drupal doesn't matter with any account either admin or normal user. I get error Access Denied. I then again try to login and it works fine. What is that problem?
My theme was shipped with its own drupal so i guess they might have done some thing wrong.

I feel some session issue because my error messages on drupal valiation forms also occurs one page delayed. So if a submit a invalid form the page post back and hight light the fields with red color but don't show any message. When i go to any other page the error message dive comes up. This happens on both front end and admin panel forms.

Update: I forgot to mention that i am using a custom template for user login page.

Here is the code for my user login template. I am not sure if this is causing issue or something else.

<?php
     // we aren't getting messages, get them manually
            if (isset($_SESSION['messages'])) {
                echo '
';
                foreach($_SESSION['messages'] as $type=>$messages) {
                    echo "
".implode("

", $messages)."
";
                }
                echo '
';
                unset($_SESSION['messages']);
            }
?>

Login

  <?php print drupal_render_children($form) ?>

Updatd Part: I found the culprit i.e my own module

Actually i got the problem. But coudln't find the work around. I have a custom module that redirects user to paypal when he is creating account on my site. I put the $form and $form_state values in session and when the user return back from paypal i pass both variables to user_register_submit function to resume the process of creating account. For this purpose i have to put @session_start() at the start of my module file. This works fine in case of my paypal process. But because of sesion_start() my login flow is disturbed. What can i do to resolve this issue as i need session to hold form and form state

What worked for me was enabling and configuring the $cookie_domain variable in settings.php (because I have a site that can be accessed by 2 different domains).

Pay attention to the comment before this variable! The domain name must start with a period. EX:

$cookie_domain = '.example.com';

Good luck!


Prevent Drupal from Caching API Responses I am not sure this is even supposed to happen, but it looks like Drupal is caching REST API responses. I have created a module that makes certain data available through the REST API, and changing the value in the DB requires clearing the cache for it to be reflected immediately in the API response.

Is there a way to prevent Drupal from doing this? The idea behind my API responses is that they are supposed to return real-time data. Currently I'm talking about the user.data service (users_data table), but an answer for any arbitrary data would be appreciated.

A specific random example of what retrieving the data looks like:

$user_data = \Drupal::service('user.data')->get('my_module', $id);

It looks like the cache I want to avoid is stored in cache_dynamic_page_cache.

EDIT: The simplest API response in this case (in the get() method) is:

return new ResourceResponse($user_data);

I think you need to define #cache settings in your controller's response. You could define it in such a way that your response isn't cached at all, but you're probably better off defining cache tags in such a way that the cache is cleared when the entity is updated. See the Cache API documentation for more info.

Based on the information you've given, I think you'll probably want something like below added to your response array.

'#cache' => [
  'keys' => [
    'MY_MODULE_WHATEVER_KEY_YOU_LIKE',
  ],
  'tags' => [
    'user:' . $id,
  ],
  'max-age' => Cache::PERMANENT,
],

You'll need this use statement at the top of your file for Cache::PERMANENT

use Drupal\Cache\Cache\Cache.php;

The above will cache your response permanently, but break the cache when the user with $id is updated.


How can I translate the checkout system? I have been translating my Commerce Kickstart site with no ease although with success until now. Have translated content, taxonomy, product fields etc, following some tutorials and Drupal own documentation. Have installed a variety of modules for localization.

But now as regarding checkout system. I'm calling checkout system all screens starting by clicking on "checkout" in shopping cart block that appear in above and right corner of Kickstart demo store.

To translate checkout system, I went in https://localize.drupal.org/translate/downloads?project=commerce and downloaded my translation (Portuguese, Brazil). Then I imported that with /admin/config/regional/translate/import. In Overview tab all the 1222 expressions (100%) are translated. In Translate tab I searched for some strings that appear in that checkout system screens, like "Payment", "Checkout complete", and indeed there are already translations in Portuguese Brazil.

In /admin/config/regional/language/configure, on Detection and selection tab I enabled URL and Session as Detection methods.

So, are there more configurations that I need to do to have checkout system translated?

In importing translation page /admin/config/regional/translate/import I have chosen "Drupal commerce"in Text group section. The process went fine, but the words to translate were indeed in Bult-in interface. So I imported the same file again but now choosing "Bult-in interface" in Text group section. Now I have checkout system translated at some degree.

I think perhaps because I installed Commerce Kickstart 2 and Drupal Commerce comes all in Built-in interface.


How to get the values of an array in the options list (hook_rules_condition_info ()) instead of array index? 'example_condition_user' => array(
      'label' => t('User Condition'),
      'arguments' => array(
      ),
      'parameter' => array(
        'username' => array(
          'type'  => 'text',
          'options list' => 'list_all_users',
          'label' => t('Username'),
          'description' => t('user that the conditions apply'),
         ),
        'user_entry' => array(
          'type'  => 'user',
          'label' => t('user'),
        )
      ),
      'group' => t('exemplo'),
      'module' => 'exemplo',
)

function list_all_users(){

  $query = db_select('users', 'u');
  $query->fields('u', array('name'));

  $result = $query->execute()->fetchAll();
  $ret = array();

  foreach($result as $r){
    array_push($ret, $r->name);
  }

  return array_values($ret);

}

The list_all_users function returns the users (that are in my database) in a array, but the options list does not get the values of the array, but the array index, and this is a problem, because I need the values of the index, and then do the validations rule_condition_info (), does anyone have any idea how to fix this?

You just need a reliable array key so you can load the data up again somewhere else; since you're going into the users table, uid seems appropriate:

function list_all_users() {
  return db_query('SELECT uid, name FROM {users}')->fetchAllKeyed();
}

That will turn the options into an array with user IDs as keys and names as values. As far as the front end is concerned, nothing changes.

Now when you receive the selected option value in the validation function, you can just load the user up and get the name from the entity:

$account = user_load($the_value);
$name = $account->name;


How to reset form values when Ajax submits? I develop a module which converts submit in the form to Ajax submit (e.g. node/add/article). After every submit, the node is successfully created, but all the values remain saved.

In the Ajax callback, I added a return $form to reload the form after submission, but all fields are empty, not filled with old values.

What shall I do?

You can try the code below

$response->addCommand(new InvokeCommand('#form-id','trigger',['reset']));

  The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

This command is implemented by Drupal.AjaxCommands.prototype.invoke() defined in misc/ajax.js

Please see InvokeCommand


Commerce / Rules - commerce-order:mail is empty for anonymous users I'm having trouble sending order notification emails to anonymous users. As a bare-bones test I have created a new rule which triggers on 'Completing the checkout process', checks if the current user is authenticated, and if not sends an email to [commerce-order:mail]. When it's triggered I get the following error message, suggesting it is not able to get the email address from the order.

Error sending e-mail (from admin@ourwebsite.com to ).

I'm fairly sure the problem isn't to do with Rules config as it's so simple, but here is the export anyway:

{ "rules_anonymous_order_notification" : {
"LABEL" : "Anonymous Order Notification",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "NOT user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "2" : "2" } }
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : [ "commerce-order:mail" ],
      "subject" : "Order received!",
      "message" : "This is to tell you the order has been received.",
      "language" : [ "commerce-order:state" ]
    }
  }
]

}
}

What else could be causing this?

EDIT: I've just noticed in the db the mail column is empty for anonymous orders in 'commerce_order' - is this normal?

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

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

Rules debugging

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

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

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


How does Drush figure out modules that have updates? How does Drush get information about installed and disabled modules and  updates for them?

I'm facing issues since drush is trying to update modules that AREN'T in the modules directory nor in the system table anymore.

I had to remove them since they were causing problems.
But in the end I got nothing but more problems.

How could I get drush to understand these do not exist anymore and do not need to be a)checked and b)especially not updated.

I've tried drush rr to "make it clear" but it keeps trying these causing errors that crash all other updates etc.

Update:

These the modules.
Simplenews [simplenews-7.x-1.1],
Simplenews Bounced Mail Handler [Simplenews_BMH-7.x-2.x-dev],
Simplenews Statistics [simplenews_statistics-7.x-1.0-alpha1]

I can confirm that I can remove the simplenews rows from system table but they come back as soon as I run:              drush rr OR drush pm-list --pipe --type=module --status=disabled--no-core

Use pm-uninstall to completely remove a module from your system.

If you have already deleted the code for the modules in question, the safest and best thing to do is put the code back and run pm-uninstall.  If you just want to get rid of the reference to the module in the system table, you could take matters into your own hands, and just do this:

drush sqlq "delete from system where name in ('moduleone', 'moduletwo');"

If you do that, though, then the module won't have a chance to remove any other unneeded assets that would be deleted if you used pm-uninstall.


How to disable browser autocomplete for the login form I would like to remove auto fill user name and password while login or forgot password.

I have tried this but its not working:

if ($form_id == 'user-login-form') {
  $form['name']['#attributes']['autocomplete'] = 'off';
}

What am I doing wrong?

You can try:

$form['account']['name']['#attributes']['autocomplete'] = 'off';


Any kind of sorting gives duplicate results in Views (Search API) Problem

My view based on Search API is giving me duplicate results. I get duplicate results if I use the following things in combination:

A pager
A sort of any kind. e.g. Sort by ascending integers, sort by descending select field etc.

Sometimes I get a couple duplicate results, other times entire pages are identical.

According to the module page I should be able to use view sorts on single valued indexed fields, but I can't seem to get this to work at all.

Has anyone else run into this? How did you solve it?

Common solutions for duplicate results

Most of the solutions I've spotted for this involve options which don't appear for Search API. They usually involve adding aggregation or distinct filters in the Views options.

The possible solution here fails. The problem is it searches for duplicate results only amongst the current page of the view.

i.e. if I get 60 nodes on a search with a pager of 15, this splits into 4 pages. If the duplicates are on pages 1 & 3 then they're not spotted.

Bleh what a horrible bug.

I solved it by re-creating the search index (and therefore the view as well).

Why did it happen?

I think it's possible to have certain things saved into the Search Index (possibly when it's created?) and then it's impossible to remove them without just starting afresh.

I discovered this bug while trying to debug this.

After re-creating the new index the only difference I can find between it and the original is that I can now sort by an un-related taxonomy field (see the bug). Presumably this is an indicator of something as it doesn't seem relevant, but I have no idea what.

Second EDIT:

Actually just re-creating the index wasn't enough to solve this problem, I then continued to find duplicates after.

Deleting and re-creating the field with a new ID however did work. I never worked out why, but I'm presuming something was corrupted.


How do I add a span "wrapper" to all required form fields? In the current Drupal configuration required fields simply display an asterisk wrapped in span of class "form-required":

return '*

This isn't really suitable and I have noticed quite a few users miss the asterisk (poor visibility, etc.). To combat this I would like to apply much better styling / hinting to all elements of a required field (label, value, background, etc.).

How do I add a span wrapper to al required fields on the form?

  Label

  ....

I presume I need to use hook_form_alter() but not sure what I need to check or how to output the original field data correctly/safely.

I'd suggest you create an implementation of the theme hook form_element, to add a new class at the top level rather than an extra div which is simply redundant. That way you don't have to recursively process every form on the site looking for required fields. Unfortunately the standard form_element implementation is not designed in a very helpful way, so you have to duplicate a lot of code:

  function mymoduleortheme_form_element($variables) {
    $element = &$variables['element'];
    // This is also used in the installer, pre-database setup.
    $t = get_t();

    // This function is invoked as theme wrapper, but the rendered form element
    // may not necessarily have been processed by form_builder().
    $element += array(
      '#title_display' => 'before',
    );

    // Add element #id for #type 'item'.
    if (isset($element['#markup']) && !empty($element['#id'])) {
      $attributes['id'] = $element['#id'];
    }
    // Add element's #type and #name as class to aid with JS/CSS selectors.
    $attributes['class'] = array('form-item');
    // extra code here --->
    if(!empty($element['#required'])) {
      $attributes['class'][] = 'form-element-required';
    }
    // <---
    if (!empty($element['#type'])) {
      $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
    }
    if (!empty($element['#name'])) {
      $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
    }
    // Add a class for disabled elements to facilitate cross-browser styling.
    if (!empty($element['#attributes']['disabled'])) {
      $attributes['class'][] = 'form-disabled';
    }
    $output = '
' . "\n";

    // If #title is not set, we don't display any label or required marker.
    if (!isset($element['#title'])) {
      $element['#title_display'] = 'none';
    }
    $prefix = isset($element['#field_prefix']) ? '' . $element['#field_prefix'] . ' ' : '';
    $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';

    switch ($element['#title_display']) {
      case 'before':
      case 'invisible':
        $output .= ' ' . theme('form_element_label', $variables);
        $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
        break;

      case 'after':
        $output .= ' ' . $prefix . $element['#children'] . $suffix;
        $output .= ' ' . theme('form_element_label', $variables) . "\n";
        break;

      case 'none':
      case 'attribute':
        // Output no label and no required marker, only the children.
        $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
        break;
    }

    if (!empty($element['#description'])) {
      $output .= '
' . $element['#description'] . "
\n";
    }

    $output .= "
\n";

    return $output;
  }


Create a field collection field programmatically Is there a way to create a field collection programmatically? I saw this code:

$field_collection_item = entity_create('field_collection_item', array('field_name' =>'field_text')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // This is required, there shuold be a host entity, this case I used a node.
$field_collection_item->field_text[LANGUAGE_NONE][0]['value'] = 'Test Value';
$field_collection_item->save(); // Save the field collection item.

But when I run this code I get this error:

  Exception: Invalid field name given: field_text is not a Field
  Collection field.

I can't find a proper solution for this.

Have you tried using entity metadata wrappers? They come with the Entity API module and allow you to do this (copied from linked documentation):

<?php
    // Populate the fields.
    $ewrapper = entity_metadata_wrapper('node', $node);
    $ewrapper->field_lead_contact_name->set($contact_name);
    $ewrapper->field_lead_contact_phone->set($contact_phone);
    $ewrapper->field_lead_contact_email->set($contact_email);

    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();

    // Save.
    $ewrapper->save();
?>

In this example a node and the attached fieldset are created at the same time, so it might just work with only below code. Perhaps it is required to save the node afterwards, I have not tested it.

<?php
    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();
?>

Update:

At the bottom of the Entity Metadata Wrapper documentation (before the comments) there are some lines about debugging and finding available parameters. That also might be of help while attempting to find the right property.


How do I get a field count from an executed query? I'm sure this exists, but after a few dozen searches, I'm not any closer to an answer.

After I've executed a query in Drupal (for example)

$dbParts = db_select("parts", "p")
    ->fields("p")
    ->execute();

How can I get a count (or list) of fields without pulling this first record? With MySQL I was able to use "mysql_num_fields".

UPDATE

Just to give a little background... I have some old code (using mysql_* functions) that export data to the DBF format. In order to format the header of the DBF, I need to have a field count (and information about the fields) even if the record count is 0 in order to format a "blank" database.

Drupal uses PDO, whose equivalent function is PDOStatement::columnCount():

  Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

So what you're looking for isn't totally possible these days. I can't see a Drupal equivalent of columnCount(), but you can always grab the PDO connection object with Database::getConnection(), and work with that directly if it'll help you get part of the way there.

To take a different approach, and assuming you've used the schema API to describe your table to Drupal, you can query that instead:

$table = drupal_get_schema_unprocessed('MYMODULE', 'table_name');
$fields = $table['fields'];


Unauthorised users to view homepage without menu I have installed the Front Page module on my site.
I want to show visitors (not-logged in users) to see the same homepage as logged in users but without the navigational bar.

I have used re-direct to the "/home" in the front page settings and removed menu permission in the anonymous users roles section but I am getting an access denied message.

Create a new template for your front page name it page--front.tpl.php

Create a variable which assign a role to a temporary variable in your template_preprocess_page(&$vars) like

function THEMENAME_preprocess_page(&$vars) {
  global $user
  if(drupal_is_front_page()) {
   if(in_array('anonymous', $user->roles)) {
      $vars['navigation'] = false;
    }
  }
}

then in you page--front.tpl.php just check if($vavigation) ..


Custom Views filter for multi-level taxonomy I'm struggling to set up two kinds of views for displaying multi-level taxonomy. One would list terms that are final nodes, and the other would list nodes that have children. Somehow, I can't.

I stated that what I really need is a filter criterion "Content: Has taxonomy terms (with depth=1) which have children". Does anyone know of a module/add-in that would add such a filter criterion, or perhaps knows how to define a native Views equiv (I'm still too fresh to say if that is possible).

Thanks
Artur

in Relationships you add:
 Taxonomy: Parent item

then in Filters add:
 Taxonomy: Term ID, set Relationship to the above Parent, and the Operator: Is empty(NULL)

This way you only get the top level terms, because they don't have parents. Or you set it to Not empty(NOT NULL) to get the child terms.

I hope this method helps you in some way.


Should I use Entity Views Attach module to solve my problem I've check the question in this node: https://drupal.stackexchange.com/questions/5732/is-there-a-good-tutorial-for-entity-views-attach-module

And I see that maybe what is answered there is a partial solution to the issue I'm facing. To avoid writing I will paste the issues addresses I've been creating on my help search:

https://drupal.org/node/1928064
https://drupal.org/node/1929030
https://drupal.org/node/332001

Basically it's to send an argument from a view to another view, both displayed at the same time in the same page (one in block, the other in content). A further complication is that those views are contained in panels.

On the "block view", there is a list of let's say names (extracted from a content type) exposed as links which point to the "content view". This takes the argument (text of the link) from the clicked link of the "block view" as a filter to display some others fields from the same content type.

I suspect you might get a better answer if you were to say more about what you are trying to achieve than how you are doing so.

For example, reading between the lines of your question I wonder if you are working on some sort of faceted search? In which case I'd recommend you look at Search API. And this may be of interest: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels


How to store/manage/display data sets in Drupal without using the node/entity systems? I need to store some straight forward data rows (similar to the JSON objects that can be stored in MongoDB), where all the data associated with one object is found on the same row and not scattered over several database tables.

What is the best approach to do this in Drupal?

Notes:

I am considering storing them on database (MySQL/Postgres or MongoDB). I have no data yet (I am at the project planning stage).
I'll be using some API code (server side - does not need to have anything to do with Drupal) and I will be creating/updating the data via JSON post requests from a c# application. I need Drupal only to display the data.

Have a look at the Forena module which can be used to display (= query, not update) data stored in databases external to Drupal. It comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgres or any PDO compliant variation.

For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the Forena Documentation.

The Sample reports and graphs are fully functional, such as the drill downs available on the Master Summary with drill down. To filter data (by the users), you'd typically use "report parameters", which you can see in the sample report "Users in cities". On top of that, using Forena "skins", you can also use the amazing "dataTables" (and its widgets, such as sorting by selected columns).

It also includes a UI for either creating your reports (the WYSIWYG Report Editor) and/or for creating your SQL queries (the WYSIWYG Query Builder).

Disclosure: I'm a co-maintainer of Forena.


Creating folders for images using Tokens module I have a node for a photo. I want to know what is the best why to define the file path for the images. The images will be user submitted.

Ideally, I would have liked the path be sites/default/files/photo/[node-reference:NID] so that each node would have all the image nodes associated with it in their own folder. This would make it easier to migrate the images since not only in the database but also in the file system would describe which images belong to which. Because the referenced node isn't available for the Tokens module I need to come up with a different strategy.

I have considered things like user sites/default/files/photo to dump all the images into one folder which might become a mess over time or sites/default/files/photo/[user id] so that each user's images are in separate containers. I don't know what the benefit of that would be.

I'm also thinking about creating a name convention for each image to that it has the node reference NID and user name in code. Is it worth the effort?

I'm looking at the image scr attributes on websites like grammy.com and examiner.com to see how they set it up. It looks like the examiner.com uses a hash to name the image.

Does anybody have any ideas on how to do this?

Since Token does not yet have support for field tokens, I would choose a temporary convention that makes sense to you. Once that feature is added, you can use FieldField Paths to reorganize your files.


How to move a drupal 6 installation to a new server? I backed up my files and database. uploaded files to new server, created and restored the database to the new server, edited the settings.php file. I navigate to the site, it pops up perfectly. I try to navigate to any other page and I get a 404 page not found error. What am I missing?

Do you have mod_rewrite for Apache enabled/installed?  If not, verify this is the case.

Also, ensure that your .htaccess file in your Drupal root is unchanged from the old server.

If you're on a Debian-based distribution, go to /etc/apache2/mods-available to verify that rewrite.load is present.  Then go to /etc/apache2/mods-enabled to verify that rewrite.load is symlinked in that directory.

If you're on a RedHat distro like CentOS, then go to /etc/httpd/modules and look for mod_rewrite.so.  Then, open up /etc/httpd/conf/httpd.conf and verify that this line is in there LoadModule rewrite_module modules/mod_rewrite.so.


How to fix my String Translation error in my selection list value? I am using the String Translation module (part of i18n) and I have added new string in Italian language.

Example:
Data d'inizio

Output:

So instead of translated text Data d'inizio its shows me the drop-down text.

How to fix this issue?

This can be fixed via a hook_form_alter, in which you loop through all select list options and run the option text through decode_entities().

Refer to HTML Encoding in Drupal Entity References for more details, which also includes this code sample:

function misc_form_alter(&$form, &$form_state, $form_id) {
 $to_fix = array('field_reference');
 foreach($to_fix as $fix) {
   if (isset($form[$fix]) && isset($form[$fix][$form[$fix]['#language']]['#options'])) {
     foreach($form[$fix][$form[$fix]['#language']]['#options'] as &$text) {
       $text = decode_entities($text);
     }
   }
 }

}


t() function doesn't render HTML It is the t() function and the way I assigned value to a body field

$my_body_content = t('!frequency new comment(s) sent to !title', array('!frequency ' => $frequency , '!url ' => $url , '!title ' => $title));
$ewrapper->field_body->set(array(
        'value' => $my_body_content
) );

the $frequency, $title and $url are already set. This is the configuration of the body field (it allows a tag)

But it is what I get

Why it doesn't render the HTML ?

UPDATE :

I edited the body by UI like this

and it worked! sounds the problem is because of the PHP code

This code should work for you

$link = l($title, $url);
$my_body_content = t('!frequency new comment(s) sent to !link', array('!frequency ' => $frequency , '!link' => $link));
$ewrapper->field_body->set(array(
    'value' => $my_body_content
) );


Alphabetically filtering a view I have a view that I need to filter alphabetically. How is this done? I need to also add a list item for each letter of the alphabet, with an ID of that letter for a quick anchor scroll-to script. Can anyone help me getting this done?

This video is from Nodeone.se addresses sorting, but the entire series on Views is an excellent tutorial.


Theming user_profile_form (the user edit form) I am looking for easy ways to theme the user profile form that will allow me to setup a two-column layout for the form and exclude certain elements.

How can I achieve it?

Aside from using the Display Suite module, most methods for theming forms require a bit of code to be written. In the following method I define variables from the form that can be outputted in a template file to fit whatever HTML structure you'd like. I put all of my code in template.php, but you can just as easily make a custom module to do this.

Add a hook_theme() implementation

function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
Next we'll define some variables to pass into that template in a hook_preprocess_HOOK function. We can find the structured array of the form in $variables['form'] and assign the form elements to the variables we'd like to throw around our tpl.php file.

function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $form_inputs = array(
    'account' => $variables['form']['account'],
    'picture' => $variables['form']['picture'],
    'actions' => $variables['form']['actions'],
  );
  $variables['rendered'] = _YOURTHEME_form_variables_render_all($form_inputs);
}

function _YOURTHEME_form_variables_render_all($elements) {
    //Create array to return, with element name as key and element as value
    $elements_array = array();
    //For each element, render it and add it to the array
    foreach ($elements as $key => $element) {
        $elements_array[$key] = render($element);
    }
    //Return array
    return $elements_array;
}

This example will put the general account info fields, the user picture upload field (if pictures are enabled), and the submit actions into a variable called "rendered."
Now that we have defined these variables, we can output them in a template file. Create a template file named user-profile-form.tpl.php in 'YOURTHEME/templates'. This is a demo example:

<div id="new-form">
  <?php echo $rendered['picture']; ?>
  <?php echo $rendered['account']; ?>
  <?php echo $rendered['actions']; ?>
  <input type="hidden" name="form_id" value="<?php print $form['#form_id']; ?>" />
  <input type="hidden" name="form_build_id" value="<?php print $form['#build_id']; ?>" />
  <input type="hidden" name="form_token" value="<?php print $form['form_token']['#default_value']; ?>" />
</div>

Notice the hidden form fields at the end; these include vital Drupal tokens that help secure forms from attack. Your form won't work without them.

When you visit your user edit page, you should now see only some general account info fields and the picture fields. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the user-profile-form.tpl.php file, adding whatever markup you like.


How do I redirect users to the page they were before logging in to my site? I´ve got a Drupal site that after the user logs in it is redirected to his profile.
I want to create a specific rule so people from specific characteristics can retur to the page they were before they´ve logged in.

I´m planning to do that with the rules module.

So, I´ve set the parameters and conditions, but when I try to create the rule, telling Drupal where it should redirect people, I just don´t know how to say that.

I think I should put some php code inside that page redirect rule, but don´t know how.
Hopw you can help me out.

FYI, I've tried (unsuccessfully) this:

$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header("Location: http://www.mysite.net/user");
exit();

// On successful login
$redirect = $_SESSION['redirect_to'];
// unset the session var
unset($_SESSION['redirect_to']);
header("Location: http://www.mysite.net/$redirect");
exit();

Have a look at the Login Destination module.

In custom code, to issue a redirect in Drupal use the drupal_goto() function. Drupal has a massive API, use it.


How do I filter exposed taxonomy terms with other exposed taxonomy terms? OK, so I have 3 different Taxonomy Vocabularies filled like this: One for Carriers [AT&T, T-Mobile] One for Manufacturers [Samsung, iPhone, etc] And one for the Models [Galaxy S3, S4, etc]

All of these are set as an Exposed Filter for a custom view, But what I want is for the last Exposed Filter, "Models" to be Filtered by whatever Selection is made in "Manufacturers"

So if I Select iPhone, I only see Models for iPhones.

I've searched everywhere without the solution I need. And if it is what I needed, I wasn't able to set it up, or directions weren't clear enough.

I have Term References Linked from the Models to the Manufacturers, but idk how to Filter the Exposed Filter to only show Model choices for the selected manufacturer.

How do I filter exposed taxonomy terms with other exposed taxonomy terms?
Any help is appreciated!

I'm Working with Drupal 7.

Use the Search API.  Totally awesome.  It will provide you with the Facets you need.  Don't be intimidated.  The instructions below are great.

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/


Search all content fields with "find content" module instead of title I want to search all fields instead of the title only.

Right now I'm using the "find content" module. Tried to find another one which is similar but am not able to find.

Your best option is to use the Administration views module and edit the view to suit your needs. Edit the view with an exposed search filter.

Replaces administrative overview/listing pages with actual views for superior usability.

Features

  Filter all administrative views via AJAX. Perform any kind of
  bulk/mass operations on items in administrative views. Filter content
  by title, node type, author, published status, and/or vocabulary.
  Filter comments by title, author, node title, or published status.
  Filter users by name, ban/blocked status, or user roles.
  *Note: If you are upgrading from an older version of Administration views and the default views have been overridden (saved in the
  database) you could encounter issues or not see any new changes unless
  you revert these views, so the default in-code views are used. This
  can be done in the views UI listing or using drush (drush cter
  views_view --module=admin_views)


Change the order of product variations on the "add to cart" form I have a product type with three variations (to make this simple, let's assume it's a t-shirt store):

Color
Size
Team

On the "Add to Cart" form (configured at /admin/commerce/config/order-item-types/default/edit/form-display/add_to_cart), I have Purchased entity set to Product variation attributes.

This displays three dropdown menus that let me select the values for Color, Size, and Team.

How do I change the display order of these menus (for example: change the order to Team, Color, Size)?

Drupal 8/Commerce 2

Similar to Drupal 7, Drupal Commerce for Drupal 8 respects the ordering of attribute fields on the product variation form when rendering them into the Add to Cart form. To find these options, you'll need to navigate to Administration >  Commerce > Configuration > Product variation types and select the Manage form display option from the Operations dropdown for the variation type in question. Reorder the fields there, and they'll appear in the new order on the Add to Cart form.


Refreshing AJAX Forms in Drupal 7 My dynamic Competition form has two basic parts:

1- Basic Info

Name
Size Dropdown

2- Ajax Fields

Options dropdown based on Size

When I change the value in Size, a new combobox is loaded via AJAX with related values.

Here is part of my form:

if ($competition->size == 0)
    {
        $form['country'] = array(
            '#type' => 'select',
            '#title' => t('Country'),
            '#weight' =>3,
            '#required' => FALSE,
            '#zurb_class'=> 'cleared',
            '#default_value' => $competition->country_id,
            '#options' => _ajax_countries_dropdown_options(),
            '#prefix' => '
',
            '#suffix' => '
',
        );
    }
    else if ($competition->size == 1)
    {
        $form['continent'] = array(
            '#type' => 'select',
            '#title' => t('Continent'),
            '#default_value' => $competition->continent_id,
            '#weight' =>2,
            '#required' => FALSE,
            '#options' => _ajax_continents_dropdown_options(),
            '#prefix' => '
',
            '#suffix' => '
',

        );
    }
    else
    {
        $suffix = '

';
    }

    $form['size'] = array(
        '#type' => 'select',
        '#title' => t('Size'),
        '#default_value' => $competition->size,
        '#weight' =>1,
        '#options' => $options_size,
        '#required' => FALSE,
        '#ajax' => array(
            'callback' => 'ajax_competition_size_dropdown_callback',
            'wrapper' => 'dropdown-competition-size-replace',
            'method' => 'replace',
            'effect' => 'fade',
        ),
        '#suffix' => $suffix,
    );

Ajax Callback

function ajax_competition_size_dropdown_callback($form, $form_state) {
    $size = $form_state['values']['size'];

    if ($size == 0)
    {
        return array(
            '#name' => 'country',
            '#type' => 'select',
            '#title' => t('Country'),
            '#weight' =>3,
            '#required' => FALSE,
            '#zurb_class'=> 'cleared',
            '#default_value' => $competition->country_id,
            '#options' => _ajax_countries_dropdown_options(),
            '#prefix' => '
',
            '#suffix' => '
',
        );
    }
    else if ($size == 1)
    {
        return array(
            '#name' => 'continent',
            '#type' => 'select',
            '#title' => t('Continent'),
            '#default_value' => $competition->continent_id,
            '#weight' =>2,
            '#required' => FALSE,
            '#options' => _ajax_continents_dropdown_options(),
            '#prefix' => '
',
            '#suffix' => '
',
        );
    }
    else
    {
        return '

';
    }
}

Steps I made so far:

When I change the first select when editing, the values are not saved.
Debugging Backend
The form changes on the front (AJAX), but it does not change on the backend
Apparently the problem is I am creating the form fields based on size, Drupal will only recognize this fields. So when I change the select and load the second, it won't parsed by Drupal
I tried to use $form_state['rebuild'] = TRUE; but it didn't fix anything, actually avoided the redirection after submission.

The Ajax callback should only return the named FAPI element that is to be replaced. For example:

function questionaire_4D_selector_form_ajax_callback($form, $form_state) {
  // If the form has errors we show them in the Preview spot. There's not much
  // else we can do because jQuery is replacing out the specified
  // target element in the #ajax FAPI element.
  if (form_get_errors()) {
    return $form['preview-content-area']['esci-questionaire'];
  }
  return $form['preview-content-area']['esci-questionaire'];
}

Your form_builder function which build/rebuilds the form should examine the $form_state and alter the form as necessary based on the ajax submitted values:

/** Our form builder function */
function questionaire_4d_selector_form($form, &$form_state) {
 # for ajax inspection goto /tmp and view file output.
 #dd($form_state);
 #dpm($form_state);

  // This form responds to an AJAX submit button, and also a $_GET argument.
  $form_passed_get_parameter_questionaire_id = $form_state['submitted'] == FALSE &&
          count($form_state['build_info']['args']) &&
          ctype_digit($form_state['build_info']['args'][0]);
  #dpm($form_passed_get_parameter_questionaire_id ? 1 : 0);
  if ($form_passed_get_parameter_questionaire_id) {
    $id = $form_state['build_info']['args'][0];
  } else {
    $id = !empty($form_state['values']['questionaire_id']) ? $form_state['values']['questionaire_id'] : '';
  }
  #dpm($id);
  $form['questionaire_selector'] = array(
    '#type' => 'fieldset',
    '#title' => t('Select 4D Questionaire'),
  );
  $form['questionaire_selector']['access_id'] = array(
    '#type' => 'hidden',
    '#value' => drupal_get_token(QUESTIONAIRE_4D_PREVIEW_AJAX_SECRET_VALUE),
  );
  $form['questionaire_selector']['questionaire_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Questionaire Number'),
    '#default_value' => $id,
    '#element_validate' => array('element_validate_integer_positive'),
    '#size' => 15,
  );
  $form['questionaire_selector']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Preview 4D Questionaire'),
    '#ajax' => array(
      'callback' => 'questionaire_4d_selector_form_ajax_callback',
      'wrapper' => 'questionaire-preview',
      'method' => 'replace',
    ),
  );
  $form['preview-content-area'] = array(
    '#type' => 'fieldset',
  );
  $form['preview-content-area']['esci-questionaire'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'markup',
    '#markup' => '
Your Questionaire Preview will appear here.
',
  );

  // This says if we were given an remote 4D form id of say 23456, load it into the supplied FAPI
  // element.
  if ($form_passed_get_parameter_questionaire_id) {
    $remote_response = retrieve_questionaire_4d_response($id);
    if (strpos($remote_response->data, 'Error',0) === 0) {
      form_set_error('questionaire_selector', "Remote 4D Error
" . $remote_response->data);
    }
    $form['preview-content-area']['esci-questionaire']['#markup'] = questionaire_4d_selector_build_esci_questionaire_preview($id, $remote_response->data);
  }

  $form['#attached']['css'] = array(
    drupal_get_path('module', 'questionaire_4d_preview') . '/assets/questionaire_4d_preview.css',
  );
  return $form;
}

/* Implements hook_menu() */
function questionaire_4d_preview_menu() {
  $items['admin/config/esci-online/questionaire-4d-preview'] = array(
    'title' => '4D Questionaire Preview',
    'description' => 'View a preview of a remote 4D questionare.',
    'page callback' => 'drupal_get_form',
    // I'm not sure we have to, but explicitly pass in the 4th
    // argument on the URL as the questionairre ID. This is added
    // to build_info of form automatically.
    'page arguments' => array('questionaire_4d_selector_form', 4),
    'type' => MENU_CALLBACK,
    'access arguments' => array('administer esci'),
  );
  return $items;
}


Can Drupal Commerce and Ubercart be installed on the same site? Can Drupal Commerce and Ubercart be installed on the same site or will they conflict with eachother?

These two modules define the same menu entries - so you can use only one of them.


how to add form action twig template form I have created a module in which I create a form and then rendered it in twig template I  want to know how to give form action in a twig template i.e  how to pass form action attribute in twig form.

any help will be greatly appreciated .

mymodulename-form.html.twig file

<form>

   {{form.first_name['#title']}}

        {{form.first_name}}

I am assuming you are building this form with Form API and not plain HTML (don't do that). You need to add the attributes to ensure you get everything you need.

<form{{ attributes }}>

See the main form.html.twig template: https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21form.html.twig/8.4.x

In general, I advise you to theme the form elements themselves instead of stitch the form together like this, because you will likely be missing the things in the form Drupal adds behind the scenes to a rendered form.


How to move a field to a different region using Omega sub-theme / D7? I used to be pretty good at theming Drupal sites, but I haven't done it much since D7. I added a custom field to my Basic content type and I want to put it in a Sidebar if it exists. What's the best way to accomplish that?

Thank you IRC! At least two modules will help with this (quotes included are from their project pages):

CCK Blocks:

  Since version 6.x-1.1 , the module does not hide the field in the node's content area anymore. You can do that for yourself in the display settings for your content type.

  CCK blocks will define a display mode named "CCK Blocks", which you can use to configure the display of fields when they are appearing as blocks.

  This allows you show the field both in the node's content area and in the CCK block, with different display settings.

Display Suite:

  ... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

  By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.


How can I stop Drupal from sending e-mails of any kind? I have a dev, staging, and live server workflow set up on Pantheon.  My site has a lot of rules that cause members to be e-mailed for various reasons.  I sometimes need to work on these on my dev/staging sites but I've realized that, since they have the live data, sometimes users will receive additional or duplicate e-mails when I'm working on something.

Is there any easy way to turn off all e-mailing capability (preferably automatically to prevent me from forgetting) on a dev/staging server?  Ideally, I'd like to disable e-mail via a custom module, since I already have steps in place for making sure a custom module is enabled on dev/staging.

As another, quicker, option, you can add the following lines to your site's settings.php file (if you have the Devel module installed, which you certainly should if this is a dev site).

$conf['mail_system'] = array(
  'default-system' => 'DevelMailLog',
);

That will replace the default mail system with Devel's development mail system, which writes emails to a file log rather than sending them to a recipient. By default the files are stored in temporary://devel-mails, but you can alter that by setting another variable, eg.

$conf['devel_debug_mail_directory'] = '/path/to/folder';


Video Migration from MySQL I have a video link and the video is there in my FTP. I need to migrate videos from mysql to DRUPAL database. Video complete path is stored in mysql database at present. In this process I  dont want to transfer videos from this FTP, instead I want to link somehow to the video-upload field of my content type. Is this achievable ? Is there a module to do this? I have used feeds module for migration but int that I can not migrate videos.

Content type: Sports
Fields: Sports Type(Text) and Sports Video(Video upload)

I have a video link in my existing database. I want to migrate or somehow link the video to the Sports Video field.

If you want to keep the video stored somewhere else and you don't need to consider the video as a managed Drupal file, then you could just migrate the 'video url' to a text field or a custom field type.

Depending on how you would like to output the video to your visitors you could create your own field formatter. And use the stored 'video url' as a source for your video player.


Get webform values in page which is action for this webform I have created a form using webform in Drupal 6. I have set a action URL like node/15 a new node. When form is submitted it will be redirect this node. I want to display all values which are filled by user at this page. Please help.

Thank you

You can use hook_form_alter and add your custom submit handler.

    /**
     * Implements hook_form().
     */
    function hook_form_alter(&$form, $form_state, $form_id) {
        if ($form_id == 'WEBFORM_ID') {
            $form['#submit'][] = 'custom_webfrom_submit';
        }
    }

    /**
     * Implements webform custom handler
     */
    function custom_webfrom_submit($form, &$form_state){
        //get the values here $form_state['values']
    }


How to manipulate field with Number of value "unlimited" through php I've got a field image with unlimited number of value and a view who shows 12 of them from different node(in this case I can not use delta).
Now instead of showing the 8th and the 11th pictures I want to show a blank box with text.

I would like to insert this loop so I installed view PHP and I wrote this code on the box "Output code"

$counter = 0;
foreach ($row->field_image as $image){
  if ($counter++ = 8){
  echo "something";
continue;
}
  if ($counter++ = 11){
  echo "something else";
continue;
}
print $images;
}

What am i doing wrong?
How can I get the result I want?
Thanks in advance

Those if($counter++ = 8) lines look whacky to me.

don't you mean:

$counter++;
if( $counter == 8 ) {
  /* do stuff */
}

checking for equality is == or === not =


is it possible to add a permission to only one user , without creating role for him? i'm trying to create drupal 7 module for online payment , it will be by roles , for exemple ( user1 can create 'Blog content type' just if he has the permission on that) so after the payment i want to add that role to that user so i can avoid the each time creating roles for the users

thanks ^_^

Assuming you're using Ubercart this would be super easy by using hook_order through your own module: http://www.ubercart.org/docs/api/hook_order. I do this exact same thing with one of my other sites.

I can't go into it all, but essentially it flows like:

//make sure the order is complete and payment is received:

function sitetheme_order($op, &$arg1, $arg2) {
{
 // on the final update check this order
 if ($op == 'update' &&
     $arg1->order_status == "payment_received" &&
     $arg2 == "completed")
 {

In order to keep this short I can't include everything, but I have short loop written that loops through the order until it meets a condition like "Tickets". Then, I'll assign a role and do some other stuff. Like:

//If they bought tickets, assign them the role "TicketHolder"
if ($node->type == 'tickets') {
  //I assign some vars, for example the ID of the user role:
   $ticketUser = $node->uid;
   $customerRole = 16;
   //Assign this user the "TickHolder" role after the sale is complete
       $data = array(
       'uid' => $ticketUser,
       'rid' => $customerRole,
        );
   drupal_write_record('users_roles', $data);

That would be it. In your case you check to see if they purchased rights to create blog content, then assign the role.


My site was hacked, how can I use chmod permissions to avoid this? To be honest, only the home page was switched (even the text that was modified bragged about this, grrrr!), but still... not pleasant at all.

So the important question, and something that was on my mind for a long time but never got around to ask:

which files MUST be read-only or what kind of permissions should I had to enforce in which files to make this at least a bit more difficult?

Thanks in advance.

See: Securing file permissions and ownership

You also might want to try adding the Security Review module to help make sure your site is following the correct file permission settings.


Relation module tutorial I could not find good quality of tutorials on Internet for learning Relation module . Could anyone suggest some links for good documentation/tutorial for relation module ? Thank you .

Well, there are a number of screencasts available on the module project page as well as the official module documentation. Assuming you've already tried these and still need help, there are two possibly less obvious places you can go for 'tutorials':

Look through the source code of the module. Many of the more popular contrib modules have excellent documentation in the source on how to use the specific functions, methods, etc.
Scan the issue queue for relations. Other users may have some of the same questions you have (especially issues filed under 'support request') that may be of use to you.

Finally, most modules won't have really useful tutorials on how to use them and rely on the user community to help each other define what is needed. One of the best things you can do to help is to ask questions as you explore the relations module, either here or on Drupal.org, as others may have the same questions. As you get more confident, you can help by adding some of your experience back as a tutorial for other beginners.


custom permissions for score quizzes I need your help I need to make a very custom way of scoring quizzes and need some opinions and ideas.

I'm making a job applicants website, when you try to apply to a job in the website you have to take a quiz, and if you pass it your resume is sent to the creator of the job.

The complex part is that the quiz for the job is bound in the job content type with an entity reference field, the creator of the job can choose the quiz with an autocomplete field.

Now, I already have that part until the applicant finishes the quiz and then notify the creator of the job (instead of the creator of the quiz) if the applicant passed the quiz.

What I do not know how to do, is that the result of the quiz must be scored by the creator of the job, and not by the creator of the quiz.

A quiz can be reference to unlimited jobs, but when a quiz is bound into a job and somebody applies to a job, and answer the quiz, the results must be scored by the creator of the job instead of the creator of the quiz.

Any ideas how to achieve this?

When the quiz is completed I guess you need to email the job creator. You could do this using hook_node_insert().

E.g.

function hook_node_insert($node) {
  if($node->type == 'quiz') {

    // Get the job nid from the quiz nid
    $job_nid = db_select('field_data_field_quiz', 'q')
      ->fields('entity_id')
      ->condition('field_quiz_target_id', $node->nid)
      ->condition('entity_type', 'node')
      ->condition('bundle', 'job')
      ->condition('deleted', 0)
      ->execute()
      ->fetchField();

    $job = node_load($job_nid);

    $job_author = user_load($job->uid);

    drupal_mail (
      // The name of your module
      'my_module',
      // An arbitrary mail key, that you decide (used in hook_mail())
      'new_quiz_submission',
      // The destination mail address
      $to->mail,
      // The language that the mail should be sent in (requires translation if not English)
      $to->language,
      // Some parameters we can use in hook_mail()
      array (
        'account' => $job_author, // Pass the user account to hook_mail
      )
    );

  }
}

function my_module_mail($key, &$message, $params) {
  // The key allows for a module to define multiple mails. This
  // key needs to be the same as the first parameter in drupal_mail() above
  if($key ==  'new_quiz_submission') {
    $message['subject'] = t('New Quiz submission');
    // Each element of the body array becomes a new line in the email.
    $message['body'][] = t('Hello @user', array('@user' => format_username($params['to'])));
    // Adding an empty string to the body array adds an extra line in the email
    $message['body'][] = '';
    $message['body'][] = t('A user submitted a quiz. To see the results click here.');
  }
}

I pretty much just copied and pasted the code for sending simple emails from here.

I would create a view with a contextual filter that shows all of a particular authors quizzes that need scoring and then the link the in the email could just link to that view.

When they marked the quiz then I would also use a boolean field to mark the quiz as scored.


Font Awesome icons in link field I would like to have a font awesome icon in my link text.

<i class="fa fa-pencil"></i>Blogs

Since link fields are generated in LinkGenerator.php, they get escaped.

if (!SafeMarkup::isSafe($variables['text'])) {
  $variables['text'] = Html::escape($variables['text']);
}

There doesn't seem to be any way to bypass this by setting a HTML option to TRUE.

Is there any way to achieve this?

You can define your own template.

For example as inline:

$link = array(
    '#type' => 'inline_template',
    '#template' => '{{ title }}',
    '#context' => array(
        'url' => $url,
        'title' => $title,
        'fa_icon => 'fa-pencil',
    ),
  );

If you are working on a theme or module you should define a template with its own name like link_fa, so that it can be overridden by other modules or themes.


Cannot add files to a specific folder using file resumable module I recently moved to a droplet at DigitalOcean. Because they have small hdd's I added 20GB extra space to my droplet.

Because my resources does not fit neither on extra space or on the server's hdd I split the

  sites/default/files

folder by creating 2 symlinks  for 2 folders that hold around 15GB pointing to the extra space.

Now if I try to create a node of the type that should put the files in the extra space I get this error:

The upload directory public://xxx for the file field field_fisiere_audio could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

All the folders where I upload files have 700 rights. The owner and group is www-data.

Any idea why do I get this? Is this because of the symlinks? Is there any other way of splitting the files folder?

I also tried with 777 and is not working either.

Because I was pressed by time I made the following changes:

1 I moved the whole sites folder to the extra space (after I bought
   some more)

2  I created a symlink to sites

Everything seems to be working ok.

My idea is that inside files drupal can't handle symlinks.


Is this possible to allow creating nodes only for Administrator via interface but for others in custom code? As author of my content type I can choose any user (current user, even anonymous).

Nodes will created programmatically, so:

$node->uid = $current_user->uid;

However I want to allow access to node/add/custom_type (node form) only for Administrator or even block for everyone.

I am no totally sure that Drupal checks permissions before node_save(), so that's why I am asking.

If what you are asking is...

How can I allow nodes of a certain type to be created programmatically by everyone, but, at the same time, disallow everyone but the Administrator from creating them from the UI?

...the quickest way might be for you to use Rules to create a redirect away from node/add/custom_type for everyone but the Administrator.

However, if you are already creating custom module code, you could also do this pretty simply in hoot_init(), eg, something along the lines of:

global $user;
if ($_GET['q']=='node/add/custom_type') {
   if ($user->uid != 1) { // or whatever logic you want to use to determine the Administrator
     drupal_goto('somewhere else');
   }
}

In either case, you'd have to set up permissions to allow any user to create these types of nodes.


Is it important to reset the $user object when accessing global $user? I see that some developers reset the $user object in a manner similar to the following:

function my_example_callback($args) {
  global $user;
  $account = $user;
  $user = user_load(1); // Bypass access checks with User 1.
  $data = views_embed_view('my_view', 'page', $args);

  // Do things..

  // Reset the $user to the original value.
  $user = $account;

  return $data;
}

My question, is this really necessary? If so in what situations?

It depends..

Since you load the user object from the global scope, everything you change on it will affect other functions further down the line.

If you make alterations to the user object that only apply to your module, you might want to reset those changes so other modules won't be able to see the alterations you made. Think about adding something like adding a security key, then run it through some of your functions. You don't want other modules and functions to see the key, so you want to remove it from the user object after your functions are done with it.

For only loading the user and reading it, I'd say it doesn't make sense to reset the variable.

Update

As for your example, to bypass the access check the global user object (current logged in user) is swapped with the object of user 1.
In this case it is very important to switch back, otherwise all other functions will see you as user 1 rather than your own account!

See https://www.drupal.org/node/218104 for documentation on impersonating other users.


Mobile browser to be assigned different background I'm trying to get my site to operate differently depending on if the browser is a phone or a computer etc... I understand that this is most likely done using the sites.php file but I've been unable to get this working, and have an open question on SO about it.

Broad Question

This question is a little more specific and is to tied me over while I battle the broader issue out. I would like to remove the current background image when a mobile browser turns up. I thought something like the following would do it (same CSS file)

body {
 background-color:blue;
}

@mobile {
 body {
 background-color:green;
 }
}

but this doesn't appear to make any difference when using my HTC desire using Dolphin.

I use Omega for that.

It's based on CSS media queries.


Adding memory to themed pager? I have a content type called as People that lists all users on the site.

Next i have a view PeopleList that lists the content type People in a list form and has a pager.

I have customized the pager to look like a Load More button that adds the next set of People and the list grows on the same page. Now when i view a node and hit browser's back button the pager comes to first state only that is on first page .

For example- If i have 30 people listed and i hit load more next 30 add up and now if i view node say number 51 and hit browser's back button the pager comes to its default state that is first 30 people listing only.

How to solve this issue. What should i need to incorporate to get this sorted. Please guide.

It sounds like you wrote most of this yourself, or with some heavy work in Views maybe -- either way Good job! :)

You can solve your problem by saving the pager value into the users $_SESSION data. Every time they the pager page adds a key the querystring http://www.yoursite.com/page&page=2 you can check the querystring for the page key and save its value to the users session. Eg,

if (isset($_GET['page']) && intval($_GET['page'], 10)) {
  $_SESSION['your_custom_pager_index'] = $_GET['page'];
} else {
  $_SESSION['your_custom_pager_index'] = 1;
}

Then you can check for $_SESSION['your_custom_pager_index'] in your list form pager code to offset by whatever amount based on your index value.


how do I get Rounded Corners to work on a ddblock in drupal 7? I am trying to make the borders of a dd-block that I am using round. They are round in Firefox 5.0, but anything earlier than that, or in any other browser, it doesn't work. I have the CurvyCorners module installed, and I have the CSS set up to make it round. the problem is, that in chrome, only the header is round, and nothing else. and in Internet explorer, everything is round, except the dd-block, making it look like the dd-block is overlapping, and going over and past the corners of the region that it is in (being the Content region).
here is a copy of the CSS that is supposed to be making it round (I used 4 different classes/blocks at the same time just for a single dd-block, and it still won't work!):

#block-ddblock-7 {
    margin-left: -10px;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
   border-radius: 20px;
}

#block-ddblock-7 .slider {
     border-radius: 20px 20px;
    -moz-border-radius: 20px 20px;
    -khtml-border-radius: 20px 20px;
    -webkit-border-radius: 20px 20px;
    -o-border-radius: 20px 20px;
    width: 553px;
    height: 332px;
}

#ddblock-container clearfix ddblock-processed .inner {
     border-radius: 20px 20px;
    -moz-border-radius: 20px 20px;
    -khtml-border-radius: 20px 20px;
    -webkit-border-radius: 20px 20px;
    -o-border-radius: 20px 20px;
    width: 553px;
    height: 332px;
}

.slider ddblock-processed  {
    border-top-left-radius: 20px 20px;
    border-top-right-radius: 20px 20px;

    -moz-border-top-left-radius: 20px 20px;
    -moz-border-top-right-radius: 20px 20px;

    -khtml-border-top-left-radius: 20px 20px;
    -khtml-border-top-right-radius: 20px 20px;

    -webkit-border-top-left-radius: 20px 20px;
    -webkit-border-top-right-radius: 20px 20px;

    -o-border-top-left-radius: 20px 20px;
    -o-border-top-right-radius: 20px 20px;
}

what is it that I am doing wrong?

this is a picture of basically what it looks like. the part in blue is the "Content" region, and the part in orange is the ddblock:

I've used ddblock before with round corners.   I was able to do it all, across every browser, with the csspie module.

But atlas you are using CurvyCorners. With this demo, they are only using

.myBox {
    ....
    border: 3px solid #FFFFFF;
    border-radius: 20px 20px 20px 20px;
    ...
}

nothing to do with o-border, webkit-border, khtml-border, -moz-border, border-top-right etc.  half of these are browser specific  (ie -moz-border is for firefox only).


Get Authenticated User ID in Hook Cron? I have been trying to get the current authenticated user ID in Hook_cron() function.

But Its showing only the anonymous user, though the current user is an authenticated user.

How Could I get the current authenticated user in hook_cron()

There's no such thing - cron always runs as the anonymous user.

This is forced by the drupal_cron_run() function in Drupal 7:

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

and Cron::run in Drupal 8:

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$this->accountSwitcher
  ->switchTo(new AnonymousUserSession());


html.tpl.php is ignored I have Drupal 7 site using a custom theme, which was working just fine. I created some regions and then I went and extracted some parts of the html.tpl.php file and made them blocks to make them translatable. The idea was to display these new blocks in the new regions. But all of a sudden my theme stopped working and now drupal ignores my html.tpl.php file and uses the default. I have no idea what went wrong. Any help is much appreciated.

EDIT: I checked the logs and i noticed this error, just before the problem begun.

The directory /var/www/***********/tmp does not exist and could not be created.

I have a development server which runs the same site and this directory is specific to that. So i created a /tmp directory in the live site and set it in the configuration page but still the problem persists.

EDIT2: I am using a template.php file to send the blocks to the html.tpl.php. Something like this:

function <themename>_preprocess_html(&$variables) {
  $variables['footer_menu'] = block_get_blocks_by_region('footer_menu');
  $variables['info_bar'] = block_get_blocks_by_region('info_bar');
}

The question is bit confusing and contradicting. The html.tpl file is just there to take care of the HTML structure. If you need to add regions or change blocks, then page.tpl.php is the one you need to change.

SR


How to get form values in URL as keys of an array I have a custom form with min and max price value:

    $form['price']['min'] = [
      '#type'          => 'hidden',
      '#default_value' => isset($_GET['price']['min']) ? $_GET['price']['min'] : '',
      '#attributes'    => ['id' => 'price-min'],
    ];

    $form['price']['max'] = [
     '#type'          => 'hidden',
     '#default_value' => isset($_GET['price']['max']) ? $_GET['price']['max'] : '',
     '#attributes'    => ['id' => 'price-max'],
    ];

and I would like the URL after the form is submitted to look like this:

/search?price%5Bmin%5D=5000&price%5Bmax%5D=10000

but actually it's coming out like this:

/search?min=5000&max=10000

How can I get the form values to appear in the URL in the required format?

Try adding:

$form['price']['#tree'] = TRUE;

This tells the form builder you want to nest field names. Otherwise it will just use the most immediate element keys for the field names, as you have found.

This is actually useful behaviour most of the time, as it means you can group fields in containers such as fieldsets without affecting their name attributes.


Simplenews category approval I've got multiple newsletter purposes: some newsletters are for publicly available content and other newsletters are for example for journalists only or retailers only.

Is it possible to have each type as a Simplenews newsletter category? It doesn't seem to be out of the box, but I'm thinking it should be possible right?

My dream scenario would be to have these newsletter categories on admin/config/services/simplenews:

General news (open for all)
System news (mandatory for registered users)
Press releases (admin approval required)
Retail news (admin approval required)

Any suggestions on how to achieve this?

The long term idea is to add similar user roles for the restricted newsletter subscribers enabling restricted content, wholesale prices etc.

Probably not possible out of the box.

You'll need to implement access for them, see for example https://www.drupal.org/node/1140606 for some discussions/ideas.

In 7.x-1.x, categories are terms, in 7.x-2.x they are separate entities.

However,I doubt that simplenews, in either 7.x-1.x or 7.x-2.x fully respects whatever access you define there, but patches to improve that are welcome.


how to change the value of the form in the preprocess functions or get the value of the function preprocess I need to get the value of preprocess function and write it in the form #default_value, while my form is a variable that preprocess functions
I create custom module

<?php
/**
 * Реализация template_preprocess_comment()
 **/
function comment_email_form_preprocess_comment(&$variables){
    $variables['content']['email_form']['email']['#default_value'] = 'New value!';
    $variables['content']['email_form'] = show(drupal_get_form('comment_email_form'));
    dsm($variables);
}
/**
 * Создаем форму, которая будет хранить данные email адресов бригад и отправлять письмо.
 **/
function comment_email_form($form, &$form_state){
$query = db_select('comment', 'c')
    ->fields('c', array('cid', 'nid'));
$result = $query->execute();
$comments = array();
foreach($result as $value){
    $comments[$value->cid] = comment_load($value->cid);
 }
  $form['email'] = array(
    '#type' => 'textfield',
    '#access' => TRUE,
    '#default_value' => 'test123',
    '#required' => TRUE,
  );

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

  $form['#validate'][] = 'comment_email_form_validate';
  $form['#submit'][] = 'comment_email_form_submit';
  return $form;
}

Thanks for any help.

You pass extra arguments when building the form using the drupal_get_form.

For example:

drupal_get_form('comment_email_form', 'default_value');

function comment_email_form($form, &$form_state, $default_value)
{
    // $default_value is here the string 'default_value' value passed as extra argument
    // ... rest of your form
}


Trying to get fullPage.js implemented, but how to add data-attributes? This is such a great script called fullPage.js

I managed to load the js file and css file and even with the Void Menu Module, managed to call anchor links, but I'm struggling with the data attributes part of the implementation of this cool code!  Any help is greatly appreciated!  How do I get data-attributes to work in Drupal 7.25?  I mean, I need to add them to the menu, so that the html looks something like this:

First slide

Second slide

Third slide

Fourth slide

Just want to add it to the Main Menu in Drupal.  Any idea how?  Am trying to implement this on my homepage and using the Adaptive Sub-Theme with Display Suite Module installed, if that helps any.

Have added the following to template.php, but it makes no difference at all:

function MY_THEME_NAME_menu_link(&$variables) {
  $variables['element']['#attributes']['data-menuanchor'] = substr($variables['element']['href'], 1);
  return theme_menu_link($variables);
}

What am I doing wrong here?

Now there is contributed module that will let you add custom attributes per menu item, you can find it here: Menu Links Attributes


how to apply exposed filter without apply button in Drupal 8 views? I have textfield as exposed filter in table view. How I can apply that filter without pressing apply button. any contrib module or suggestion?

Try this It may solve your problem. It may not be the proper solution but it will help you apply filter without having to click on apply button.

(function($) {
  $(document).ready(function() {
 $(document).ajaxComplete(function(event, xhr, settings) {
 $(".views-exposed-form .form-select").change(
         function(){
           $(".form-submit").click();
         }
);
  });
       });
})(jQuery);


How to grant userpoints only for modifying nodes last changed at least 20 days ago? I am not sure how to go about this. I use the Userpoints module in Drupal 7 to attribute points to users who create nodes ('reviews'). I also want to allow them to gain some points if they supersede or modify an existing node... but only if the previous creation/mod was done over 20 days before.

How can I do this with Rules? Or else, how should I code it manually?

Sorry to say, but the previous answer has some challenges:

Rules Event After saving new content is not the right event.
I disagree with the "You will need a custom module ...", since there is an out-of-the-Rules-box Rules Condition you can use ... Read on for more details on that.

Here is a rule (in Rules Export format) that does what you're asking for:

{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Some more details about the above rule:

Rules Event: After updating existing content (you may want to limit it to selected content types only).
Rules Condition: Token [node-unchanged:changed] is at least from 20 days ago.
Rules Actions:

Grant 123 user points (adapt the number and the other options as you want).
Load the current userpoints balance.
Display a message with the current userpoints balance.

If you have the Rules UI enabled (and the Userpoints Rules module, you should be able to just import the above rule in your own site.

PS: After you're convinced the rule works as you want, you may want to remove the last 2 Rules Actions about the message shown to the user after user points were granted.