How can I use Drush to determine if a module is being used or not in a multisite architecture? I have a multisite architecture that has over 30 sites.

In one specific site search_api_solr version 7.x-1.0RC5 is installed, and I can see that it's enabled and being used in the module list.

In the common sites/all/modules folder search_api_solr 7.x-1.0-rc2 is there. When I do drush pm-list | grep search I can see that it's listed but "Not Installed."

Does this mean that none of the 30+ sites is using this module and it's safe to delete it? Or is that command simply telling me that it's not being used by the default install?

If the latter, how can I use Drush to tell me what specific sites are making use of modules in the common sites/all/modules directory?

EDIT:

@greg_1_anderson

I tried your solution with:

drush @sites pm-info search_api_solr --field=status

On each line of the output after hitting y I get something like:

.appdrupal#mysite.example.com >> blahblah : some.description

looks like the above output is 3 columns. Possible values for that 'blahblah' column seem to be numerous (requires, required by, type, title, description, version, date, package, 'group', files.. etc, etc..) nothing to denote if it's enabled)

I can see a couple times in the 'blahblah' "status", but it's not singled out. Ultimately this creates 1000s of lines of output. I tried to add | grep status but it hanged (I gave it 120 seconds).

Drupal is 7.26 and Drush version is 5.9 - thoughts?

This works in Drush 6.x and later:

$ cd /path/to/drupalroot
$ drush @sites pm-info MODULENAME --fields=status
You are about to execute 'pm-info devel' non-interactively (--yes forced) on all of the following targets:
  /path/to/drupalroot#default
  /path/to/drupalroot#other
Continue?  (y/n): y
.path.to.drupalroot#other   >>  Status   :  enabled
.path.to.drupalroot#default >>  Status   :  enabled


Show a boolean as a pair of images? I have PictureEvents and those have a few boolean fields:

HasCD | HasDVD | HasSlowMo

I'd like to have an icon for each of them that is dim/bright in all the places where it's shown (I have a few Field-Views for the lists of PicutureEvents, and I'd like to place the icons below the video in the main page).

Where do you do this in Drupal 7?

Easiest way to do this would be in a content-type template. You want to create a template for your content type, ex. node--[type|nodeid].tpl.php and add this in your theme folder. In your template, for displaying the boolean field you could use logic like this:

<?php
if ($node->field_boolean_field[$node->language][0]['safe_value'] == 0) {
    print "";
} else {
    print "";
}
?>

This similar question may help as well:

Optionally add image/icon after node title based on boolean content type field?


How to update the search title and page title depending on facet options I am using Search Api Views module to list some publications. User can filter them using facets. For example he can look for publications only in Kenya.

I want to update the title of my page (view) depending on this user selection.

Here is a screenshot of my application:

I tried to use Facet API Bonus module, unfortunately I cannot figure out how to use it, I looked everywhere, but cannot find where the configuration interface is located..

The solution is on the Facet API Bonus module's project page:

Integration with Page Title module Now you can set search (views) page titles using Page Title module. Module provides possibility to set tokens 'facetapi_results' and 'facetapi_active' groups. So in title we can display number of results on the page or values of active facets. As there can be multiple active facet values please use following pattern to use facetapi_active tokens:
list<[facetapi_active:facet-label]: [facetapi_active:active-value]>

This will make coma separated list of active facet labels and their values.


How to get by insufficient memory impass - can't access site? Can someone help me by this impasse?
I have multiple instances of Drupal running (for now).  One is for testing and major changes.  It seems that I cannot get past the WSOD on my testing instance.  The php.log indicates insufficient memory when database.mysql.inc runs.  I've tried my php.ini max memory setting at 256M and even -1 (unlimited) and restarted apache with no better results.  I can't run drush, can't access the test site.  I'm STUCK!

Can anyone suggest a method to get by this issue to allow me to move forward?  BTW - the other instances work just fine with a 128M max.

There is 3 method to increase your PHP memory limit.  They are all outline in http://drupal.org/node/207036

The best way to check your current situation is to create a file in the root directory call phpinfo.php, with these lines of code

<?php
  print phpinfo();
?>

Then check the settings by going to http://www.example.com/phpinfo.php


How to add a new calculated field by using `hook_views_query_alter`? I have three node types that I have created relations between using the Relation module.
Seaon --> Player --> Week

The player node has a numeric field called cost.
The relationship between the player and the week has a numeric field called score.

The following is a views query (with some alias changes to make it a tad more intelligible) that I use to summarise data per season.
The view works fine but I need to add a calculated field that takes the sum of the weekly scores and divides it by the player cost.

SELECT  PLAYER.title AS PLAYER_title
        ,PLAYER.nid AS PLAYER_nid
        ,PLAYER_COST.field_cost_value AS PLAYER_COST_field_cost_value
        ,MIN(PLAYER.nid) AS PLAYER_nid_1
        ,'node' AS field_data_field_cost_node_entity_type
        ,MIN(PLAYER2WEEK.rid) AS PLAYER2WEEK_rid
        ,'relation' AS field_data_field_score_relation_entity_type
        ,SUM(PLAYER2WEEK__field_data_field_score.field_score_value) AS PLAYER2WEEK__field_data_field_score_field_score_value
FROM    {node} SEASON
INNER JOIN
        {field_data_endpoints} FDE
ON      node.nid = FDE.endpoints_entity_id
AND     (FDE.bundle = 'player_in_season'
AND     FDE.endpoints_entity_type = 'node'
AND     FDE.endpoints_r_index = '1')
INNER JOIN
        {field_data_endpoints} FDE2
ON      FDE.entity_id = FDE2.entity_id
AND     (FDE2.endpoints_entity_type = 'node'
AND     FDE2.endpoints_r_index !=  FDE.endpoints_r_index
AND     1 = '1')
INNER JOIN
        {node} PLAYER
ON      FDE2.endpoints_entity_id = PLAYER.nid
AND     FDE2.endpoints_entity_type = 'node'
LEFT JOIN
        {field_data_endpoints} PLAYER_FDE
ON      PLAYER.nid = PLAYER_FDE.endpoints_entity_id
AND     (PLAYER_FDE.bundle = 'has_weekly_score'
AND     PLAYER_FDE.endpoints_entity_type = 'node'
AND     PLAYER_FDE.endpoints_r_index = '0')
LEFT JOIN
        {relation} PLAYER2WEEK
ON      PLAYER_FDE.entity_id = PLAYER2WEEK.rid
LEFT JOIN
        {field_data_field_cost} PLAYER_COST
ON      PLAYER.nid = PLAYER_COST.entity_id
AND     (PLAYER_COST.entity_type = 'node'
AND     PLAYER_COST.deleted = '0')
LEFT JOIN
        {field_data_field_score} PLAYER2WEEK__field_data_field_score
ON      PLAYER2WEEK.rid = PLAYER2WEEK__field_data_field_score.entity_id
AND     (PLAYER2WEEK__field_data_field_score.entity_type = 'relation'
AND     PLAYER2WEEK__field_data_field_score.deleted = '0')
WHERE   (( (node.nid = '3' ) )
AND     (( (node.type IN  ('SEASON')) AND (node.status = '1') )))

From all the reasearch I've done, it looks like the correct option is to use hook_views_query_alter() to add the new field.
This is where I lose it, I have no idea how to write the code to build the new field.
Essentialy, based on the query above the field needs to be

SUM(PLAYER2WEEK__field_data_field_score.field_score_value) / PLAYER_COST.field_cost_value AS new_field

I just need some help in getting strated on the code in my custom module

This answer seems to meet my requirements conceptually, I am just lost on how to construct the function.

Turns out that I didn't need the hook at all. I was able to achieve the result by using a Math Expression within the views module


WYSIWYG Editor with highlighting for PHP code input Is there a WYSIWYG editor that would do highlighting for typed in text?

I'm looking for something similar to the way Notepad++, and similar, does highlighting depending on the file opened. Doesn't format the output of the file (php stays php, but it gets colored based on "s, tags and what not.

Or is their a way to get CKEditor (or similar) to do this?

I've done a brief looking and haven't seen anything like what I'm looking for.

EDIT
Just to be clear: I'm not looking to format the output of the field; I'm looking to format the field while inputing PHP code (or similar). I can use Geshi or SyntaxHighlighter to format the output of code easily. I haven't figured out how to format the code on the input field.

I want the right side (PHP field content entering in Drupal 7) to look like the left side (Notepad++): pretty colors, parenthesis matching, keyword highlights, etc.

For output highlighting, you want the Syntax highlighter module. That syntax highlighting module integrates with a couple of other WYSIWYG modules, and you can find great setup instructions.

For in-editor syntax highlighting, you will want the Wysiwyg CodeMagic module. It depends on CodeMagic, TinyMCE, and Drupal's WYSIWYG module. That will allow you to do input highlighting, as demonstrated here:


how do I add a table and where clause to query object using hook_views_query_alter()? I currently have a unique situation whereby I need a to use a different term reference field in a view's contextual filters based on a node's content type value. I don't want to have to manually add a display for each possible combination of content types so I have been tying to use hook_views_query_alter() to accomplish what is now seeming impossible to me.

In my .module file I have:

/**
 * Implementation of hook_views_api().
 */
function mymodule_views_api() { // your module name into hook_views_api
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule').'/includes',
  );
}

Then in the file mymodule/includes/mymodule.views.inc:

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(&$view, &$query) {
   //this is the name of our View and Display
   if ($view->name == 'shop' && $view->current_display == 'listings') {

       $query->add_table('field_data_field_my_category');
       //then add where clause afterwards etc etc
   }
}

This throws the error:

  Fatal error: Call to undefined method SelectQuery::add_table()

Which leads me to believe that the Views API is not loading properly, unless I'm completely on the wrong track here.

I've been trying to find the best practices for altering views queries but have just ended up being generally confused and frustrated. Could anyone lead me towards the light please?

I don't know enough about your problem to say whether using  hook_views_query_alter is the best approach.

In regards to the error you're getting, the answer is in the error message: the query object you have is an instance of SelectQuery. If you look at the documentation for SelectQuery you will see that it doesn't have an add_table method.

Instead you should use SelectQuery::addJoin (or one of the more specific methods, such as SelectQuery::innerJoin, SelectQuery::leftJoin, etc.)


Inserting space/gap between two main menu links In my main menu, I have the following links: Home, About Us, Blog, Log In and Sign Up.
I want the Log In and Sign Up links to float to the right such that there will be space/gap between the 'Blog' and 'Log In' links.

Please how can I achieve this?

You can use menu attributes module to specify ids for those both menu then you try


Query taxonomy term for given product I have a node template, rendering a product list based on a query :

$productsQuery = db_select('commerce_product', 'p');
$productsQuery->join('commerce_product_type', 't', 't.type = p.type');

$productsQuery->fields('p')
    ->fields('t')
    ->condition('p.status', 0, '>')
    ->orderBy('p.created', 'DESC')
;

$results = $productsQuery->execute()->fetchAll();

foreach ($results as $product) {
    $productNodeQuery = new EntityFieldQuery();
    $productNodeQuery->entityCondition('entity_type', 'node', '=')
        ->propertyCondition('type', $product->type)
        ->fieldCondition('field_product', 'product_id', $product->product_id, '=')
        ->range(0, 1);

    if ($node = $productNodeQuery->execute()) {
        $node = array_shift($node['node']);
        // Render the node
    }
}

It is working well, but I do not access to the different fields of the product-display node in EntityFieldQuery...

For instance, In my product-display, I have a required relation to a taxonomy term, that I would like to display for each product.

How to get this specific field ?

An EntityFieldQuery just returns IDs, you need to load the entities manually:

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node'));
  foreach ($nodes as $node) {
    if ($items = field_get_items('node', $node, 'field_foo')) {
      // ...
    }
  }
}


Sorting content list alphabetically Is there any way to sort Drupal's content list in the admin area alphabetically by title? I am using Drupal 6.

A simple solution is to override the default content list or to create an alternative one using Views and VBO.

With views it's easy to create sortable tables. I believe a view of the content listing is already predefined in either VBO or Views.


created element with ajax ,not act autocomplete i have a select option value , in change create a text field with auto complete feature,
every thing is ok , but autocomplelete of this element not work!!!

part of my code

        $form['azlocation']=array(
            '#type' => 'select',
            '#title' => 'location',
            '#options' => array(1,2,3),
            '#default_value' => 1,
            '#description' => t('select your news location.'),
            '#ajax' => array(
                    'event' => 'change',
                    'callback' => 'country_select_f',
                    //'path' =>'roadtonowhere',
                    'wrapper' => 'city-term',
                    'method' => 'replace',
                    'effect' => 'fade',
            ),
            );
    $form['field_terms_city']= array(
            '#markup' => '

');

    function country_select_f(&$form, $form_state){
$form['city_list_item2'] =array(
        '#type' => 'textfield',
        '#title' => t('select city (optional)'),
        '#autocomplete_path' => 'user/autocomplete',
        '#weight' => -1,
        '#attributes' => array('id' =>'city-term-select'),
);

where is the problem?

Try this.

$form['azlocation'] = array(
'#type' => 'select',
'#title' => 'location',
'#options' => array(1, 2, 3),
'#default_value' => 1,
'#description' => t('select your news location.'),
'#ajax' => array(
  'event' => 'change',
  'callback' => 'country_select_f',
  //'path' =>'roadtonowhere',
  'wrapper' => 'city-term',
  'method' => 'replace',
  'effect' => 'fade',
 ),
 );
 $form['field_terms_city'] = array(
 '#type' => 'textfield',
 '#title' => t('select city (optional)'),
 '#prefix' => '
',
 '#suffix' => '
',
 );
 return $form;
}
function country_select_f($form, $form_state){
   $form['field_terms_city']['#autocomplete_path'] = 'user/autocomplete';
   return $form['field_terms_city'];
}


Drush doesn't detect drupal installation under sites sub-directory I have been using  Drush 4 and 5 with no problem. Now that I have downloaded and installed new Drush 7.0-dev using composer, I am having problem i.e  it doesn't by-default detect drupal installation when I am on sites sub-folder,

Drush running on sites-root directory,

drupal7/sites/example.com/modules/views$ drush status

 Drupal version                  :  7.30
 Site URI                        :  http://example.com
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database port                   :
 Database username               :  example_user
 Database name                   :  example_db
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  bartik
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php5/cli/php.ini
 PHP OS                          :  Linux
 Drush version                   :  7.0-dev
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :
 Drupal root                     :  drupal7
 Site path                       :  sites/example.com
 File directory path             :  sites/example.com/files
 Temporary file directory path   :  /tmp

Drush running under sites-subdirectory,

drupal7/sites/example.com/modules/views$ drush status

 Drupal version         :  7.30
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  drupal7

So, how do I configure Drush, is there anything I can do to make it work, I don't want to use --uri  or -l flag or any other options everytime.

Update

Also when I download modules it get downloaded on sites/all/modules directory

drupal7/sites/example.com/modules$ drush dl webform
Project webform (7.x-3.20) downloaded to drupal7/sites/all/modules/webform.                                     [success]

But if I am on sites-root directory it works fine,

drupal7/sites/example.com$ drush dl webform
Project webform (7.x-3.20) downloaded to /home/sysop/project/drupal7/htdocs/sites/heisenberg.com/modules/webform.                          [success]

You need to add an alias conf file named YOUR_SITE_NAME.aliases.drushrc.php in sites\all folder with that code.

// The site in sites/YOUR_SITE_NAME/
$aliases['YOUR_SITE_NAME.local'] = array(
  'uri' => 'YOUR_SITE_NAME_URI',
  'root' => '/path/to/drupal_root_folder',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);

Then clear cache : drush cache-clear drush.

Test your alias : @YOUR_SITE_NAME.local status.

To run a command, for the sake of example : @YOUR_SITE_NAME.local mb MODULE_NAME hook1 hook2 --write

UPDATE : in order to create automatically Drush site aliases for many sites, place this code in your aliases.drushrc.php file.  Drush will look for aliases.drushrc.php in the ".drush" folder in your home directory (see this post to get sure where to put this file).

$aliases = array();
$drupal = '/var/www/drupal';

// Automatic alias for each Drupal site
$site = new DirectoryIterator($drupal . '/sites');
while ($site->valid()) {
  // Look for directories containing a 'settings.php' file
  if ($site->isDir() && !$site->isDot() && !$site->isLink()) {
    if (file_exists($site->getPathname() . '/settings.php')) {
      // Add site alias
      $basename = $site->getBasename();
      $aliases[$basename] = array(
        'uri' => $basename,
        'root' => $drupal,
      );
    }
  }
  $site->next();
}

// Get all site aliases
$all = array();
foreach ($aliases as $name => $definition) {
  $all[] = '@' . $name;
}

// 'All' alias group
$aliases['all'] = array(
  'site-list' => $all,
);

You can also read this : create your own drush aliases. You could even think about managing synchronization between remote and local systems (source).

EDIT : as per ericx comment, consider adding bash-completion. Drush comes with a bash-completion file, drush.completion.sh, which offer alias completions.


Retrieve Drupal Commerce order history Is it possible to retrieve a user's order history programatically?

Ideally, I would be able to user the user's profile ID to then load multiple past orders.

Yes you can use the commerce_order_load_multiple() function and take advantage of the $conditions parameter, e.g.

$orders = commerce_order_load_multiple(array(), array('uid' => $user_id));


Validate if Date1 > Date2 If I have 2 date fields in a content type: Event Start Date and Action Start Date.

Is there a way to validate that Action Start Date is later/greater than Event Start Date while creating the content?

If you use the Date module you can create one field and configure it to use a start and end date. Then the module will validate the end date is greater than start date automatically for you.


How to modify jsonapi response? Hello Drupal community.

I have a “Product” content type with field_alert_date field.
The field date type is “Date only” so when I get jsonapi response
by accessing jsonapi/node/product I have the following output for this field:

"field_alert_date":"2020-02-22"

However, this response will be used by another program
and that program requires data in the following format:

"field_alert_date":"2020-02-22 0:00:00”

So I need to modify the jsonapi output to add “0:00:00” (or another time) without changing the field data type.
The program is not developed by me so I cannot change this requirement.
I have to do something with the output of the jsonapi.

Could you please tell me if it is possible and how it can be implemented?

You can change the JSON output of a date field by implementing a custom Normalizer for date fields in a custom module. I got it to work using the following code. This is a bit of a hatchet job, so you'll want to clean up and stuff, but otherwise it should do the job:

/src/Normalizer/DateTimeCustomNormalizer.php:

<?php

namespace Drupal\custom_date_serializer\Normalizer;

use Drupal\serialization\Normalizer\DateTimeIso8601Normalizer;

/**
 * @internal
 */
class DateTimeCustomNormalizer extends DateTimeIso8601Normalizer {

  /**
   * {@inheritdoc}
   */
  protected $allowedFormats = [
    'RFC 3339' => \DateTime::RFC3339,
    'ISO 8601' => \DateTime::ISO8601,
    // used to be 'Y-m-d', so you can use any PHP date format you want
    // I just set it to this because it was easy to test
    'date-only' => \DateTime::ISO8601,
  ];
}

And /custom_date_serializer.services.yml:

services:
  custom_date_serializer.normalizer.datetimecustom:
    class: \Drupal\custom_date_serializer\Normalizer\DateTimeCustomNormalizer
    arguments: ['@config.factory']
    tags:
      # Priority must be higher than other datetime normalizers.
      - { name: normalizer, priority: 40 }

And you'll need an info.yml obviously.


Conditional Fields Module in drupal 8 Hi I have enabled the drupal 8 conditional fields module , but I do not see anywhere to configure it, the "Malnage Dependencies" tab that is supposed to appear does not show.  Am I missing a step?
thanks,

According to the code, these are the admin routes. The links file would indicate that Conditional Fields should appear in the Structure area of the admin. Did you clear cache after enabling it? It should be in the Structure menu.


curl nor wget was found When I use drush to download modules, I get this weird error:

drush dl registry_rebuild
exec(): Unable to fork [wget --version 2>&1] exec.inc:150 [warning]
exec(): Unable to fork [curl --version 2>&1] exec.inc:150 [warning]
exec(): Unable to fork [which curl 2>&1] exec.inc:150 [warning]
wget nor curl executables found. [error]

which wget gives me /usr/bin/wget and which curl gives me /usr/bin/curl. /usr/bin/ is in my PATH. This seldom works if I do drush cc drush. How do I solve this permanently?

On Centos, to install wget:

sudo yum install wget

To install curl the following should suffice:

sudo yum install php-curl
sudo service httpd restart

++++++++++++++++++++ EDIT +++++++++++++++++++++++++

According to this post, "unable to fork" errors are likely to result from too many processes running.  They recommend increasing the limit like so:

sysctl -w kern.maxprocs=1000000


Redirect anonymous user to login page I need to redirect an anonymous user when they hit the url 'node/add/project' to 'user/login' - otherwise, just leave them enter that url.

Not sure if I'm going about this the correct way (probably not as it doesn't appear to work!) - Can someone shed some light, or advice!

function local_menu() {
    $items['node/add/project'] = array(
        'page callback' => 'local_project_anonymous',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function local_project_anonymous(){
    global $user;
    if($user->uid == 0){
        drupal_goto('user/login');
    }
}

Cheers

function MODULE_init(){
  global $user;
  if ($user->uid == 0  && $_GET['q'] == 'node/add/project' ) {
    drupal_goto('user/login');
  }
}


How to find bad PHP node that makes search_cron fail? I can't run cron, manually or automatically. I installed Cron Debug module, checked all modules, and found out that the Search module makes cron stuck. When I disable it, cron is working.

I suppose the reason is one of my nodes has bad PHP code in it.
I googled for "search_cron errors", and found a solution in Drupal.org
I tried it by editing node.module, but I got this error:

  Fatal error: Call to undefined function db_fetch_object() in /home/mysite/public_html/modules/node/node.module on line 2616

Can you propose me a solution on how I can find the errorenous PHP code in nodes?
I am using Drupal 7.12.

i was facing this issue after upgrading a big application from 6 to 7.This is what I did. From the database run this query

SELECT n.nid FROM node n LEFT JOIN search_dataset d ON d.type = 'node' AND d.sid =
n.nid WHERE
d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid asc

This will give you the last node that is giving you issues and has refused to be re-indexed.
From there you can do what you want with that node. For my case I realized it was a whole content type that was not displaying well. I had to resave one of the fields to allow this content type to display.


Using Panelizer, how can I add a new menu item properly I want to add a menu item the right way See "Edit IV Block" in the picture below.

That is the wrong way to do it.

The code is here: http://api.drupalecommerce.org/api/panels/panels!plugins!display_renderers!panels_renderer_editor.class.php/function/panels_renderer_editor%3A%3Aget_pane_links/7.x

If you search for  drupal_alter('get_pane_links', $links, $pane, $content_type); you can see that the get_pane_links hook is supposed to fire, but for some reason it does not fire.

My question is, it seems like drupal_alter('get_pane_links') is the correct way to add menu items, but I've tried adding functions in other modules and they don't get called. I modified the code to do

echo 'before';
drupal_alter('get_pane_links', $links, $pane, $content_type);
echo 'after';

And no dice.
What is the correct way to add a menu item or how to I implement this hook?

Cleared the cache and then it worked.
Found this by doing a $modules = module_implements('get_pane_links_alter');


View page as default page for content type This could be a noob question but i am really not able to understand how to achieve this. I have several content types and custom detail page i.e view page for each content type. So each time i add/edit/update/search a content type say news or something, it redirects me to default node page but i don't want that. I want it to redirect to the view page i have created.

There is a module called Rules, which helped me to redirect to that page after adding/updating content, but it has some redirection errors which results in server ended unexpectedly error. Also in search the default page shows up as node page not my custom view page.

How do i do this, so that my custom view page becomes the default page for my content type. Please help..?

There are a couple of ways to do this.

One is to edit your node template file and field order so that the default node view is how you want it to look.

Another, if you prefer to create a view, is to do so and use a module like Internal Nodes or Page Manager (part of ctools) to redirect to the view.


How do I assign a role after user clicks a link? I'm trying to get a behavior when a link is clicked, a role is applied to a user.

My use case is to allow a registred user to step into another type of user. Example is airbnb.com. You are a renter but once you click a certain menu link you become a host and get new menu items to then list your house.

I want to give permissions and access to certain areas of the site only when someone decides to unlock it.

You can use Rules for that. The configuration can be({{}} are placeholders, do not use on the real values):

React on event "Content is viewed"
Condition: Data comparison (Parameter: Data to compare: [node:nid], Data value: {{NID from the node you're using to trigger this role activation}})
Action: Add user role (Parameter: User: [site:current-user], Roles: {{the role you want to add}})


Source entity type and id in webform node Im looking for a way to set the source entity type and id to a webform that is inside a webform content type (webform_node)

I followed the modal convention: the address of the webform is /webform/14?source_entity_type=node&source_entity_id=15
Now i would like this to work.

in QueryStringWebformSourceEntity class i see the notice

 // Note: We deliberately discard $ignored_types because through query string
 // any arbitrary entity can be injected as a source.

which makes sense.
what are my options then to add my source identity to the webform submission?

thank you!

a naive solution:

function THEME_preprocess_node(&$variables){
  //adding query source entity and type to a webform node
 if($variables['node']->getType()=='webform'){
   if (\Drupal::request()->get('source_entity_type') && \Drupal::request()->get('source_entity_id')){
     $variables['content']['webform'][0]['#entity_type'] = \Drupal::request()->get('source_entity_type');
     $variables['content']['webform'][0]['#entity_id'] = \Drupal::request()->get('source_entity_id');
  }
 }
}


How to remove the shipping flat rate for particular products in Drupal commerce kickstart? I am using Commerce kickstart. I have to add the products for category wise. Categories are DVD,Audio CD and edownload.I have to use term reference field for field_category in the products content types.

Now the user purchase the edownload products means shipping charge should be 0rs. How to set the edownload term reference field products for shipping charge is 0. Anyone guide to me?.

Thanks in advance.

Try using these modules:

Commerce Discount Product Category
Commerce Discount


New Relic performance monitoring and the Features Module We've just started using New Relic to monitor our D6 sites, and are also taking advantage of New Relic's ability to report on Drupal module performance.

Our sites contain several modules with configuration exports that are controlled by Features (views, content types, etc).

New Relic's module performance page shows features.module as being the slowest and as having the highest function call count.

It was my understanding that Features doesn't do too much of anything except for when you are creating/updating/reverting your features, so I'm confused as to why New Relic would report it as being such a drag in terms of site performance.

Can anyone confirm that Features does indeed significantly impact site performance? Or confirm that it doesn't (in which case this seems like a New Relic issue).

By design, Features shouldn't induce any performance hit besides what is inherent to any Drupal module.  It doesn't implement hook_init() or hook_boot(), nor does it implement any hook_form_alter()s or Node API hooks, so there should literally be no Features activity on most page loads.

However, every time caches are cleared, Features does some heavy work — it interrogates all Feature modules and rebuilds Faux-Exportables.

There are two kinds of Features Components: Exportables and Faux-Exportables.

Exportables

Anything that is a CTools Exportable is also a Features Exportable, such as Views, Contexts and Panels.

On this issue thread, one of the Features maintainers says:

  Generally speaking a View in the database and a View in code perform exactly the same. There are some slight differences in loading methodology (it helps to have a good PHP code cache like xcache or APC when using exportables as the data lives in code), but other than that you shouldn't see any differences.

Faux-Exportables

Faux-Exportables include content types, CCK fields, taxonomy, roles, and permissions.

Faux-Exportables are by definition stored in the database, so they do not require any intervention from Features.  Features only touches Faux-Exportables when rebuilding (as mentioned above).


How to fix display problems with CKEditor? I have installed CKEditor 3.6.0.6, I have enabled some buttons as in image:

CKEditor 3.6.0.6 in full size browser

However when I resize the browser smaller than the buttons zones, here is how is looking:

How can I brake CKEditor buttons to be displayed on multiple lines ? And why this behavior of CKEditor?

My browser Chrome 12.0.742.100. In Firefox 5 is the same problem.

CK Editor supports to manage toolbars. In toolbars you can manage Buttons. See the guide.


How do I set up multiple sites with one database or multisite Apache configuration? I have a problem in multisite with Drupal 7.26. The name of the site is multisite, and the IP is 192.168.1.99.

I created a folder that hosts a new site (/var/www/multisite/sites/site1), copied the settings.php file into the site1 folder; the 127.0.0.1 site1 line is present in the hosts file.

This is the content of /etc/apache2/sites-available/site1.

<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  ServerName site1
  DocumentRoot /var/www/multisite/sites/site1

  <Directory />
    Options FollowSymLinks
    AllowOverride All
  </Directory>
</VirtualHost>

I executed the following commands.

sudo a2ensite site1
sudo /etc/init.d/apache2 reload

If I use 192.168.1.99/multisite/, it works; if I use 192.168.1.99/site1, I get the following error:

  The requested URL /site1 was not found on this server. Apache/2.2.22
  (Ubuntu) Server at 192.168.1.99 Port 80

What did I do wrong?

should i add any redirect base code in .htaccess file?

    Solution: Give Symbolic link form mulitsite to site2
    Executed that command line
    ln -s /var/www/multisite /var/www/site2

    Rename example.sites.php to sites.php

    $sites['192.168.1.99.site1'] = 'site1';

    put this line in sites.php

I got a result . Thanks for post the answers this questions

Reference URL:

  https://drupal.org/node/2622
  https://drupal.org/node/43816/

The new site vhost should be pointing to the drupal root installation where the index file lives and the entry point for all your sites, not to the site1 folder.
"DocumentRoot /var/www/multisite" this should be the same for all your sites.

With multi-site a approach you can shared modules between sites (those in all folder), have different modules per site, you can have different databases per site and share tables between them.

Your drupal sites are going to share the same code base, One drupal core for everyone.

This can be useful https://drupal.org/documentation/install/multi-site


How to use hook_form_alter to hide a form field for certain users? function custom_form_alter(&$form, &$form_state, $form_id) {

global $user;
$node = node_load(arg(1));
$num  = $node->field_node_reference['und'][0]['nid'];
$val  = node_load($num);
$event_noderef_uid = $val->uid;

if($form_id == 'regester_node_form'){

if($user->uid == $event_noderef_uid){
 $form['field_NAME']['#access'] = FALSE;
 }

I want to get ($user->uid == $val->uid) to Hide "field_NAME"

You can clean up the code a bit by using hook_form_FORM_ID_alter:

function mymodule_form_regester_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $node = node_load(arg(1));
  $num  = $node->field_node_reference['und'][0]['nid'];
  $val  = node_load($num);
  $event_noderef_uid = $val->uid;

  if($user->uid == $event_noderef_uid){
    $form['field_NAME']['#access'] = FALSE;
  }
}

Other than that, if field_NAME exists in the form and the condition is true, access will be set to FALSE. If you are testing this as user 1, you may not be seeing the results you desire as that is the superuser. It would help if you posted the form you are trying to alter and what its structure is for field_NAME. Probably a really good case to write an automated test for as well.


wrong translation in admin/structure/views I have a multi language site with Drupal 8.7.4
and default language is English.

when i go to en/admin/structure/views i see list of views in English language. if i go to french interface via fr/admin/structure/views i expect to see list of views in french words for example i expect to see 'Surveillance' instead of 'watchdog' but i see all views name in English.

Config Translation is enabled and french translation for view's name is available.

The Views list is a config entity list and these are listed override free:

ConfigEntityListBuilder::load

  public function load() {
    $entity_ids = $this->getEntityIds();
    $entities = $this->storage->loadMultipleOverrideFree($entity_ids);

    // Sort the entities using the entity class's sort() method.
    // See \Drupal\Core\Config\Entity\ConfigEntityBase::sort().
    uasort($entities, [$this->entityType->getClass(), 'sort']);
    return $entities;
  }

This is intentional. The pros and cons are discussed in these issues:

Config entity admin lists show configuration with overrides (eg. localized)

Menu overview always shows the untranslated config entities


How can I create an "allow anything" field on a node? We're building a site and need to allow our users to have a field on the node that will allow for ANY content: scripts, iframes, script files, css files, etc; essentially embed codes for mailchimp forms, donation forms, etc.

This HAS to be something the user can do so. Can I create a textarea field and then override a hook or something to prevent that fields contents from going through any sort of filtering?

I also completely understand the risks here. We don't have any public users logging into the site. We know everyone who is logging in.

I would create a new text format for that:

Go to admin/config/content/formats/add
Select the filters you want to add (in your case probably no filters at all)
Add a textarea field on your content type and select this text format you just created.


How to cancel user accounts without e-mail confirmation? I want to allow users to cancel their accounts immediately instead of having to confirm the cancellation by email (because users forget passwords, lose access to email, and other problems).

There is a great answer to the Drupal 7 version of this question and it inspired a module.

So I attempted to adopt the code in the module for Drupal 8.

First, though, you need to prevent the "account cancellation confirmation email from being sent; otherwise, users will receive an email to click a link when they don't need to.

You can do this as follows:

drush cex
Edit user.settings.yml
Change cancel_confirm to false
drush cim

Here is my code with a problem:

function MYMODULE_form_user_cancel_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'mymodule_user_cancel_form_submit';
}

function MYMODULE_user_cancel_form_submit(&$form, &$form_state) {
  $uid = $form['uid']['#value'];
  $user = \Drupal::currentUser();
  if (!$user->hasPermission('administer users') && $uid == $user->id()) {
    // Hide "A confirmation request to cancel your account has been sent to your email address."
    $messages = drupal_get_messages('status', FALSE);
    if (!empty($messages['status'])) {
      unset($_SESSION['messages']['status']);
    }

    // Cancel the account, from user_cancel_confirm()
    user_cancel($form_state->getValues(), $uid, $form_state->getValue('user_cancel_method'));

    // Since user_cancel() is not invoked via Form API, batch processing needs
    // to be invoked manually and will redirect to the front page after
    // completion.
    batch_process('');

  }
}

The main problem is that after calling the submit callback, I get the message "The update has been performed.", but the user account is not cancelled.

I used kint() to debug and the submit callback is evaluated and user_cancel is called, but the account is not actually blocked.  Users do have permission to cancel their own accounts.

Please use this code snippet it works for me

 function simple_pass_reset_form_user_cancel_form_alter(&$form, &$form_state, $form_id) {
  //  dsm($form);
  $form['actions']['submit']['#submit'][] = 'simple_pass_reset_user_cancel_form_submit';
}

function simple_pass_reset_user_cancel_form_submit(&$form, &$form_state) {
  $uid = $form['uid']['#value'];
  // exit;
  $user = \Drupal::currentUser();
  if (!$user->hasPermission('administer users') && $uid == $user->id()) {
    // Hide "A confirmation request to cancel your account has been sent to your email address."
    $messages = drupal_get_messages('status', FALSE);
    if (!empty($messages['status'])) {
      unset($_SESSION['messages']['status']);
    }

    // Cancel the account, from user_cancel_confirm()
    user_cancel($form_state->getValues(), $uid, $form_state->getValue('user_cancel_method'));

    // Since user_cancel() is not invoked via Form API, batch processing needs
    // to be invoked manually and will redirect to the front page after
    // completion.
//You need to run batch process
    $batch = &batch_get();
    $batch['progressive'] = FALSE;
    batch_process('');
  }
}


Do tokens work with Rules "Set a data value"? I have a simple Rule created in which the action is that a particular entity is created (a node) and then another action is called to "Set a data value" of one of this node's field (a standard text field). In the Rules action I setup the tokens that I want to be put as data into this field. For some reason the tokens are not showing up properly when the entity is created:

I have tried a few different combinations but as you can see above the token I am using (node:author:link) does not display properly when the node is created. What is the reason for this? I have experimented with all of the different input filters but it does not seem to work for any of them.

I have found the answer to my own question and thought I'd share. The solution is to use Token Filter module. Once you have installed this module got to: Admin > Config > Content Authoring > Text Formats. Create a new Text Format or edit an existing one and you will see an option called "Replace Tokens", check this and save your format. Now when your are using "Set Data Value" make sure that the text field has the input format that you just created/changed.

You should now be able to pass tokens successfully using Rules Set Data Value and they will format correctly.


How do I log in if I can not get the login prompt page to come up as it should? I am having some issues with my Drupal 7.

Because of a different bug I am having with component or panel, one that is taking over pages and hiding other parts of a page somehow, my login page has been corrupted.

what is supposed to be my /user and/or user/login page looks completely as it should not look. The username and password prompt and input fields are missing because of a component which needs to be removed. This component has somehow managed to cover or hide the thing I need.

The bug that has caused this problem is beyond the scope of this post but I believe that it is probably a requirement to log into the admin panel in order to fix the issue.

How do I log in if I can not get the login prompt page to come up as it should?

Drush

  To get one-time login for the specific user, use this syntax:

drush uli <user>

  Where <user> is either uid (e.g. 1), user name, or email address
  for the user.

  Custom code

  You can use user_pass_reset_url() function in your
  custom code.

  Generates a unique URL for a user to login and reset their password.

  Ex:

$uid = 1;
$account = user_load($uid);
$link = user_pass_reset_url($account);

Source: Kenorb's answer to How to get one time login for all the users?


simple external variables to hooks Using drupal 7, Views 3, I have a function (present on Leaflet Module) which takes only 2 parameters. I use this hook function to print resulting points from view in different colors
//Allow modules to alter the points data while rendering a leaflet views row.
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points)
{
  if (isset($result->number))
 {
  // Add number value to every points data entry, if present.
    array_walk($points, function(&$point, $key, $number) {
     $point['number'] = $number;
   }, $result->number);
 }
}

I am trying to use this hook to take variables from outside the function.
For example:
$data='heeeello';

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points)
 {
  echo $data;
 }

Just returns NULL. Tried setting it up as Global (which should already be, but just in case), also variable_set($data,'hello')... no success.
Executing the function passing the params works neither:
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points,$param)
{
  echo $param;
}

thanks in advance
EDIT
I want to populate an external array based on the data processed by my hook (see below MY_MODULE_leaflet_views_alter_points_data_alter)
This final array has to contain unique values. On standard PHP I would access the external array and populate recursively it but I have problems accessing this array via my hook.
Using global doesn't work, but it works using variable_set and variable_get, but it means that each time the hook access the variable (variable_get(param)), the array starts empty again.
$array = array();

variable_set('my_array', $array);

//testing global, doesnt work
$test=array();

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {

    global $test;
    var_dump($test); //NULL

    $my_array= variable_get('my_array');
    //I will get allways an empty array... even if its later correctly populated

    //fetching results from the hook
    $name=$result->name;

    if (!in_array($name,$my_array))
      {
        array_push($my_array,$name);
      }

    //plots just a value (array is not recursively populated, as allways start empty inside the hook)
    var_dump($my_array);
 }

This is a php issue.

$data = 'heeeello';

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  echo $data; // $data is NULL, will also throw a notice
}

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  global $data;
  echo $data; // $data is 'heeeello'
}

regarding your variable_set, the params are different:

$data = 'heeeello';
variable_set('hello', $data);
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  $data = variable_get('hello');
  echo $data; // $data is 'heeeello'
}

RE edit: this goes towards your extension:
variable_set() is not designed to do sets on every request, variables should be quiet consistent, every variable_set will clear your cache (to some extend), abusing this will lead to a lot of performance problems.

If you need a cache use cache_set and cache_get, for singletons/ static stuff use drupal_static. The global variable $test you are using right now in your question, should not return NULL but array(), everything else looks like a different problem.

If you want to build up a storage backend create proper tables using hook_schema or (advanced) build your own entities.

edit: almost forgot, your code from above, is not working because you are not saving that variable again, so even for the second run it will always be empty.


How to search through database of businesses/how to build the content template? sorry in advance for the more than likely simple/beginner/waste of time question(s). Anyway, I'm working on building a business ratings site of sorts (Yes, I know, way overdone. Don't worry about it! :D). However, since I know very little programming and am completely new to Drupal (7), I don't quite know the best way to go about building the basic nodes, how to add an itemized search function to the site, or how to get the listings to show up in said search. I've done as many searches as I can think of, but I think the problem is that I don't know what I don't know, and therefore am searching the wrong things.

I guess for me those are all different ways of asking a similar question. How do I build the template node for the business page so that it can be searched for and sorted based on its characteristics. For instance, when creating the basic content type template, how would I build it so that the listing can be searched, for instance, by state?

I need to display the address of the business on its page simply because of the nature of the site. So, is there a way for a search to pick up on that, and display it in a search sorted by the state that it's in? Do I need to somehow link that field to a taxonomy term of some sort? Also, what module would be the best to use for adding that type of search to the site?

I'm not sure whether this is helpful, but the modules that I have installed so far in my journey toward building this site/solving this problem are: Views, CTools, Display Suite, and Custom Search. I'm guessing that I will be able to use custom search for the actual search function, but I haven't delved into using it yet since I haven't figured out how to build what it searches.

Sorry for what I'm sure is a silly post, and thank you in advance for any help anybody may have to offer.

The two major approaches to adding locations in Drupal 7 are location/gmap and addressfield/geocoder.  Comparing these two sets of modules in detail is the subject of a book, Mapping with Drupal, and is outside the scope of this post.  Unfortunately, both approaches are still under heavy development and in all honesty you will likely encounter a fair number of bugs either way.  At the moment, I would choose the Location approach because it has working proximity search (show me all businesses within 100 km of me).

If I were approaching this project, rather than using the built-in Drupal search, I would use the Views modules and filters (exposed filters) to allow users to search.  Once you are proficient with the Views module (Node One has an excellent series of screencasts on learning Views), you will probably find it easier to work with and customize than the basic Drupal search.

A few tips on location-
If you do install the location module it provides a "location directory" view by default, though it is disabled.  You can enable this view and play with it; it creates an index of all your nodes that have locations attached to them.  This should give you some idea about how to build location-based search in Views.

If you do use location, choose Location CCK (which will eventually be named to fields for D7), not the Node Location submodule.  They are mutually exclusive and Location CCK is the direction that the next major release of the Location module will take.


Time Optional using the date_popup type Is there a way to have date/time fields with the date_popup type, but have the time field be something optional for the user to fill in?

I have the UI with both a Date and Time field with the following code:

$form['mygsb_settings']["publish_on_start_date"] = array(
    '#type' => 'date_popup',
    '#title' => "Publish Start Date",
);

But when a user doesn't enter the start time, I get back the following validation error from drupal.

The value input for field Publish Start Date is invalid:
The value 2012-03-14 does not match the expected format.

Is there any way to avoid this validation error? Basically, I want to make the time field optional.

Greg

I needed to allow users to give either a datetime or just a date, so I needed to override the default date_popup behaviour. NOTE: I am not using the date fields provided with the date uri, just the date_popup form element.

You can override the default date_popup validation. The data_popup module applies the validation function during the date_popup_element_process function.

I used a hook_element_info_alter function to append a custom process function AFTER the date_popup_element_process and applied my own validation function. Like so:

function hook_element_info_alter(&$type) {
    $type['date_popup']['#process'][] = 'my_popup_date_process';
}

function my_popup_date_process($element, &$form_state, $form) {
    $element['#element_validate'] = array('my_popup_date_validate');
    return $element;
}

function my_popup_date_validate() {
    if (isset($form_state['values'][$element['#field_name']])) {
        if (trim($form_state['values'][$element['#field_name']][$element['#language']][0]['time']) == '') {
            list($date_format, $time_format) = explode(" ", $element['#date_format']);
            $element['#date_format'] = trim($date_format);
        }
    }
    date_popup_validate($element, $form_state);
}

Removed unneeded code for brevity. Updated validation funciton with an example showing how this could be achieved. This example assumes that there is a space between the data and time formats (ie "d/m/Y H:i:s") and that the date format is first.


How to render a contact form as rendered entity I have a question about rendering a contact form as a rendered entity. I have a field in my contenttype where form should be displayed. The field has the type Contact form.

In the Manage display section in the contenttype where the field is added i got only the possibility to choose Label, Entity ID or Hidden for the format.

On the page itself i got only a link to the page where the form is embedded. I searched about a solution and got something like loading and handling the form with an own module, loading the form in a hook or create a block.

So are those the only possiblities or is there a way to include the form like another entity reference (where i choose Rendered entity as the format).

Use https://www.drupal.org/project/contact_storage.

It provides a view builder for contact forms that displays the form.

It also results in contact messages being stored, among many other optional features. If you do not want that, then you can re-use the code from it for the view builder and add it yourself.


Drupal 7 Views: Use one views.tpl.php file for multiple views Views allows you to customize output with tpl.php files.

My theme directory is getting overloaded with the .tpl.php files! Many of the files repeat the same content.

I would like to use the same tpl.php file for multiple Views. How can I do this?

Ideally, I would like to call a template file when a tag has been applied to a View.

Steps I have Tried

Use Multiple Views displays:
 This thread suggests putting all the Views that use the same template file into one view and then creating separate Views displays for them.

This isn't practical for my situation, as my Views have very different fields, which would result in a lot of overriding (which makes them harder to manage).

Views Pre Process
This article suggests to use a Pre Process function. You can then select specific views and use a theme hook suggestion to load template files. However, the code it provides is incomplete, so it's not clear how to load the template files. It's also not clear how to load different field/row/display/style templates for a single view (as a View template can take one of a field, row, display or style template).

In Views 3 you can add tag “template1” to your views and create template views-view--template1.tpl.php.

Multiple tags supported.


How can get the current region inside the 'hook_preprocess_block'? How can I get the current region name inside the hook_preprocess_block()?
I tried the following code, but it seems something is wrong.

function ThemeName_preprocess_block(&$variables) {
  if ($variables['elements']['#region'] == "nav") {
    $variables['attributes']['class'][] = 'SomeStyle';
  }
}

As described in the documentation for template_preprocess_block(),
$variables['elements']['#block'] is available, and it contains the Block object. With that, you can get the region to which the block is assigned with Block::getRegion().

function ThemeName_preprocess_block(&$variables) {
  if (isset($variables['elements']['#block']) && $variables['elements']['#block']->getRegion() == 'nav') {
    $variables['attributes']['class'][] = 'SomeStyle';
  }
}

That is slightly different from Drupal 7, where hook_preprocess_block() would get the region assigned to the block from $variables['block']->region, or from $variables['elements']['#block']->region. See template_preprocess_block() (Drupal 7).

  $block_counter = &drupal_static(__FUNCTION__, array());
  $variables['block'] = $variables['elements']['#block'];
  // All blocks get an independent counter for each region.
  if (!isset($block_counter[$variables['block']->region])) {
    $block_counter[$variables['block']->region] = 1;
  }


404 error from node access hook I have node_access hook in a module. I tried to prevent anonymous user from access unpublished node like the following:

function MODULE_NAME_node_access($node, $op, $account) {
   global $user;
if ($op == 'view' && $node->status == 0 ){
     return NODE_ACCESS_DENY;
  }
}

This is working fine and redirect to access denied custom page. However, I would like it to be redirect to the custom 404 not found page. i.e the http response to be 404. I tried to find any replacement of NODE_ACCESS_DENY but I could not able to find anything.

I tried to use drupal_not_found() but it generates Server Error on the server.

Also, I would like to know, if there a method or property of the $user object that determine if the user is anonymous user or not. I find that there is user_is_anonymous() but I could not know how to use it in this context.

You can use drupal_goto("custom 404 page") to redirect a user to your custom page. For your second question you can check if user is anonymous using this condition. if($user->uid == 0)

Thus your hook can be rewritten like this.

function MODULE_NAME_node_access($node, $op, $account) {
  global $user;
  if ($op == 'view' && $node->status == 0 && $user->uid == 0){
    drupal_goto("custom_404_page");
   }
}

See here for drupal_goto documentation

Note: This function has been removed in Drupal 8. In Drupal 8 you can do this by this way.

return new RedirectResponse(\Drupal::url('user.page'));

or this way
`use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {
   public function foo() {
   //...
   return $this->redirect('user.page');
  }
}`

See here for Drupal 8 redirect info


How to post the node link in social networking if node is published? I want to post the node link along with its title in social media (Twitter, Facebook, and Google+). Node link should be posted only if the content is published.

I have used the HybridAuth and Facebook OAuth (FBOAuth) module for Twitter, Google+, and Facebook login.

How can I achieve this?

For Facebook and Twitter you should be able to get this to work using the Rules module, though for Google+ this sounds like a business opportunity (read: no known solution as of today). Read on for more details about each of them ...

Facebook

The Facebook Rules module can be used to post to user's wall, via the Rules module. Some more details about Facebook Rules (from its project page):

  Facebook rules module extends FBOauth permissions and integrates with Rules module.

  Once the user's Drupal Account is connected to his/her FaceBook Account, FaceBook Rules can be used to set up actions based on particular events or triggers.

  It provides following rules:

  Events:

  User logged in using Facebook connect.
  User connected existing own account to Facebook.
  User registered using Facebook connect.
  User registered using Facebook connect, requires admin approval.

  Condition: User's Drupal account is connected to Facebook account.
  Action: Post to user's wall.

Twitter

After you enable the Twitter module, and its sub-module Twitter Actions, you can use the Rules module to create an action that will post a tweet to a specific Twitter account.

Have a look at Post Automated Tweets Using Rules and Twitter Actions for more details about it.

Google+

For Google+ I'm not aware of any working solution. Yes there is the Google+ module (which only has a dev version for D7 ...). And yes Google+ does have an API, but this module doesn't implement it.

Therefor I think the best you can find (to start from) is what is described in How to post in google plus wall?. Starting from there, you may get that to work also if you'd write your own (custom) Rules (Event(s), Condition(s) or Action(s)), similar to what is described in the answer to the question about "How to login-redirect users to their profile page on specific days only?".

PS: Using the Rules module to make something happen when something gets "published" should be a no-brainer (that's like Rules lesson 101, which I assume does not need any more explanation).


Using existing term reference field vs. creating new ones I have 3 content types (blogs, photos, videos) that all reference the same "topic" vocabulary.

When I add the term reference field to each content type I can either create a new field "field_blog_topic", "field_photo_topic" and "field_video_topic" for each of the types.

Or I could create a "field_topic" field for blogs and then use that existing field for the photo and video content types.

Would it make any practical difference?

Yes it would make sense to have only one field that you attach to multiple content types.

If you're using a MySQL backend then a table is created for every field you create in the UI (it's probably similar for other storage backends). If you create a single field and attach it to several different entity/bundle types then only a single table is created with the values for all entities. Fewer tables is definitely more desirable.

Also if you wanted to query the database for all nodes that are within a certain vocabulary (using EntityFieldQuery or even Views) then the query generated would have two less JOINs to make which is just much better for performance on the whole.

I think it was the intention of the developers that fields be used in this way, there's a complicated mechanism in place for managing different instances of fields and I don't think that logic would need to exist if they weren't supposed to be used like this.


Change format view data export module I want change format display View Data Export from table to unformatted list

First you need to create a view page
Display & filter those information which you want to export
Click on +Add & select Data Export
Under format you get an option to change to unformatted list
Save & check

For detailed description click on the LINK.


Display Months in dropdown for filtering I want to create a view over a content type. Over this page I want a select list of Months to filter the content by month.

Is there any module or how can I achieve this by view?

Using the Date project, you can add a "Date: Date (node)" (D7, not sure how it is called in D6) filter, where you can choose the granularity. By setting it to month, it will display a list of months in the filter.

I looks like a "All month" option is however currently missing, so you can't display all months by default, it seems. See http://drupal.org/node/574820.


Group by taxonomy term, show node multiple times for every reference I have a Content-Type called client and a Taxonomy term called Service. Inside the view I am showing content of type: node and grouping the nodes by the taxonomy reference field. Right now it is shown like this.

**Term Name1**
 node1
 node2

**Term Name2**
 node3
 node4

The problem is the term reference field is allowing multiple and I want to show the node referenced by more than one Term, under each term instead of views creating a new term grouping.

So say I reference node3 with Term Name2 as well as Term Name1 I get the following results:

**Term Name1**
 node1
 node2

**Term Name2**
 node4

**Term Name1, Term Name2**
 node3

How can I avoid this functionality and have the view show this instead?

**Term Name1**
 node1
 node2
 node3

**Term Name2**
 node3
 node4

In the taxonomy term's settings, you need to uncheck the option for displaying the values in the same row.


Drupal 7 login form redirect back to page which they logged in on $node->content['my_form'] = drupal_get_form('user_login');

I am creating a form that as outputted on http://site.com/datacollection/the-data-collection

When the user successfully logs in they are redirected to users/USERNAME

In drupal 6, the user would be redirected to the same page they logged in from...How can I reproduce this behavior?

Create a action (admin/config/system/actions)

You have to use the token module and find the right token for the needed path. (Maybe someone else can point the right token for this behavior.)

Create a trigger (admin/structure/trigger/user)

AFTER A USER HAS LOGGED IN -> redirect to the path


How do I add a file upload field to user profile? I need to add a file upload field to user profile, and show it on profile page (not during registration). How can I do this?

Use Content Profile.

By default Content Profile puts the additional fields in a tab on the profile page. If you want them to be all in one page use Account Profile


Removing second copy of ctools module from filesystem I have a site where two version of ctools are on the filesystem.

The first version is in sites/all/modules - this is correct and where I want it
The second version is in sites/all/modules/contrib - this isn't correct and was placed there by custom formatters make file.

The registered path in the system table is sites/all/modules/contrib. I want to remove the contrib folder as it shouldn't exist and is causing issues when I want to upgrade ctools using make files.

Removing the folder gives an undeclared function error as drupal expects it in that contrib folder. Using drush registry rebuild isn't an option as the error still appears because ctools is embedded so deep.

Changing the paths in the system table still brings up the undeclared function error, this could be caused by APC caching though.

Is there a simple way of removing references to this folder and using the copy of the module in sites/all/modules without causing such a huge impact?

Unless you have apc.stat = 0, then APC caching is likely not the problem.  You can always set apc.enabled = 0 as a temporary measure until you get the problem fixed.

What version of Drupal?

If you are on Drupal 7, you could try deleting the extra copy and then running Registry Rebuild via drush.  Follow the instructions on the project page.

The other method that should work for Drupal 6 and 7 would be to take a database backup, and then hand edit the {system} table.  If it has both "sites/all/modules/coots" and  "sites/all/modules/contrib/coots" in it, delete out the contrib entries.  If it just has the "sites/all/modules/coots" entries, edit them to take out contrib.  Then manually clear out all of the cache tables.

Make sure you backup your database no matter what you do.  Both of these are dangerous operations.


how do I get the depth of a MenuLinkContent? I'm using the sitemap module and i need to get the menu link depth in my preprocess function (template_sitemap_menu_link). I'm trying to do that by accessing the MenuLinkContent object with

    $menu_link_obj = $variables['element']['#original_link'];

There is a getParent() method I can access to check if this is a level zero item, but no way to check for depth. I could always loop trough getParent() until I get NULL and count the number of iterations, but that seems like a bad practise to me. Is there an alternative?

Here is our approach:

$menu_link = $variables['element']['#original_link'];

$depth = 0;
$parent = $menu_link->getParent();
if ($parent) {
  while ($parent) {
    $parent_parts = explode(':', $parent);

    $parent_entity = \Drupal::service('entity.repository')->loadEntityByUuid($parent_parts[0], $parent_parts[1]);
    $parent = $parent_entity->get('parent')->get(0)->value;
    $depth ++;
  }
}

Hope to help


How to find out which form I want to alter I am adding a functionality to drupal commerce kickstart, which involves product display modification. There should be a lot of forms but I don't which one to alter and add my new object to the existed form. Any good idea? (There is almost no documentation about it)

The way I usually do it is just implement hook_form_alter and inside put dpm($form_id);. Reload the page and it will echo all form ID's. You should find the one you want pretty easily, you can then change the hook_form_alter into a hook_form_FORM_ID_alter.


Concatenating user submission fields or components in webform Drupal 7 using Drupal 7 webform module. The module is set to email out results. The problem is that the form submissions are going via email into Zendesk, which ideally would be able to parse out first/last name from the sender.

The problem is that the email from name is set to use the component first name from the form.

The help text below the selector says "Any textfield, select, or hidden form element may be selected as the sender's name for e-mails." Is there a way to concatenate the first and last name fields from the form into the from name field?

the form was previously set (before I started working on it) with 'Value of First Name'  in the "cusstom" from field. That wasn't working. Would [submission: first_name] [submission: last_name] or a similar token work?

If you'd be willing to also use the Rules module for actually sending such eMails (together with Webform Rules), you'd have all sorts of flexibility about how you want those eMails to look like.

As an example, consider this custom rule for sending an eMail (in Rules export format):

{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I intentionally did not include any Rules Conditions here, just to illustrate that by using such basic rule, you do have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail]. In other words, you don't need a Rules Action like "fetch entity by ID" for these kinds of tokens to be available.

But wait, there is more ... You can also include any of the "Webform data" in such eMails. To do so, you could use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
In your subsequent Rules Actions (e.g. in which you create an eMail) you can refer to the value of these variables you just added (that's the clue!).


How to create simple confirmation page? I want to create simple confirmation page. It means that after user change his email then he gets confirmation email with link to page. This link contains token. This link should open page for user with appropriate message (success or fail if token expired). I want to create simple module, But I don't know which hook I should use to create this simple page. I must check this token by sending POST request to REST API before rendering page.

Any advice?

I suggest you use hook_user_update. Then you compare $account->mail and $account->original->mail. If the two email addresses are different, the user's email address changed. Next you generate the token and send an email to the user with a link to your page.

For the page, create a new menu entry via hook_menu and do the logic for the REST call there. You can get URL query parameters (especially the token) by using drupal_get_query_parameters. Maybe you should ensure that the token is unique and store it with the email address and the creation time (to check if it has expired) in the database.

The documentation for hook_menu (or 99% of all other modules available) should give you an example on how to use it.


How do I recreate the accesslog? In Drupal 7, every time a node is viewed the following columns are populated in the {accesslog} table:

aid: unique accesslog ID
sid: browser session ID of user that visited page
title: title of page visited
path: internal path to page visited (relative to Drupal root)
url: referrer URI
hostname: hostname of user that visited the page
uid: user users.uid that visited the page
timer: time in milliseconds that the page took to load
timestamp: timestamp of when the page was visited

In Drupal 8, the accesslog was removed from the statistics module. I would like to recreate some this functionality in a Drupal 8 custom module. I need:
- A hook to fire on every node view
- Capture the relevant information
- Write it to a database table

My plan was to copy from statistics module, because it still counts node views. However, the code is not straight forward. In Drupal 8 the mechanism appears to be:

Implement hook_ENTITY_TYPE_view(), which attaches some JavaScript and settings to the page build

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function statistics_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if (!$node->isNew() && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
    $build['#attached']['library'][] = 'statistics/drupal.statistics';
    $settings = array('data' => array('nid' => $node->id()), 'url' => Url::fromUri('base:' . drupal_get_path('module', 'statistics') . '/statistics.php')->toString());
    $build['#attached']['drupalSettings']['statistics'] = $settings;
  }
}

Implement the following code in statistics.js

/**
 * @file
 * Statistics functionality.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  $(document).ready(function () {
    $.ajax({
      type: 'POST',
      cache: false,
      url: drupalSettings.statistics.url,
      data: drupalSettings.statistics.data
    });
  });
})(jQuery, Drupal, drupalSettings);

Implement statistics.php, which where information gets written to the database

/**
 * @file
 * Handles counts of node views via AJAX with minimal bootstrap.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

chdir('../../..');
$autoloader = require_once 'autoload.php';
$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel->boot();
$views = $kernel->getContainer()
  ->get('config.factory')
  ->get('statistics.settings')
  ->get('count_content_views');

if ($views) {
  $nid = filter_input(INPUT_POST, 'nid', FILTER_VALIDATE_INT);
  if ($nid) {
    \Drupal::database()->merge('node_counter')
      ->key('nid', $nid)
      ->fields(array(
        'daycount' => 1,
        'totalcount' => 1,
        'timestamp' => REQUEST_TIME,
      ))
      ->expression('daycount', 'daycount + 1')
      ->expression('totalcount', 'totalcount + 1')
      ->execute();
  }
}

Can anyone explain this code?

There is no official way to do your own thing in statistics.php, it is on purpose kept as light as possible.

But of course, you can duplicate its functionality and do whatever you want. The whole trick is adding a JS file that sends an uncached POST request to the server. That's the only reliable way to get access statistics for anonymous users, as those requests might be cached by the page cache or an external CDN/Varnish.

Given that you already posted all the relevant code, I'm not sure what you are asking exactly. You even linked to the d.o issue that removed that feature, which links to the change record (https://www.drupal.org/node/1900384), which in turn links to the contrib module that provides similar functionality: https://www.drupal.org/project/better_statistics. So instead of doing it yourself, you could build upon that.


Discovering cookie session data Can anyone advice me on how I can discover the active cookie details for a user logged into a Drupal website?

All cookie data is in the PHP superglobal $_COOKIE.  However a typical Drupal site only stores the a random session identifier in the cookie, so it may not be what you're looking for.  If $_COOKIE doesn't answer your question please post more details about what you're trying to accomplish.


Slow page loads - unable to determine the cause I am experiencing ~ 6 second page loads on every page of my Drupal 7 site. All of my scripts are loading from cache and relatively quickly except one, which will take 5.6-5.9 seconds to load (I am using FireBug to monitor):

Originally it looked to be the overlay.js javascript file, so I disabled the module. Then it was contextual.js with the exact same load time with everything else being quick. When I disabled that module it was yet another js library taking the same amount of time. This leads me to believe it has nothing to do with the libraries and is some other issue with the pages / rendering. I tried aggregating the JS and CSS, but the same issue was happening. All the queries showing up in my MySQL logs are executing relatively quickly (total of all query execution time is less than .5 seconds).

I am honestly at a loss for what to try. I suspect there is some problem here unrelated to loading any of the js files and that firebug is just reporting the delay as part of the last loaded file. This happens on both my custom pages and core drupal pages (like the modules and people screens). Is there any way to tell what is causing the long delay if it is not the javascript library?

EDIT: Details from the header for the script:

Request Headersview source
Accept  */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  Drupal.toolbar.collapsed=0; __utma=163199651.1343774579.1355785168.1378243005.1379453429.30; __utmz=163199651.1378243005.29.5.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); _ga=GA1.2.360149903.1357234390; SESSb5e5274d127f94079db0dc72d78d2200=AnQQv9Tp-NQT-b3YcVfOKzEnVSL-3cBexxbp2jY70D0; has_js=1
DNT 1
Host    example.com
If-Modified-Since   Wed, 03 Apr 2013 21:29:52 GMT
If-None-Match   "bcc-4d97b8dea7400"
Referer http://example.com/drupal/?q=peopleace/form/14172
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0

Response Headers From Cache
Accept-Ranges   bytes
Content-Length  3020
Content-Type    application/javascript
Date    Wed, 02 Oct 2013 19:26:36 GMT
Etag    "bcc-4d97b8dea7400"
Last-Modified   Wed, 03 Apr 2013 21:29:52 GMT
Server  Apache

If a 304 is taking 5+ seconds that means you webserver (most likely Apache) is being very slow. The ONLY other thing that could be causing this is if you have Far-Future enabled with the CDN module (and that's a stretch). Aggregating should help, as this will reduce the # of requests hitting Apache.

What web server are you using? Also noticed that Clean-URLs is disabled so I would bet that the webserver needs to be configured.


Searching for a pptx and pdf viewer I'm using Embedded Google Docs Viewer but it's not what I need exactly.
I searched for a while but I could not find my answer.
I need a module that displays the .pdf or .ppt file like in this image.

Can anybody suggest me a module?

You can convert your PDF to a series of images and show them as slideshow, using the PDF To ImageField module.

  The PDF To ImageField module provides automatic conversion of uploaded PDF files to images.
  It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.

  The module is implemented as CCK widget for FileField where PDFs are uploaded to. It places generated images into a CCK ImageField on the same content type.


Add sufix to field in views I have a view displaying webform fields (results).

In some questions, the user answered for example 15€, but I added the sufix "€" to the webform so the user won't have to write it. So the answer is just "15".

I want to add the same sufix "€" to the view field so it appears "15€". How can I do this?

You can rewrite the output of any field in a view by using "Rewrite results" and clicking on "Rewrite the output of this field" (see screenshot below). You can use a replacement pattern for the actual content of your field and then add the "€" symbol.


convert webform date to oracle format I need to ask some help in converting the date format of a webform.

I'm writing a custom module that send the submissions of my webforms to a third party, however I have to convert my date format from "m/d/Y - H:i a" to the oracle format "DD-MON-YYYY"

I've read up on articles saying that webform uses the site's "short form" but Ideally I'd like to make the conversion in my mod, to keep it contained and because I don't know if changing the "short form" will break anything currently on the site.

This is the line capturing the date field of my form:

 $dob = $submission->data[11]['value'][0];

I'm using Drupal 6.19 and webforms 6.x-3.4
if anyone can give me some suggestions I'd appreciate it.
Please let me know if I need to provide more detail.

Thanks!
Steph

This is more of a PHP question, I believe, as you use PHP functions to accomplish this.

<?php
  $dob = $submission->data[11]['value'][0];
  $time = strtotime($dob);
  $oracle_format = date('d-m-Y', $time);
  // OR
  // $oracle_format = date('d-m-Y', strtotime($dob));
?>

This uses the functions date() and strtotime()


What hook is triggered when adding / updating and deleting taxonomy? I need to update some value in database when a taxonomy
term is added or updated or removed. What is the proper hook
to use here ?

Take a look at the taxonomy.api.

Looks like you're gonna want to take a special look at hook_taxonomy_term_insert, hook_taxonomy_term_update, and hook_taxonomy_term_delete.


How to add a custom field to a taxonomy term I am developing a module and I would like to know how to add a field to a taxonomy term?

My section is named special and I want to add terms in this section

I have this code:

function add($form,&$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('name'),
        '#required' => TRUE,
    );

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

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

    return $form;
}

function special_add_submit ($form, &$form_state) {
    $instance = array(
        'field_name' => 'nombre',
        'entity_type' => 'taxonomy_term',
        // This is the vocabulary
        'bundle' => 'special',
        'label' => t('Relates to option'),
        'description' => t('This is the description'),
        'required' => true,
        'widget' => array(
        'type' => 'text_textfield',
        'settings'=> array(
            'max_width'=>80)
        ),
        );
    field_create_instance($instance);
}

How to do that?

i create a field named name when i save that field i want to add the value to taxonomy term named special

$term = Term::create([
  'name' => 'fashion',
  'vid' => 'special',
])->save();

'fashion' is the new taxonomy item name and 'special' is the existing vocabulary machine name.
The fashion will the taxonomy term under the vocabulary special


SelectQuery::fields and Drupal's naming conventions - how to make it all match? Convention for database column names is underscore_notation. Convention for class properties is camelCaseNotation. But when I'm using SelectQuery::fields('t') and then fetchObject(), fetched object's properties are in underscore_notation.

I know I can use code like:

foreach($fields as $field)
    $query->addField($table_name, $field, to_camel_case($field));

That's a solution when I know fields I'm supposed to get. What if I don't? If all I want is good old SELECT * FROM {table}? Is there a simple way to fetch object compatible with Drupal's naming convention?

I know that formally, as written, convention does not apply to objects generated dynamically and returned from PDO. I want to avoid mixed namings none the less. It feels wrong to make user input $object->camelCase and give him $output->underscored_answer back. Bad as in causing errors and confusion.

What the naming conventions actually say is that "Methods and class properties should use lowerCamel naming." (my emphasis).

The properties added to the object returned by a query are not class properties. This is confirmed by the PHP documentation which defines "properties" (or "class member variables") as "defined by using one of the keywords public, protected, or private, followed by a normal variable declaration". There is no such declaration that applies here.

The object you are looking at is of type StdClass. There isn't much about the concept behind StdClass in the PHP documentation (unless I missed it), but the concept of a class-less object with dynamic fields is sometimes known as "anonymous object". You can create one in PHP by doing:

$obj = (object)(array('field' => 'value'));
echo $obj->field; // Outputs 'value'

In the case of the object returned by the query, it doesn't even have methods - it could just be an array (which it would be if you fetched your data using DatabaseStatementInterface::fetchAssoc). So we can think of anonymous objects as containers, rather than instantiations of classes to which the coding style should apply.

Since this object is a container of fields from the database, I think it makes sense for the database convention to apply. It is an object wrapper around a database row.

As a Drupal programmer, if I get a result that is essentially a database row, I will actually expect it to be in underscore notation. While it may feel wrong, it is what people are used to expect. Every time I use [node_load][4], the result I get is an object in underscore notation. Even when you use the entity meta data wrappers, which essentially are there to provide an object interface around Drupal entities, you still use the underscore notation. Changing this approach would potentially confuse other Drupal programmers.

I understand that if you are writing, say, an API which returns your own data, you may want to abstract the fact the result is a database row and present it as an object like any other (as suggested by your param vs. result example). One option, though one that has some overheads, would be to create a class to hold such result, and casting the database result object to it. This would at least make it clear that what you are returning is a proper object, not just a container around a database row. You could do something like this:

Class MyApiResult {
  function __construct($row) {
    $vars = get_object_vars($row);
    foreach ($vars as $name => $value) {
      $cc_name = to_camel_case($field);
      $this->{$cc_name} = $value;
    }
  }
}

Then your API would return:

return new MyApiResult($row);

However this has some overheads, it depends whether those will be acceptable in your particular case.


jQuery integration problem I have an problem to get my jQuery code working with D7. In HTML it works fine but with D7 it doesn't work at all...

the code:

(function ($) {

Drupal.behaviors.exampleModule = {
attach: function(context, settings) {

    var thumbstart = $("ul li img");

    for (var i = 0, ii = thumbstart.length; i < ii; i++){
        if (thumbstart[i].title && thumbstart[i].title.length > 0)
        {
            var imgtitle = thumbstart[i].title;
            $(thumbstart[i]).wrap('
').
            after('
' + imgtitle + '
').
            removeAttr('title');

        }
    };
// At here the code works fine...
$('.wrapper').find('img').css({opacity: ".8"});
$('.teaser').find('.caption').css({top:"107px"});
$('.test2').find('.caption').css({top:"165px"});

$('.teaser').hover(
    function(){
        $(this).find('img').animate({opacity: "1.0"}, 300);
        $(this).find('.caption').animate({top:"160px"}, 300);
    },
    function(){
        $(this).find('img').animate({opacity: ".8"}, 300);
        $(this).find('.caption').animate({top:"107px"}, 300);
    }
    );

}
};

})(jQuery);

the problem is that the top of part is not working (begins at: var thumbstart...) is there anything that I can do? Does D7 need extra library/modules?

Far from needing extra libraries, Drupal needs less libraries then you're giving it.

Drupal 7 ships with jQuery 1.4, and can be updated to 1.5.2 with the jQuery Update module. Updating to v1.7 is not really feasible at the moment (see How do I update jQuery to the latest version I can download?, and search the site for 'latest jquery' for more information on that).

Even if the core/contrib Drupal JS worked well with v1.7, you can't just add it to the page and expect it to work, it will conflict with the core jQuery libraries added by Drupal (see jQuery.noConflict() for background).

That said, I can't see anything in your code that would necessitate using jQuery 1.7, so just remove the erroneous line from your .info file, clear the caches, and move on :)

To address the problems with your code now that the correct jQuery files are being included:

Your JS looks like this:

if (thumbstart[i].title && thumbstart[i].title.length > 0)

So the wrapper won't be added unless the  has a title. If you look at the source code of http://icon-guideline.fanlobby.net/ you'll see that the markup is as such:

As you can see, there's no title on any of the images, so your JS condition will never resolve to true, and the wrapper will never be added.


Translate admin settings I am writing a module configuration page for a module. Is there a way to make variables submitted and saved by system_settings_form translatable?

I think there are two issues you have to think about...

Is the item you are saving in the variable used for calculations?
Is the item you are saving going to be displayed?

Note there is actually a variable translation module located in Localization Module, but it seems you would need to ask for these for each language supported.

In the case of #1, code may be require this variable to be a specific value. This will make it to whether you need to keep a record of all the available translated values of this item that can be entered and compared against.

In the case of #2, you could simply wrap a t() around the variable setting it up for translation, but if it is something like a text field, this will have to be done after one figures out what the item is... Select fields and others would be no problem as you have a finite number of possibilities.

With all that said, if the item is a free-formed text field, I would just allow your user to type in a different value for this item for each language he has enabled using the Variable Localization module.


How do I change certain page titles? How do I change certain page titles in Drupal, most notably the create new account, log in, and request new password tab headings?

you can create a module. inside the module you can use the function form_alter to modify the form, and specifically use the function drupal_set_title() to add the title, for example:

create a module with the name "change_title".
add a form_alter function (note that the name of the module is added to the _form_alter name function)

function change_title_form_alter(&$form, &$form_state, $form_id) {

 //dsm($form_id) this function is to know the $form_id

   if ($form_id == 'content_type_node_form') {
       drupal_set_title('this is my new title');
   }

}

note: about how to get the $form_id value, you can use Devel module to use the function dsm($form_id), then the return of this function will show you the $form_id value.


Edit php code on a webform I need to set an auto response message on a Webform 7.x-3.19. I understand that I need to add a script which is going to do the job. My question is which php file should I edit to do so?

I don't have the exact answer to your question but I can give you some advices to how you can do.

First option, UI way, You can try the "Rules" Module with "Webform Rules" Module.
It gives you the ability to do some operations on given context.
I don't know that module, but it seems to be the easiest solution.

Second option, Dev way, you can manually hook your webform and add php code.
You have to implement the "hook_form_FORM_ID_alter" hook
You can retrieve webform form_id by following this answer of this post.
In your hook implementation, add your custom submit function like the following snippet :

function YOUR_MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    if(isset($form['#submit'])){
        $form['#submit'][] = 'your_custom_function';
    }
    else{
        $form['#submit'] = array('your_custom_function');
    }
}

Some usefull links :

Drupal : Form API
Drupal : hook_form_FORM_ID_alter
Module : Webform Rules
Module : Rules


How to decide between 'Hook_preprocessor' or using twig template? We all know that for a customs web designing issue there are many solutions and various methods and ways,
but this question has always existed, i.e about what the advantages/disadvantages (pros/cons) of each of them are.

For example, by using hook_preprocess in the theme file we can add our desired styles to custom blocks or regions,
and reduce our needs to keeping multiple twig templates compared to times we use twig template to add our styles.

I want to be able to use those criteria (pros/cons) to decide which one is recommended in specific situations by considering indicators such as:

Stability
Efficiency and Loading speed
Maintenance

It's not really an either/or thing. They are used together - preprocess functions are run before a template is used. Templates should only have very simple logic, if/else, and loops for the most part. Any logic more complex than this should go into a preprocess function. If you want to do things like adding classes to the attributes of a variable, this should generally be done in the preprocess function, though if you have a class that will only go in a single template, then it can be done in the template itself.


How to resize images in a slideshow for a Responsive Theme? I am using a responsive theme in which I have a slideshow on the homepage of the slide. I am creating the Slideshow as a Block using Views.

Question: How do I make the slideshow (i.e. the images) re-sizable as the screen size is changed?

You can use Flex Slider either alone, or in combination with FlexSlider Views Slideshow (which provides integration with Views Slideshow in case you already use that one).

Flex Slider module integrates the Flex Slider library with Drupal and allows you to build responsive and resizable slideshows. You'll find plenty of documentation on the project page to fit it to your needs.


get variable indicating node preview mode (D7)? I would like to display a specific message to users when they are previewing a node they are submitting. So I thought I would use a block with PHP code, using some info indicating that the node is being previewed.
Unfortunately, I cannot get it working. I have tried these conditions:

if ($variables['view_mode'] == 'preview') ...

I get this error:

  Notice : Undefined variable: variables in eval() (line 4 in
  /.../modules/php/php.module(80) : eval()'d code).

Tried this too:
if ($node->in_preview == TRUE) ...

I get these errors:

  Notice : Undefined variable: node in eval() (line 5 in /.../php.module(80) : eval()'d code).
  Notice : Trying to get property of non-object in eval() (line 5 in /.../php.module(80) : eval()'d code).

I guess I have to declare the variable before, but how? I thought that since the
node form is rendered anyway, the needed variable was available?

The variable that inside node.tpl.php says the view mode currently used for the node is $view_mode, but that variable is not used when Drupal is displaying a preview of the node. To know that, you can:

Check the value of $node->in_preview; when that value is TRUE, Drupal is displaying the preview of a node.
Check that $classes contains the string 'node-preview', such as with the following code.

if (strpos($classes, 'node-preview') !== FALSE) {
  // Drupal is showing a preview of the node.
}

Drupal already shows a message when the user is watching the preview of a node, anyway.

  The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.