Drupal 7 views 3 add custom filter handler for an existing field How can you implement custom filter handler for an existing field in Views 3? With hook_views_data() you can expose a new table to views but how can you alter the handler for an existing field?

To add a Drupal 7 views custom filter handler for an existing field, you should implement the following hooks.

//in yourmodule.module
/**
 * Implements hook_views_api().
 */
function yourmodule_views_api() {
  return array(
    'api' => 3,
  );
}

// in yourmodule.views.inc
/**
 * Implements hook_field_views_data_alter().
 */
function yourmodule_field_views_data_alter(&$result, $field, $module) {
  if($field['field_name'] == 'field_your_existing_field'){
    $name = $field['field_name'];
    foreach ($result as $table_name => $table_data) {
      if (isset($table_data[$field['field_name']]['field'])) {
        $result[$table_name][$field['field_name'] . '_value']['filter']['handler'] = 'your_custom_handler_in_separate_inc_file';
      }
    }
  }
}

//your custom handler class in separate file
class your_custom_handler_in_separate_inc_file extends existing_handler_class{
// your code goes here
}

//Don't forget to add your_custom_handler_in_separate_inc_file.inc file in your module's .info file like.

files[] = your_custom_handler_in_separate_inc_file.inc


Can I make a subdirectory in public:// viewable in Media module's UI? In Drupal 7 Media module (admin/content/media) is it possible to view subdirectories in my public:// domain? I have images and files from legacy site that were uploaded in a variety of subdirectories, i.e.

sites/default/files/presentations

sites/default/files/sponsors

etc.

My Media module browser lists all the files that exist in the main public:// directory, but doesn't show any of the subdirectories, even though I confirmed via FTP the subdirectories exist. Thanks!

I guess you can five a try to filedepot module if it helps you. Here is a quote about it (from the module's project page):

  ...  full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.


file upload using CCK not showing nid reference I have uploaded the image using CCk  the file path is stored in file table but where i can find the nid and fid for the uploaded file?

So lets say you have a content type X. You add a field Y to X to upload a file (using filefield or image etc) then you will find the nid and fid in the field table created by cck.
This table will be something like content_field_Y which should have the nid and fid that you desire.

Update: To clarify the column name will not be simply fid, but will be the machine name of the field suffixed with _value, _nid etc.


Generate PDF with Print PDF and send in email When a user registers he has to select some options that will be defining for the invoice created afterwards.

I have a rule that will be executed when saving a user account. This is what I do:

Rule 1: Create Invoice (invoice = content type) and Save Invoice
Rule 2: Fill in Invoice

The invoice is generated when a user registers an account. When I go to the invoice like this:

http://domain.com/node/147294

I see the Invoice. When I go to http://domain.com/printpdf/147294 I get a pdf with my content in it.

Now I would like to create a pdf and send it in a mail to the user that is registrated (an extra rule). But how can I do this?

Try this modules:

Views PDF

  With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

https://drupal.org/project/views_pdf

Views PDF Mime Mail

  This module provides the integration of Views PDF and Mime Mail.
  This allows the user to send a View as a PDF to a customer by Rules.

https://drupal.org/project/views_pdf_mimemail


Changing a block title per theme or page I have a search view, and I use the exposed form as a block to put the search box on every page.  In the block configuration I hide the exposed form block title so that I'll just get the search form with no title.

That works fine, but now on the Admin dashboard, I want to include the same search box.  The dashboard shows the block title, which is what I want, except the view title is 'Exposed form: publication_search-page' which is gross.

If I try to go into the block configuration and change the block title to Publication Search, I override the  that is in there now, and the title starts showing up everywhere.

How can I change the block title in the dashboard (or when I'm using the adminimal theme or whatever the admin theme is set to if that is easier) without messing up the configuration to hide it on all the other pages?

Here is a per theme solution.
In your View, under Advanced, click on Theme Information, the following pops up:

Now click on style output, and copy the entire code inside in to a new file in your text/code editor.
In my case it is:
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

Change the
<?php print $title; ?>
 to
Your Custom Title

Then save the file as views-view-unformated--[view-name]--[machine-name].tpl.php
(In my screenshot, example is the name of my view, and machine name is page, basically use last name suggestion)

Put this template file in your Adminimal theme's template folder and clear the cache to see changes.


Which version of Behat (Guzzle) would be okay to use on a RHEL server with PHP 5.4? On a Red Hat Enterprise Linux Server release 7.1 (Maipo) development server using [Behat Drupal Extension][1], a RHEL 7 / PHP 5.4 installation. When I try to run behat from the command line on a dev server, I get the following error:

$ ./vendor/bin/behat

  Feature: First
        Playing with features and exploring

  @api

  Scenario: Run cron                                             # features/first.feature:6
      PHP Fatal error:  Call to undefined function GuzzleHttp\Handler\curl_reset()

  in /var/www/html/sites/default/behat-tests/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php
  on line 78

From answers below, it appears the the version of Guzzle bundled with this requires 5.5 or greater.

  guzzlehttp/guzzle               6.1.0   Guzzle is a PHP HTTP client library
  guzzlehttp/promises             1.0.3   Guzzle promises library
  guzzlehttp/psr7                 1.2.0   PSR-7 message implementation

My question: what version of Guzzle should I use in order to be able to run test on a server with PHP 5.4?

Call to undefined function GuzzleHttp\Handler\curl_reset()

Means PHP is trying to find the function curl_reset() in the namespace GuzzleHttp\Handler.

It does that because it can't find it in the global namespace (where it should be). curl_reset() was only introduced in PHP 5.5, and you have version 5.4, so your version just isn't compatible with Guzzle 5.

Guzzle isn't explicitly listed as a dependency in the Behat extension's composer.json file, so one of the other libraries must depend on it. I'm not sure it would even be worth the time trying to unpick that, upgrading php would be much quicker.


Alter webform value submitted by webform I'm using a Webform, which have 3 fields:

- number of table (enter by user)

- price per table (default webform value)

- total amount to pay (calculation using formula, in webform is hidden field with no default value)

The calculation formula should be:
 total amount to pay = number of table * price per table

What I want to do is add in total amount to pay after calculation and submit to webform.

I'm writing the codes as below but it does not work.

function my_module_validate($form, &$form_state) {
  if ($form_id == 'webform_client_form_7'){
        $form['submitted']['total']['#value'] = $form['submitted']['number_of_tables']['#webform_component']['value'] *  $form['submitted']['price_per_table']['#value'];
    }
}

Am I writing anything wrong?

List of issues with your code (random order):

You are taking $form by value, not by reference, so all changes you make to it are local, scoped to function body only. Make it my_module_validate(&$form, &$form_state) if you want to have a chance to alter form - but see next points, too.
You are passing values around using $form instead of $form_state - things that can change in the form's lifetime belongs to $form_state rather than $form (yes, simplification, but a good starting point). In specific case of Webform module that may be needed, but you are coding against expected practice, so you should expect some difficulties when doing so.
You are using validate hook for something that is not validation. You should rather prepend additional save handler for this purpose.
You calculate on input. Usual practice in Drupal is to save user data "as is", and do formatting and calculations at output. It allows greater flexibility and retroactive changes if algorithm change. Again, it's not set in stone, and your situation may need other approach. It's OK, as long as you remember that's not quite the way Drupal was designed to work.

Tobias Kirsch posted nice summary, and I fully agree with it:

  What this means in your case: neither the validation nor the submission function of your form might be the right place for you to achive this. Maybe it would be better to add this calculation when the user is shown his submitted values. Honestly I think webform as a beginning might not be the right module to achieve this


How do you print nothing from a Field template? (field--field_name.tpl.php) I need to show a block if a field has a given state, or print nothing if it has a different state. I can get it to work using a field template with the code below, but printing useless html just to stop it from rendering it's default output seems more than a little hacky.

I've tried setting $element = null; - that didn't work. I tried changing #markup to be empty, that didn't work. Even using print ''; means Drupal kicks it's default rendering back in.

Is there a recommended method for telling a field to do nothing?

<?php if($element['#items'][0]['value'] === 1){
    //This is an archive page - show the block.
    $block = module_invoke('customblocks', 'block_view','archive');
    print render($block['content']);
    } else {
        //nothing to do here - not an archive page
        //The only way to stop Drupal rendering something appears to be to get it to print SOMETHING.
        //So we're going to print an invisible hr.
        print '<hr style="display:none;" />';
    }
?>

This tutorial might be helpful http://akyl.net/how-extract-and-theme-drupal-7-fields-out-renderpagecontent


Programmatically assign permisions to role I have a custom module and with hook_permission() I create module's specific permissions. Is there a hook (hook_role_permission) in which I can create a module specific role and assign it's permissions?

I don't want to put these in custom_module.install file because I don't want to reinstall the whole website.

You don't need to re-install the whole website just to make a change to your .install file...you can just implement hook_update_N() instead.

/**
 * Description of the update.
 */
function MYMODULE_update_7100() {
  // Perform some tasks. From the comments it looks like you have the logic you need.

  return t('Tasks completed');
}

After adding that code visit update.php and follow the instructions (or run drush updatedb) to update the database.

The changes will then be applied, without having to reinstall your modules.

This hook is the best place for your code in this situation (in my opinion) as it will only need to be run once. The update system will make sure of that on your behalf, and if you need to make further changes you can just add another update function.

Please make sure you read through the docs fully before giving it a go, there are some caveats that you really should know. Basic stuff but quite important


How to prevent a block from being cached? After login. I'm adding one sidebar block. Once I clear cache then only updates variable or it's value.

namespace Drupal\test_demo\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides 'Sidebar' Block
 *
 * @Block(
 *   id = "sidebar_block",
 *   admin_label = @Translation("Sidebar Block"),
 *   category = @Translation("Sidebar Block"),
 * )
 */

class SidebarBlock extends BlockBase {
  public function build() {
    return [
      '#markup' => $this->t('Sidebar'),
      '#cache' => [
            'max-age' => 0,
          ]
      ];
  }
}

In mytheme.theme

function theme_preprocess_block(array &$variables) {
  echo $variables['elements']['#id'];
}

How can I stop that block to being cached. So once I refresh the page. It loads the value immediately.

Got the solution via https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

Add below function to your block

https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

public function getCacheMaxAge() {
    return 0;
}

https://www.drupal.org/docs/8/api/cache-api/cache-max-age


How to add page content and webform as tab in a page? I'm using drupal 7 and I have a content type "service".

And I have a enquiry page, built with webform with following fields:

Name
Email
Service
Message

In each service page, I would like to have a tab for page content, a tab "Enquiry", with the enquiry webform in the tab.

For service field, I would like it to show page title as default.

Is there any way I can do it?

There are two ways to do that :

Write a custom module and create a menu path "node/%node/enquiry" and return your enquiry form programmatically. In hook_menu you can set type = MENU_LOCAL_TASK that will display the path as tab.
You can create a view page that displays webform and select the menu Menu tab under menu setting. Path of page should be node/%/enquiry, so that It will create a tab on node/% page. Screenshot for the second method :


Different logo on different pages I want to switch my site logo for different pages. Actually there are two site logo's that need to appear on different set of pages on my drupal 6 website.

What is the easiest way of doing this? Is there any module available for doing this or some other easy steps??

This module appears to have helped many: Logo Tool

From the Logo Tool page:

  A simple tool to display either a random logo on every page refresh, else display a specific logo on specified pages and a default set logo on all unspecified ones.


How do I make a custom block that has an image background with hotspots? I am working on making a custom module with a block that contains a floor plan.  It will be an office, when you hover over employees desks it will have a bubble appear showing that employees project status and other information.  All instructions I can find for setting the image in the block uses css.  Is this how I need to do it? Will i be able to set regions for mouse over this way?

You can try the module jQuery Map Hilight which uses jQuery maphilight plugin (visit the link to view demos).

Download from David Lynch blog / GitHub.


Changing Allowed HTML tags: @tags for help text input field I want to display a simple table under a form field as part of the help text for that field (file field to be exact). Am I being totally mental or is there really no easy way of changing the allowed html tags for this text area? At the moment I have displayed:

Instructions to present to the user below this field on the editing form.
Allowed HTML tags: a b big code del em i ins pre q small span strong sub sup tt ol ul li p br img

If there is no easy way, what is the next easiest way of doing it?

UPDATE:

Clive came up with a great way of doing it below with a custom module. You can also add to this using ctools to make the help text collapsible as follows:

// Implement hook_field_widget_form_alter()
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
  // If some condition is matched based on the element provided...
  if (isset($element[0]) && $element[0]['#field_name'] == 'field_test') {
    // Alter the description using your more permissive set of tags
    $reworked = filter_xss($context['instance']['description'], _MYMODULE_field_filter_xss_allowed_tags());
    $element[0]['#description'] = theme('ctools_collapsible', array('handle' => 'Help text', 'content' => $reworked, 'collapsed' => TRUE));
  }
}

// Provide a more permissive set of tags to be used with filter_xss()
function _MYMODULE_field_filter_xss_allowed_tags() {
  // Merge the new set of allowed tags with the less permissive defaults
  $new_tags = array('table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td');
  return array_merge(_field_filter_xss_allowed_tags(), $new_tags);
}

There isn't an easy way to do it really, the list of allowed tags is hard coded into the _field_filter_xss_allowed_tags() function.

This is in turn called by field_filter_xss(), not when the data is saved to the database but rather when it's displayed in field_default_form().

Fortunately there is a way but it'll take a small custom module to do it. You're basically looking to implement a form alter hook for the field's widget form and set the element's description to use filter_xss() with a more permissive set of tags.

Something along these lines:

// Implement hook_field_widget_form_alter()
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
  // If some condition is matched based on the element provided...
  if (isset($element[0]) && $element[0]['#field_name'] == 'field_test') {
    // Alter the description using your more permissive set of tags
    $element[0]['#description'] = filter_xss($context['instance']['description'], _MYMODULE_field_filter_xss_allowed_tags());
  }
}

// Provide a more permissive set of tags to be used with filter_xss()
function _MYMODULE_field_filter_xss_allowed_tags() {
  // Merge the new set of allowed tags with the less permissive defaults
  $new_tags = array('table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td');
  return array_merge(_field_filter_xss_allowed_tags(), $new_tags);
}

That's based on the premise that you only want to allow the new tags for an element called field_test, obviously if you want to do the same for other fields you'll need to change it to match a different condition. I advise using the excellent dpm() function included in the Devel module to inspect object in your form alter function.

I've just tested the above and it works (I now have a table where my file field description would normally be), it feels a bit like a hack even though it technically sticks to the rules but hopefully it'll get you on the way.


Adding a CSS class to every form in Drupal 6 in a theme I would like to add a class to every form tag that could appear on a page. Because it's strictly for theming purposes, I would like to do that in my custom Drupal 6 theme.

How should I do that?

Override the theme function theme_form(). See About overriding themable output for an explanation of how to override theme functions.


How do I set the options for a programatically created content type? For example, if I want to set 'Publishing options - Promoted to front page' to 0 in a .install file when creating a new content type.

I've looked in the variable table, where I was expecting to see variables for these options, but it's not obvious to me. What am I supposed to set?

Thanks.

You can set a node_options_[type] variable,

e.g:

node_options_article: Array
(
    [0] => status
    [1] => promote
)

which can be set with:

// Make my_type nodes published and not promoted to front page by default
variable_set('node_options_my_type', array('status'));


"The directory sites/default/files is not writable" error I am trying to install drupal 8.1 on a CentOS linux machine as root user.
I am getting "The directory sites/default/files is not writable." error. Before that, I had to manually create the sites/default/files folder. I have even changed the permission to 777 for all files and folder in "sites" and its sub folders and 'root' is owner of all files and folders/subfolders.

  -rwxrwxrwx. 1 root root  5997 Apr 27 05:28 default.services.yml
  -rwxrwxrwx. 1 root root 29105 Apr 27 05:28 default.settings.php
  drwxrwxrwx. 2 root root     6 Apr 27 05:45 files
  -rwxrwxrwx. 1 root root 29105 Apr 27 05:40 settings.php

How can I fix this issue?

Install the drupal using virtual host, it will be help to manage all the permissions. Here i'm giving an example of a virtual host file with some permissions which might help you install the site.

    <Directory "/var/www/html/mysite">

    Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
        Allow from all

    </Directory>

    ServerName mysite.local
    ServerAlias www.mysite.local
    DocumentRoot /var/www/html/mysite
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>


A lot of redirect for a simple page While working on the SEO of a site, we noticed that, just for the homepage we have 5 redirects (301 and 302).

http://mydomain.be = 301 => https://mydomain.be (well, that one, OK)

https://mydomain.be = 301 => https://mydomain.be/en (EN is the default language)

https://mydomain.be/en = 302 => https://mydomain.be/en/node/42

https://mydomain.be/en/node/42 = 301 => https://mydomain.be/fr/the-clean-url (why does the language detection only appears here? )

https://mydomain.be/fr/the-clean-url = 301 => https://mydomain.be/fr (because this is the homepage)

That's quite a lot of redirect jus for one page... Is there any way to reduce  that?

Like don't go to the default language and directly go to the good language? Or don't redirect to the clean URL if this is juste the homepage?

.htaccess file using redirect.

IfModule mod_rewrite.c

Redirect 301 /fromurl /tourl

Example:

Redirect 301 /http://www.example.com /https://www.example.com

Try it.


Admin (uid=1) access denied to custom module page I'm developing a custom module and the last step is to add custom permissions. I've added the administrator role to the new permission, but I see "Access Denied" when viewing /ledger/reports/balance-sheet. I've cleared caches, reloaded the module, and rebuilt permissions. I've even dug into the users.module file in core to verify that it is entering the if uid==1 return TRUE; section of function user_access(). Any help would be appreciated.

/***************************************************************
 * Drupal core hooks
 * *************************************************************/

/**
 * Implements hook_menu().
 */
function ledger_reports_menu() {
  $items = array();

$items['ledger/reports'] = array(
  'title' => 'Ledger Reports',
  'description' => 'List of available reports',
  'page callback' => 'ledger_reports_page',
  'access callback' => TRUE,
  'weight' => 10,
);

$items['ledger/reports/balance-sheet'] = array(
'title' => 'Test Balance Sheet',
'description' => 'The current balance of all asset, equity, and liability accounts',
'page callback' => 'ledger_reports_balance_sheet',
'page arguments' => array(3),
'access callback' => array('view ledger reports'),
'weight' => 10,
);

/**
 * Implements hook_permission().
 */
function ledger_reports_permission(){
  return array(
    'view ledger reports' => array(
      'title' => t('View Ledger Reports'),
      'description' => t('View the accounting reports.'),
    ),
  );
}

This:

'access callback' => array('view ledger reports'),

Needs to be:

'access arguments' => array('view ledger reports'),

Currently you're trying to make Drupal invoke a function by string while giving it an array - it's not going to like that very much ;)


How do I let users be able to view, update and delete their own content? I want to let users view a list of their own content and also be able to edit or delete them same as "/admin/content" page.

However, giving access to edit and delete their own content can be achieved using Node Access Rules or setting the access to user type at Permissions tab.

Thanks for the help.

You can use Views. Create a view of content on your site and use table format, list the fields as listed in admin/content. Add a relationship to the content:author so as to get access to the user table. In contextual filters (arguments for drupal 6), add user:uid => provide default value => user id from logged in user. Add a page display to your view and optionally provide a normal menu entry (or do that with the menu system) and Save your view. Go to the page you created, you should see only the content you created. To be able to mass delete or perform other bulk operations on the content, use Views Bulk Operations


What core configurations should be used in settings.php for a production site? Can someone please share Drupal core configurations that should be included and/or excluded from settings.php to make the site both performant and secure?

Drupal 8 has a default settings.php you can use:

sites/default/default.settings.php

Just copy it as sites/default/settings.php, add your DB connection array - and you are pretty much ready to go. Then use the UI to turn on caching and CSS/JS aggregation.

For security you may want to add in your Trusted Host Pattern

# TRUSTED HOST PROD
$settings['trusted_host_patterns'] = [
  'mysite\.com$',
];

If you really want to you can lock down your caching & preprocessing settings in the settings.php file, rather than setting it through the UI

# CACHING & JS/CSS AGGREGATION PROD
$config['system.performance']['css']['preprocess'] = 1;
$config['system.performance']['css']['gzip'] = 1;
$config['system.performance']['js']['preprocess'] = 1;
$config['system.performance']['js']['gzip'] = 1;
$config['system.performance']['cache']['page']['max_age'] = 86400;


settings.php not in expected location(s) We are trying to change the database settings for a long-standing drupal 6 site, but are having trouble finding the correct settings.php file:

$ cd /var/www/vhosts/mysite
$ find sites/ -name "settings.php*"
sites/default/settings.php.save
sites/default/settings.php.mod2
sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php
sites/mysite.com/settings.php.pre_handoff_unedited
sites/mysite.com/settings.php~
sites/mysite.com/settings.php.20131022

We renamed the two most likely suspects, but the sites continues to run smoothly:

sites/mobile.mysite.com/settings.php_hold
sites/mysite.com/settings.php_hold

I also looked for a sites.php that might be overriding settings.php, but we don't seem to have one of those either:

$ find sites/ -name "*sites.php*"
$

Which means I can't find a sites.php or settings.php anywhere in the web directory that seems to control drupal.

We have nginx set up to receive http requests and mysite.com requests are forwarded to apache.  Could that be relevant?  Where else I might look for the drupal config settings?

You should search for setting file as:

find sites/ -name settings.php

as the file won't have any other name than settings.php (unless included from settings.php).

So you're down with these 2 valid entries:

sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php

Normally when you have settings.php in sites/default it applies to all sites, unless overridden by the site specific file (which is the case).

So:

sites/mobile.mysite.com will work on sites like mobile.mysite.com
sites/mysite.com/settings.php works on sites like mysite.com

Here is example from default.settings.php documentation page:

For example, for a fictitious site installed at http://www.drupal.org/mysite/test/, the settings.php file is searched in the following directories:

sites/www.drupal.org.mysite.test
sites/drupal.org.mysite.test
sites/org.mysite.test
sites/www.drupal.org.mysite
sites/drupal.org.mysite
sites/org.mysite
sites/www.drupal.org
sites/drupal.org
sites/org
sites/default

  The configuration directory will be discovered by stripping the website's hostname from left to right and pathname from right to left. The first configuration file found will be used and any others will be ignored. If no other configuration file is found then the default configuration file at sites/default will be used.

If you're still confused, please run drush status command to find the right settings file, e.g.

$ drush status | grep settings
 Drupal Settings File            :  sites/default/settings.php

or for specific site:

$ drush -l http://mobile.mysite.com status | grep settings


Pass URL to menu item call back I'm implementing hook_menu to add a new tab to the user account page. I'd like to pass a URL as the page callback (a local URL for an existing page on the site). the page_callback parameters just accepts a function name.
How would I go about using that to pass a URL?

You can use page arguments:

function MYMODULE_menu() {
  $items['foo'] = array(
    'title' => 'Bar',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_baz',
    'page arguments' => array('http://google.com', 'another arg'),
  );

  return $items;
}

function MYMODULE_baz($url, $another_arg) {
  // Do something with $url, e.g. redirect.
  drupal_goto($url);
}

That's quite a contrived example, if you are redirecting, you could shorten that by just using drupal_goto as the callback:

function MYMODULE_menu() {
  $items['foo'] = array(
    'title' => 'Bar',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('http://google.com'),
  );

  return $items;
}


Override display of content type using Views How can I use the Views module to override the output of a content type's display?

So that when a user visits a page/node created with this content type, it renders a view instead

Use Panels instead, are designed for this very reason, and more.

Alternatively do this: Create a new node display (admin/structure/types/manage/node_type/display) with all fields you want and in Views, below "Format" there is a "Show" option, change it to "Rendered entity" and choose the node view you have created. The downside of this method is that all views advantages like: "Rewrite results", "Style settings" etc are not available, ds or preprocess functions should lift this weight if need it.


Sorting the terms of taxonomy How to set sort alphabetically in this view

I badly I asked the question above. I did not write that I want to sort alphabetically by the "slownik". The first in the table. This field is a term taxonomy.

Click here:

Then set the column to sortable, set the default sort order, and set the column to the default sort column:

Save settings and done.


Organic-Groups theme selection Does anyone know how to use the OG-Theme module to set unique themes for groups?

I can't find a relevant user interface.

Found the readme file online which describes the steps to add theme selection per group.

It can be found @ here.

It uses fields to make the selection as I suspected but the initial configuration is done via a different user interface.

Thanks for your input Steven.


How do I check the version of a third-party module? There's a place in the search_krumo module where we want to supply a different JavaScript file path basing on the version of the Devel module being used.

Is there a Drupal function that will check the version for us, or do we need to get the module version with system_get_info(), and then do something with  $module['version'] (which is a string like 7.x-1.5) ourselves?

If the latter, how should we test if version is greater than 1.6? Should we convert the string to an integer, strip out the x and stuff, and compare integers?

You can use system_get_info('module',  'devel') function and split version to get number after 7.x-
Or goes with this aproach parsing info file here is a solution from stackoverflow get a module version


db_select() returns an array I have just started using Drupal 7 and db_select().

if I have a result from db_select() (e.g. $result = $query->execute(), why can I only loop through this result once?

It appears as if there is a cursor that is not reset following a foreach loop.

So I tried to find a function that would convert this result into a multi dimensional array (e.g. $result = $result->fetchAllAssoc()) but I have found nothing.

Instead, at the moment I have to loop through the result to create an array of row objects to use later through the code (if i need to loop through it more than once)

/* this returns an array of row objects that you can use like any other array but seems as though there should be an API function to do this for me as part of the database class ? */

$array = array();
foreach($result as $row) {
  $array[] = $row;
}

Surely there must be an API function to do this already.

I don't have a Drupal 7 dev environment handy to try this on, but I think you are looking for fetchAllAssoc(), as you mentioned. This page has some query examples that are helpful.

When you call fetchAllAssoc(), you need to specify a field name as the primary key of the array, like:

 $result->fetchAllAssoc($field);

It also appears that fetchAll() will work (but apparently it is not the recommended solution).


How to let users subscribe and be notified (email) when certain type of content or taxonomy is created? I would like to notify users (by email) whenever a content type or taxonomy term they subscribed to is submitted.

I thought Rules may play a role in this but can't figure out how to let them subscribe to the content type/taxonomy term

Any ideas are welcome

I'm using Drupal 7

You could do the subscription by adding the taxonomie term to the user profile. If you don't have to many content types you could add it as a simple select list to the profile. This can be done at admin/config/people/accounts/fields.

As you sugested you can use Rules to get triggered about creates/updates of content or taxonomy terms. You might have to implement custom rules conditions or actions in PHP in a custom module to get exactly what you need. Check the differen hooks to define your own rules conditions or actions. hook_rules_action_info and hook_rules_condition_info are the most interesting for you.

To lear how to build your own rules code you find many examples in Drupal core and contributed modules.


Ability to order fields for each content in a content type I have a custom content type which is rendered by a custom tpl php. I would like to have the ability to control the order in which the fields are displayed for each contents.

I can use the order of the fields defined in the content type, but that will affect all the contents for that content type. Can I have some field in which I can specify the order of the content types that is being displayed? So that based on the field containing the order, I will render the fields in configured order.

Or else what would be the best way to do that, so that I can get control over the order of each content?

It's not clear how you define the order of the field, but if you put extra information in the node and want to use this to change the order of the fields before output, you can use the weight property to change the order in an alter hook:

hook_node_view_alter(&$build) {
if ( $build['field_sort_order']['0']['#text'] == 'sort it this way' ) {
   $build['field1']['#weight'] = -10;
   $build['field2']['#weight'] = 10;
   ...
}
...


hook_menu() (edit) not working I am doing something wrong and am not able to find what.

I have defined the hook_menu for my module, add and delete are working fine, but edit and view are not. Is like are never being called.

function nutrition_menu()
{
  $items['admin/structure/ingredients'] = array(
    'title' => 'Manage Ingredients.',
    'description' => 'Manage Ingredients.',
    'access arguments' => array('administer ingredients'),
  );

  $items['ingredient/%ingredient'] = array(
    'title callback' => 'ingredient_page_title',
    'title arguments' => array(1),
    'page callback' => 'ingredient_page_view',
    'page arguments' => array(1),
    'access arguments' => array('view ingredients'),
    'type' => MENU_CALLBACK,

  );

  $items['ingredient/%ingredient/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,

  );

  $items['ingredient/%ingredient/edit'] = array(
    'title' => 'Edit',
    'page callbacks' => 'ingredient_page_edit',
    'page arguments' => array(1),
    'access arguments' => array('update ingredients'),
    'weight' => 2,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,

  );

  $items['ingredient/add'] = array(
    'title' => 'Add new Ingredient:',
    'page callback' => 'ingredient_add',
    'access arguments' => array('create ingredients'),
    'weight' => 1,
    'menu_name' => 'management',
    'file' => 'ingredient.pages.inc',
  );

  $items['ingredient/%ingredient/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ingredient_delete_confirm',1),
    'access arguments' => array('delete ingredients'),
    'weight' => 1,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,

  );

  return $items;
}

load functions

function ingredient_load( $iid = NULL, $reset = NULL)
{
  $iids = (isset($iid) ? array($iid) : array() );
  $conditions = array();
  $ingredient = ingredient_load_multiple($iids, $conditions, $reset);
  return $ingredient ? reset($ingredient) : FALSE;
}

function ingredient_load_multiple($iids=array(),$conditions=array(),$reset=FALSE)
{
  return entity_load('ingredient', $iids, $conditions, $reset);
}

Callbacks

function ingredient_page_view($ingredient,$view_mode='full')
{
  $ingredient->content = array();

  field_attach_prepare_view('ingredient', array($ingredient->iid=>$ingredient),$view_mode);
  entity_prepare_view('ingredient',array($ingredient->iid=>$ingredient));
  $ingredient->content += field_attach_view('ingredient',$ingredient,$view_mode);

  return $ingredient->content;
}

function ingredient_page_edit($ingredient)
{
  var_dump($ingredient);

  drupal_set_title(t('Edit @name', array('@name' => $ingredient->name)), PASS_THROUGH);

  return drupal_get_form('ingredient_form',$ingredient);
}

Basically what I see is the two tabs ( View, Edit ) with no information bellow, the title isn't changing either.

Any idea?

The 'edit' page probably isn't working because you've mis-spelled page callback (it's currently spelt page callbacks).


Passing array from a form to another I have a custom module that has a form like this :

    /*
 * Sytems settings form for listing skill
 */
function skillbar_form($form, &$form_state) {

    $form['skill1'] = array(
        '#type' => 'textfield',
        '#title' => t('What's your skill ?'),
        '#default_value' => variable_get('skill1'),
        '#description' => t('Enter your skill'),
    );
    $form['skill2'] = array(
        '#type' => 'textfield',
        '#title' => t('What's your second skill'),
        '#default_value' => variable_get('skill2'),
        '#description' => t('Enter your second skill'),
    );

    return(system_settings_form($form));

}

This form will get information from user like (What's your skill ?).

FIRST : i want to redirect user after submiting this form to another form
SECOND : i want to reuse data from first form ("what's yous skill ?") and use variable's from first form to creat second form an let user to add their percentage of skill like : 90 %
Any help would be appreciate it

EDIT :

You need to use 'rebuild' property of forms here (used in multi-steps form) :

 function skillbar_form($form, &$form_state) {
   if (!empty($form_state['storage']['myvalue'])) {
    drupal_set_message(t("You submitted: @name", array('@name' => $form_state['storage']['myvalue'])));
   }
   $form['skill1'] = array(
    '#type' => 'textfield',
    '#title' => t("What's your skill ?"),
    '#default_value' => variable_get('skill1'),
    '#description' => t("Enter your skill"),
   );
   $form['skill2'] = array(
    '#type' => 'textfield',
    '#title' => t("What's your second skill"),
    '#default_value' => variable_get('skill2'),
    '#description' => t('Enter your second skill'),
   );
   $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
   );
   return $form;
  }

 function skillbar_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form_state['storage']['myvalue'] = $form_state['values']['skill1'];
  $form_state['redirect'] = ANY_URL;
 }


Node or Taxonomy reference field with "Add new item" on node creation page I would like to include an "Analyst" Reference field in a content type and allow users to create a new option without needing to leave the Add node page.  So it would be a drop-down with an "Add New Analyst" button.  So a pop-up or an iframe or something so the user doesn't have to leave the page to add a new option and then start over from scratch.

The "Analyst" could be a separate content type or even taxonomy term with multiple fields.

I would use Select (or other) module, but it doesn't support Node reference or taxonomy with multiple values.

For node reference fields, I use References Dialog to include a link for adding the referenced node. Looks like they are working on taxonomy references.


Where is the email New release(s) available coming from With Drupal 7, we are getting some emails that say "New release(s) available for name of site" , but they are going to someone who doesn't work here any more, and they are bouncing back to me.

Where are these emails coming from, they seem to be from drupal but I can't find where this is configured.

Thanks!!

It's configured on the "Available updates" settings page at /admin/reports/updates/settings:


Where can I check my module information in database? When I create a module, where does the information of the newly created module is stored in the database?

The information is stored in the config table.

Search for the record with name 'core.extension', the related data is an array of all enabled modules with their related weight.


Generating URL with CSRF token I have a route that requires a CSRF token:

mp.ajax.authorized:
  path: /mp/ajax/authorized
  defaults:
    _controller: 'Drupal\mp\Controller\AjaxController::authorizedCallback'
  requirements:
    _csrf_token: 'TRUE'

I need to generate a URL for this route. As the route has _csrf_token set to TRUE, the route needs to contain a CSRF token.

I've generated a URL from the route using Url:

Url::fromRoute('mp.ajax.authorized', [], ['absolute' => TRUE])->toString()

It generates a route with a token:

http://example.com/mp/ajax/authorized?token=91018d3f93299fe116c5596ea32d9addca063a92

I also tried the url_generator service to generate the URL:

$url_generator = \Drupal::service('url_generator');
$url = $url_generator->generateFromRoute('mp.ajax.authorized', [], ['absolute' => TRUE]);

And it generates the same URL.

However, the token on the URL is incorrect, as the actual CSRF token that is retrieved from CsrfTokenGenerator is:

1qG-Tw4AyQgNmVWtlkp_to7mielSz8ZfQZAkhWqAlsQ

I've done some reading, and it appears that the token given from Url is a placeholder, but I need the actual token, not the placeholder. Does anyone know how to get this?

Update: I've discovered I can retrieve the URL with a token in it by passing token as a parameter to the Url builder:

Url::fromRoute('mp.ajax.authorized', [], ['absolute' => TRUE, 'query' => ['token' => \Drupal::csrfToken()->get()]])->toString()

However, this token fails validation in Drupal\Core\Access\CsrfAccessCheck, so it appears this is not the correct solution.

Well, I found a solution, however, I'd be amazed if there isn't a better way to do it, and in fact I'm pretty sure it's bypassing the placeholder API, so it's likely the wrong way to do it. But until someone gives me a better solution, it's a working one.

The solution is to generate the token manually, then set it as a GET query on the URL when generating the URL.

When generating the token however, you need the internal path for the route, which is used as a basis for generating the token.

$url = Url::fromRoute('mp.ajax.authorized');
$token = \Drupal::csrfToken()->get($url->getInternalPath());
$url->setOptions(['absolute' => TRUE, 'query' => ['token' => $token]]);
$absolute_url = $url->toString()

Note that I've already found this method doesn't work on routes with optional parameters, so if someone comes across this, you'll have to find another method in such a case.


Imageapi Optimize - enabled libraries exec I'm investigating Imageapi Optimize module and everything is quite clear except one thing. There is a list of internal libraries on UI which can be enabled and set the order of it. So, for example if first library is set to pngquant and second is optipng and both are enabled, what does the second one do?

I assume, when the image is being displayed pngquant process the image and it's being compressed. After the compression the image already have the desired size, so what does the second one do? I've searched through all the web and the module code and I can't really find out what is the logic behind it. I suppose it should be radio buttons rather then checkboxes.

so what does the second one do?

It'll optimise the already-optimised image from the previous plugin as best as it can. Which won't be much.

  I suppose it should be radio buttons rather then checkboxes.

Perhaps; but that would remove the ability to have combinations of different kinds of plugins (not just file size optimisers) in the future, so it might be a bit short-sighted to say that.


Displayed content by alphabetical order I have a custom content named course and each time the admin wants add a course, it is displayed in a form with all courses, my issue is it is displayed by date and I want to change by alphabet, how can I do that? please help!!

If you are creating the form with the help of a custom module, you can sort the options in the form at the time of db query before displaying them. You can do something like this.

$query=db_select('table name','n');//here your table name
 $query->fields('n', array('title'));//SELECT the fields from table
 $query ->orderBy('title', 'DESC')//ORDER BY create
 $opts=$query->execute()->fetchAllKeyed();

$form['courses'] = array(
    '#type' => 'select',
    '#title' => t('courses'),
    '#multiple' => TRUE,
    '#options' => $opts,
);


Node paths come through empty unless view result is programmatically changed Task: to retrieve a list of nodes in JSON format including their aliases generated by Pathauto module. The configuration of my view is this:

Problem: path fields come empty - they won't include original Drupal path to it nor an alias generated by Pathauto:

The current solution I've got is to programmatically amend view's result in the following way:

function my_custom_views_pre_render(\Drupal\views\ViewExecutable $view) {
foreach($view->result as $value) {
    $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $value->_entity->get('nid')->value], ['absolute' => false]);
    $url = $url->toString();
    $value->_entity->set('path', $url);
}

}

And that populates the path fields:

I'd like to know if there is a way to avoid the hook and make views return node paths without it, or is it normal Drupal Views behaviour?

P.s.: If I chose "Fields" instead of "Entity" in the Format section in the Views UI, it does return me the correct paths. However I want to get the full entity due to extensive data it consists for later consumption.
Thanks!

Put Show on field, then remove "title" field and add Path field

and if you want result be Absolute Url  on Rewrite secion Check Use absolute link (begins with "http://")


How to use pjax module for batrik theme content? I am trying to use pjax module for content part reloading without refreshing a page but i following the instruction form pjax read me part but not worked. How to configure the module for batrik theme content part. please help me.

It seems that the module is not maintained and importantly the module is still in unstable state.

So you shouldn't be relying on this module, unless you're ready to make it stable.

You can check the alternatives here,

How to use URL-based AJAX in Drupal 7 to serve all pages?

But AFAIK there is no module available as of now with the same feature.


How to hide Header and footer printed page? I'm using drupal 7 with print module,when printing some node there is some extra content like (date , pager and url) in the header and footer page that will be printed.
I just want to print the content of the node.
How can i remove this content?

You can use module to print a node
also to remove unwanted region you can change print.tpl.php inside the module

or you can use css

@media print
    {
        #header,.menu_background,.breadcrumb,#comments,#sidebar-first,.footer_bg,.node-links { display: none; }
        .node-view{ display: block;height:800px; }
    }


Accidentally deleted sites/all/modules in Drupal 7 Let's say I was having a really rough day and I accidentally deleted the sites/all/modules directory in Drupal 7. Could I simply unzip my last back up of Drupal and copy that directory over to the server? Are there any other considerations or steps I should do and if this won't work, how should I go about fixing it? Thanks!

Running Drupal 7.50

Assuming the backup files you have are the same as the ones that were deleted, that should be fine.

You'll probably want to flush the cache but other than that there shouldn't be any problems in theory.


How to send a vote using Advance Poll and Services Voting Api? I need to expose a poll to a mobile app. After doing some research I found out that I could receive the votes, through a web service, using the services_votingapi module, and the go-to poll to use was advpoll, or Advance Poll.

I've made a poll with several choices and added, in a services endpoint, the select_votes and set_votes services for votingapi. What I can't figure out now is how to send a vote using the service? there's some documentation at https://www.drupal.org/node/2145873 but I don't know the correct values to send. How do I know the correct entity ids, etc.?

Ok, I figured out how this is supposed to work. The required JSON document to POST to the set_votes service must be this:

{
  "votes":[
    {
    "entity_id":"1328",
    "tag":"f5a8bb465",
    "value":"1"
    }
  ]
}

entity_id is the nid of the Advance Poll, tag is the choice_id of the Poll Choice you want to cast the vote for, and value must always be 1, it's the vote.

In case you need to know those IDs, it may be a good idea to expose them through the node or the view services. Or use the Devel module


Rewrite negative number into positive numbers I'm preparing some charts, with positive and negative values.
I would like to create one pie chart, including all the values (the positive and negative). Of course, this doesn't work as only positive numbers should be considered.
So I tried to rewrite the results (to cancel the "-") but it doesn't work. I would like to have "-100" displayed as "100", and the "100" staying at "100", so that I can create my graph.

Does somebody has an idea?

For Drupal 7 you could use the Global: Math expression field to perform a mathematical operation. Load the initial field first, suppress it from display and use the replacement token within the Math field: (abs([initial_field])).

For Drupal 8 this field does not exist (yet), though there is a sandbox linked in post #10 here: https://www.drupal.org/node/2544670. It might work.


How do I change the site name in the .theme file? I'm looking for a solution to change the site name in a .theme file in Drupal 8. I'm using the Group module and want to display a different site name when the current user navigate inside each group. How can I achieve this ?

In a *.theme file this would be difficult to find all places where the site name may end up. This is much easier to do it in settings.php right at the start:

settings.php:

if ($_SERVER['REQUEST_URI'] == '/abc/def') {
  $config['system.site']['name'] = 'abc-def';
}


Prevent "→" from being written in URL alias When the post title contains "→," it will be written in the URL alias.
When using Boost, an URL containing "→" will not be well cached; visitors will see the uncached node.

How do I prevent the "→" character from being written in URL aliases?

The transliteration module does a good job on making ASCII urls and some other useful stuff. Works with path_auto.


How do I integrate a nodes edit form on a page? I would like to integrate a nodes edit form on a page. For example, I want to alter the node with ID id equal to 1.
I know there are a lot of ways to achieve this, but I can imagine there is only one right way.

I am having some troubles with my form. After certain time, the edit form shows values from different nodes: some from this, some from the other, etc. I really don't know why.

Use drupal_get_form(NODETYPE . '_node_form', NODEOBJECT); as callback in your custom menu item.
The original node module callback for menu item 'node/%node/edit' is located in the node.pages.inc file:

/**
 * Menu callback; presents the node editing form.
 */
function node_page_edit($node) {
  $type_name = node_type_get_name($node);
  drupal_set_title(t('Edit @type @title', array('@type' => $type_name, '@title' => $node->title)), PASS_THROUGH);
  return drupal_get_form($node->type . '_node_form', $node);
}


Views and sorting by label In my content type field, I have a select list of current users on the system.  I want to create a page that lists all these usernames in a table.  The key is the user id (uid).  The label is their username.  When sorting in Views, it sorts by the key (uid number).  I want it to sort by the label (username).  Is there a way to do this with Views?  Keep in mind that the user list is all dynamically generated so manually reordering is not an option!

Drupal is not powerful enough for this.  Had to write my own module and my own SQL query to get it ordered the way I want.  Maybe in Drupal 8 this feature will be available.


Adding fields, account registrations and editing profile By default Drupal has a profile system in place that stores user name, password and email.

Profile2 extends this to allow specific roles upon account creation as well as more options for adding fields.

The problem is there are now two sections for adding fields, two tabs for editing account info, and no way to separate account editing into unique sections, or combine everything onto one edit page.

How can I have fields be on specific edit forms separated by how I feel they should be categorized.

Example:
On user page there is an edit tab in user menu. when clicked there is a sub menu that has inks to specific edit forms: 1. edit profile 2. security info (password, phone number)  3. photos and media 4. Address 5. personal info 6. social networks

Why I asked the question: I sat down to add fields to the users pages, such as first name, last name and zip code and was very confuse where I should create these fields and which edit form they should live, the profile2 edit form or the core edit form.

This is part of Profile2's interface design; different profile types (created in admin/structure/profiles) are presented as separate submenus on the user edit page.

If you want to work with the constraints of its interface, you can create profile type for each group of fields that you feel should be edited separately. If you feel like a field should be part of the main user edit page, you can add it to the core user entity (admin/config/people/accounts/fields).

As far as combining profile2 forms into the user edit form, Profile2 does allow you to embed profiles into the registration form (via its Show on all user account registration forms. option) but not the edit form. For that, there is the Account Profile module.

  Profile2 by default creates an additional tab for each new profile
  assigned to a user. Alternatively the submodule "Profile2 pages"
  provides a separated pages for viewing and editing profiles.


nice menu mobile gesture i've developed a project using Nice Menus module, but on mobile can't use well with submenus. So i thought to use JS injector to listen swipe on screen and make menu visible.
i wrote this code

$(document).ready(function(){$("#second-column").on("swipe",function(){
      if($(window).width()<=900)
        $("#nice-menu-1>li>ul").css("display: block; visibility: visible;");
  });
});

but chrome console said $ is not a function so i search and replace $ with jQuery, now i've no moar message but it doesn't work.

Thanks in advance for help

I think this is a syntax issue. Try using

jQuery(function($) {
    //Your Code
});


Drupal Commerce Free Shipping For Some Products Drupal 7, Commerce

The Setup: A store with two products. They are a shippable item and a gift certificate.

The shippable item has a number of shipping options available.

Gift certificates have free shipping, and always go via first class mail.

I added a 'free shipping' shipping method. Unfortunately this always shows up in all checkouts, so someone could order a hundred shippable items and then select free shipping.

When I 'configure component' for the free shipping method, it lets me define a rule as to how this method is applied.

In this rule, I need to make a loop that goes through all line items, and if there are only products marked with a field called 'field_free_shipping', then show this method.

However.... Rules sucks. :-) I can make a loop, but then I can't ask it about the product node or the field.

What am I doing wrong? Any assistance appreciated.

I'll be adding a bounty to this question when it becomes eligible.

In such a simple scenario, where you only have two products, I would just use the condition Order contains a particular product to look for the shippable product to enable the paid shipping service. I'd then use the same condition negated to enable the free shipping service.


{{ directory }} in Twig template in base theme breaks subtheme Given a base theme called parent that is a child of stable, and a sub-theme called child whose base theme is parent,  a Twig template implemented in the parent theme renders the wrong value for {{ directory }} variable.

In the parent theme, add a node.html.twig template with the following content:

{# contents of parent/templates/node.html.twig #}
file is themes/custom/parent/templates/content/node.html.twig<br>
directory is: {{ directory }}

Leave node.html.twig unimplemented in child theme, so that it inherits from parent.
Set default theme to child.
Visiting node/1 will print:

file is themes/custom/parent/templates/content/node.html.twig
directory is themes/custom/child

In theory, step 3 should produce a value of themes/custom/parent for the directory variable, otherwise, how can you depend on that variable to reference URLs of additional assets from the parent theme?

In actuality, {{ directory }} is acting exactly like {{ active_theme_path() }}.

As I understand it, this basically means that you cannot use {{ directory }} to reference any static assets in a base or parent theme, such as the path to an image icon, or using the {{ source() }} Twig function to insert an inline SVG.  In my case, I'm trying to do just this:

{{ source(directory ~ '/images/svg/resources.svg') }}

But I get: Twig_Error_Loader: Template "themes/custom/child/images/svg/resources.svg" is not defined.  Obviously, that file only exists in the parent theme.

Possibly this should be filed as a bug on drupal.org but wanted to check here first if this is already known and/or to award some karma points for a successful workaround.

Update:

My current workaround is to implement hook_preprocess() and set a global template variable called parent_theme_path that points to the parent theme path.

// @file parent.theme
/**
 * Prepares global variables for all templates.
 */
function parent_preprocess(&$variables) {
  $handler = \Drupal::service('theme_handler');
  $variables['parent_theme_path'] = $handler->getTheme('parent')->getPath();
}

{# @file parent/templates/node.html.twig #}
{{ source( parent_theme_path ~ 'images/svg/resources.svg') }}

You can also use this:
{{ source('@parent/../images/svg/resources.svg') }}

where @parent is the name of the parent theme. @parent references to the templates folder, so @parent/../ was added to go to the root directory of your theme.


Update webform submitted data through the DataBase? I see in the DataBase the table webform_submitted_data which contains the components's data of all webforms

But a token suddenly stop working as intended so the hidden fields of the webform, its data were incorrect for my use case. I fixed the issue but now want to update the affected submissions (luckly are only 10)

It is safe to update the respectives rows through a SQL statement? I do not need to trigger hooks, or other stuff, only need the correct data for the little code i write that uses it

Yes, that should be perfectly safe to do.

Take a backup first just in case, clear the cache after you've done it, and that should be fine.


Programmatically validate a node? I am programmatically creating many nodes. Obviously they have to be valid before storing them. Such $node objects have CCK fields mixed with custom fields.

Because the validators only set a form_set_error() and hardly ever return the validation-result, I have to go trough the form-api in order to know if a node is valid, or so it seems.

I call node_validate(), then form_get_errors() (which, in turn calls form_set_error()).

There appear to be several problems with this approach:

form_set_error() sets a message with drupal_set_message(); for stuff like cron (a session-less user), this adds orphaned persistent error-messages to the database (they will never be printed, hence never deleted).
the returning array of errors is created to be used in a multidimensional form array. Especially with CCK-fields, I have to dig quite deep in order to find the actual error.
I just want to store a node, so I am not interested in a user-faced form; using the form API just feels wrong.

Is there a simpler, more elegant method?

There aren't any other ways, as the hooks that the modules need to implement to validate a node are hook_validate() (if the module implements a content type) and hook_nodeapi('validate') (for all the other modules). Those hooks get a $form parameter, and are supposed to call form_set_error() in the case there is a validation error.

The easier way to find if there are errors set for a form is to use form_get_errors(), which returns the array with all the errors set with form_set_error(), the function that is also called from form_error().

In the case more than one node is validated, you would need to call form_set_error(NULL, '', TRUE) before node_validate(), and then get from form_get_errors() the array containing the error messages; if this is empty, there are no error messages.

form_set_error(NULL, '', TRUE);

// node_validate() call.

$errors = form_get_errors();

if (!empty($errors)) {
  // Some module reported an error.
}

Alternatively, you can use the following snippet to verify no module reported an error, after you call node_validate():

if (!empty($_SESSION['messages']['error'])) {
  // Some module reported an error.
}

Before calling node_validate() from the cron task, you would need to set $_SESSION['messages']['error'] to an empty array; in that way, you are sure the errors reported in the array are caused by the node validation hooks.

$_SESSION['messages'] is the variable used from drupal_set_message() to store the messages passed to the function.

function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
  if ($message) {
    if (!isset($_SESSION['messages'])) {
      $_SESSION['messages'] = array();
    }

    if (!isset($_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type] = array();
    }
    // …
  }
  // …
}


Managing large volume of content in tree hierarchy Firstly I apologise if this has already been answered. I thought it would be a common problem and I'm surprised that I haven't found a general solution anywhere.

I have a large corporate website (about 8000 pages) which is currently organised in our existing CMS in a multi-level tree structure. The navigation menus, breadcrumbs and URLs are all automatically built based on the position of content nodes in the tree. This makes it particularly easy for content editors to create new content in the right place and have the menus, breadcrumbs and URLs always consistent.

We are probably going to move to Drupal 7. What is the standard approach to large, tree-structured sites like this? I don't want to have to create new tag names (taxonomy terms?) for every single section since there are hundreds of 'container' type pages that contain lists of other pages. It seems far easier to just slot the node into a tree.

I suspect there is something obvious I'm missing - I would think it is pretty normal to have a tree like structure of content. Any help much appreciated.

Good strategy is to utilize Workbench and create sections from your menu.

So you would have your main menu, lets say 3-4 levels deep and mimic those in Taxonomy. Its easier to create taxonomy first as there is a module that will create menu from taxonomy.

So you create your taxonomy that has your structure going 3-4 levels deep. Then create a menu from it.

Install Workbench and Workbench Access and Moderation modules.

Configure Access to use Taxonomy for section assignment and then configure URL parameters to pull from Taxonomy as this will take care of your URL and breadcrumbs. Use Custom Breadcrumb module to generate breadcrumbs if you need them.

Then on each content type add a new filed for Sections which will pull from your taxonomy. So when adding content you select where in the tree it should live.

For example you are adding "Help" node which needs to live in About Us > Services  and About Us and Services are in the menu. Help does not need to be in menu but needs to follow the About Us > Services > Help path.

By using Workbench modules you can easily achieve that. In a sense your taxonomy acts as buckets into which content is placed. This drives URL, Breadcrumbs as well as left or right nav menu if you need one using Menu Block.

So to summarize the steps:

Create taxonomy of the items you want to be in menu.
Create menu from taxonomy using Taxonomy 2 Menu module.
Install Workbench suite of modules.
Configure workbench access to pull from Taxonomy.
Adjust content types to add a fields for Taxonomy selection, make it only 1 as you don't want multiple paths for nodes.
Configure URL Patterns to pull from taxonomy parents.
Install and configure Custom Breadcrumbs to also use URL path.
Install and configure Menu Block to use URL path.
Start adding content and assigning sections.

Additional benefits of this approach is that you can also restrict which roles or users can edit content in each section so you can have HR only have access to edit content in their part of the site.


BigPipe messing up JS, is there a BigPipe ready() equivalent function? I'm experimenting with BigPipe on D8 and it seems that the regular jQuery $(document).ready() function fires before the BigPipe has finished loading all the elements causing quite a few difficulties.

For instance I have buttons with activation trigger element ID's which are loaded into a variable, but the trigger elements don't seem to get loaded by the time JS runs and they aren't present yet,breaking the functionality.

Is there a simpler workaround than rewriting all the JS libraries I'm using, that rely on the ready() function? Maybe something BigPipe specific solution I haven't found yet?

You must not ever rely on document.ready when you write js for drupal. You should use drupal behaviours; If used properly this will ensure that your code runs both on normal page loads and when data is loaded by AJAX (or BigPipe!)

Also read this interesting post on drupal issue queue JS relying on document.ready event does not work with BigPipe


fetching taxonomy tree from database from query I add a vocablary named "product sub categories" and I want to fetch the whole tree structure from datebase through query? Can anybody can help me?

This is a way to do it!

$vocabulary = taxonomy_vocabulary_machine_name_load('Services');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));


How to output the Panel node's template name in the Body class list Is there a way to access a Panel's template name to output in the body of the page?

Here is what I'm using in my Zen subtheme's template.php

// Add the panel's template name to the page's body classes
if($panel_page = page_manager_get_current_page()) {
  $display = panels_get_current_page_display();
  $layout = $display->layout;
  $variables['classes_array'][] = 'panel-layout-' . $layout;
}

Hope that helps!


XSS in Drupal 7 Views Replacement token I am working on a Drupal 7 site that uses a replacement pattern %1 inside a View header to generate a URL with the Organic Group id(og_group_ref).

The view header markup is

Create Convo

Example URL of a page is site/b_posts/2, so the link created would be /node/add/post?og_group_ref=2.

This is vulnerable to XSS, since accessing the URL site/b_posts/%22%20onmouseover=%22alert%28559%29%22%20test=%22/2 would result in a JS alert getting executed on mousing over the link. How to protect against this? I used the latest version of Views and this is still happening.

You must enable validation on your contextual filter.

More information found here:

https://drupal.org/node/1578564

http://nodeone.se/en/learn-views-with-nodeone-part-23-validation-of-contextual-filter-input


How to enable special characters in Drupal Menu? I am using Drupal5 and Nice Menu Module. I need to provide a URL in my Menu dropdown. There are special characters in it. When I add the complete path it works but on giving the relative path special characters doesn't show up(it gets replaced by the hex code).  How can I display the special characters in Drupal Menu Dropdown as it is?

I guess that you can review in the nice_menus.module file, specifically in theme_nice_menu_tree() module function to parse/filter/encode/replace each hexadecimal string that seems be pushed by menu_item_link($mid) or $mid string. Remember do this kind of test with a copy of your production site. I have not tried this suggestions, sorry, I only guess after a rough review of the code. I think that could be useful. - @cigotete


Creating sub-fields within a field I am using the profile2 module in Drupal 7. I have created a field using the check box/radio widget that has 2 options and both options can be checked. How would I be able to create a sub-field that will show another checkbox/radio widget with options depending on what was checked in the main field?

For Drupal 6, there was Conditional Fields.

There is no Drupal 7 version yet, but there is an issue which links to field conditional state which at this point is only a sandbox project but seems to be widely used already.


help using hook_url_outbound_alter() to append "#id" to node/edit url My node/edit form pages are long. When the user visits the node/edit page, I wish to direct the user toward the interesting part of that page. This part of the page has the id :   <div id = "my_id">

I try to use hook_url_outbound_alter to change the path node/xxx/edit into the path node/xxx/edit/#My_id

I began testing for a specific example with the code below. But it doesn't work : the path stays as original.

function MY_MODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if ($path == 'node/17609/edit?destination=node/17592') {
    $path = 'node/17609/edit?destination=node/17592#my_id';
  }
}

(I think that the Pathauto module could have done this but I can't install it on my website for incompatibility reason)

Thanks for your help

The $options parameter passed by reference to the hook_url_outbound_alter() implementations is described as follows. (Emphasis is mine.)

  $options: A set of URL options for the URL so elements such as a fragment or a query string can be added to the URL.

What that documentation page doesn't explicitly say is that $options is the same array url() accepts, which includes the following array indexes.

  'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
  'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.


How do I split a contact form into multiple pages? I have a huge form that's way too large for a single page. I would like to split this form up into a few separate pages.  What are my options?

Edit: Still haven't figured out how to do this with Drupal 8.

You can use the Field Group module. This works for Drupal 7 and 8.

If you use Drush you can use the following command line.

drush dl field_group

drush en -y field_group


What is the difference between havingCondition and having? Drupal dynamic queries have 2 conditional clauses called having and havingCondition.

The documentation states "The Having clause behaves identically to the WHERE clause, except that it uses methods havingCondition() and having() instead of condition() and where()."

Other than this I can't find any mention of either clauses anywhere (including in the examples module), or any examples of their use.

What is the difference between the 2 functions?

I figured it out though trail and error.

Example of a having clause:

$query->having('user_count > 0');

Example of a havingCondition clause:

$query->havingCondition('user_count', 0, '>');

Essentially you can pass the alias, value and operator as separate arguments into havingCondition, but have to pass them all as one string into having.


Permission error while downloading file through IE8 I have one content type with file upload field. I am saving the files to drupal/sites/default/files/search/documents custom folder. The user can download the files from the site. The download works fine in all browsers expect IE8.

I am getting an error pop while downloading a file. Its only happening in IE8 on both windows XP and Windows 7. Once i click on download link this error is comming

"Unable to download 11820 from subdomain.domain.org" "Unable to open this internet site. The requested site is either unavailable or cannot be found. Please try again later."

Here 11820 is the node id. I am using SSL certificate in my site though the url is https://subdomainabc.domainabc.org/

Updated download_file module header.

 $headers = array(
   'Content-Type'              => 'force-download',
   'Content-Disposition'       => 'attachment; filename="' . $file->filename . '"',
   'Content-Length'            => $file->filesize,
   'Content-Transfer-Encoding' => 'binary',
   'Pragma'                    => 'private, no-cache',
   'Cache-Control'             => 'private, no-store, no-cache, max-age=0, must-revalidate',
   'Expires'                   => '0',
   'Accept-Ranges'             => 'bytes'
 );


Drupal view filter by date I have multiple events, each event can have multiple dates. When an events first end date is passed the event no longer shows, even though future dates are still available.

Current view filter settings:

I'm not sure what Date:delta(= 0) is but when it's removed, all versions of events are shown. Even though published filter is set it shows all unpublished and drafts.

I've been debugging this for several hours and would appreciate any help.

I just tried such a Views configuration:

Nodes with a Date field, with multiple dates
Some nodes have dates only in the past, some only in the future, some in both.
Configured a Views page with a simple date filter, when value is greater than now

Views filters:

And Views filters with end-date also works:

End result:

It seems to work out of the box, with the simplest setting for me.
Regarding the delta, this is simply an index number for the value in a multiple value field, its position in the list.


How do I get image styles to function on the original node page? I go to create a content type.
I add an image field and in the "manage display" section I change the
format so that it uses the image style that I want.
I then save it and it, I get the "changed save checkmark up top" and
it  says Image style: medium on the image section
When I create the content and post it, I go to view it and it shows the image at the
original size, not scaled and cropped like the image style that was
suppose to be applied to it.

Any idea what I could be doing wrong?

NOTE:  This image style works on views, but for some reason not on the original content page/node.

On Manage Display page click locate Custom display settings to expand for more display options. check Full Content and Save.

Now you will see the Full Display tab on right top of your content area click that to select that display and than select your desired image style.


Best method of importing a large csv file with fields containing multiple values and sub-fields like paragraphs and field collections I exported an old Drupal 7 site using the Views data export module. Now I need to import this back into my new Drupal 7 site, but some of my fields contain multiple values and fields that have sub fields in them (field collections).

What would be the best method of importing this?
Do I have to write my own custom module using the migrate module or use feeds?
And how do I deal with importing data into a field collection or a field with multiple values?

You could try using Field Collection Feeds

  Provide feeds integration for field collection module.


Create more than 1 advanced topic types I have a content type called advanced forum topic, which is created from the Advanced Forum module.

I would like to have 3 different kinds of topics(General, Player, Team).
Each of this has different fields. My thought was to organize these into Field collections. Is there a way that I can choose the topic type with a dropdown menu and then the rest of the fields in the collection would pop up dynamically?

You can easily do your requirement with Conditional Fields module. You can show different fields depend on the select list of topics.

Conditional Fields allows you to manage sets of dependencies between
fields. When a field is “dependent”, it will only be available for
editing and displayed if the state of the “dependee” field matches the
right condition.
When editing a node (or any other entity type that
supports fields, like users and categories), the dependent fields are
dynamically modified with the States API.


Webform ID not shown in debug output? I created a new module to extend the webform module for custom submission hooks:

function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_213') {
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'mywebform_extra_submit_213');
    }
}

I have the webform module installed and I created a webform that has a node id of 213.

When I try to output the $form_id variable, the value shown is nothing indicative of a webform and instead showing "search_form_block" as the form ID?

what is the error here? I pulled it straight from this example.

Install the Devel module.
Use the dpm() function, it will print out $form_id for all forms on any page you visit.

function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id);
}


How To Embed a video in a body field like facebook does Do you know please?

Instead of having to click on a button
to embed a video.

Is there a module that hides the embed code in the body field

http://www.youtube.com/watch?v=-cUWFLBZU5I&list=PL15BE2E8313A4E809&feature=share

So when you add the youtube link

<iframe width="560" height="315" src="VIDEO LINK" frameborder="0" allowfullscreen></iframe>

It fill in the src link

Many Thanks for your help

If I understand you correctly I think that you can use the Video Filter module.

Video Filter allows you to put something like this in the body:

[video:http://www.youtube.com/watch?v=PCLx4fRHmCk]

Here you can see a post about this module:

How to Embed Videos using Video Filter in Drupal 7


How to target and remove a given fieldset I am very new to drupal and have been playing around with lots of different modules and core features. I have now come to an issue I have been trying to solve for the pass 48hrs without finding the right solution.

I am building a forum, using the core module, but my problem is when users post a new topic / comment, they are given the option of selecting which 'text format' they want to use. I want drupal to take it as given that filtered HTML is the only option and not offer the use a 'plain text' format.

I can just target the fieldset's id with 'display:none' in CSS and that does work, will not display any more, but I would like to know how to remove the fieldset code itself.

I have tried this,

function THEMENAME_form_alter(&$form, $form_state, $form_id)  {
  unset($form_id('edit-body-und-0-format');
}

The 'edit' id is the id on the fieldset for the text options, but all this does is give me the white screen of death....

So what I am doing wrong?

Many thanks for any help given....

Glenn.

There's a wee bit of confusion in your PHP code there; you're calling a function with the same name as the string passed in $form_id, and passing 'edit-body-und-0-format' as a parameter.

What you need to do is change the relevant field in the $form array, e.g.

function THEMENAME_form_alter(&$form, $form_state, $form_id)  {
  $form['edit-body-und-0-format']['#access'] = FALSE;
}

Using #access is preferred to unset(); there might be something in a validation/submit handler that's relying on the existence of those fields, whether or not values have been submitted this time round, and removing it completely might break those (or cause some unpleasant warnings).

If you haven't already installed it, the Devel module is a must for development; you can use the dpm() function to inspect PHP elements on the front end. If you add dpm($form); to your current function, for example, when you visit the page you'll see a nice structured output of the $form variable making it easy to find the element(s) you want to alter.

Update...

If you're trying to hide the text format options there's a slightly different approach. You need to attach an after build function to the textarea, and remove the format options in there. For example:

function THEMENAME_form_alter(&$form, $form_state, $form_id)  {
  if ($form_id == 'some_form') {
    $form['body']['#after_build'][] = 'MYTHEME_body_after_build';
  }
}

function MYTHEME_body_after_build($element) {
  $element[LANGUAGE_NONE][0]['format']['#access'] = FALSE;
  return $element;
}

or something very similar.


D7 checkbox default checked Shouldn't be hard, but it is - how do you make a CCK checkbox default checked?!?

I've tried various responses in the PHP Default Value box:

return array(0 => array('#default_value' => 1));
return array(0 => array('default_value' => 1));
return array(0 => array(1));
return array(0 => 1));
return array(1);
return 1;

I'm sure you get the point. None of these work?!

I'm a bit confused where you're entering the code above? If I want a checkbox to default to checked then in the UI you can specify this. See screen shot where I've added a field with a label "Shippable".


How can I create bidirectional node references? I want to have a node reference for a content type. I have two content types A and B. I want to reference content B from a field in content type A. In the same way I want to refer content type A from content type B. What I want is If I referenced content type B from content type A, Ta field should be added automatically to content type B with reference to content A.

Linking from A to B should make it linking from B to A too. Both should have updated fields for this.

How can I do this? Which module can I use for this?

There has been a lot of movement around this subject lately.

The state of the art module seems to be Entity Reference.

It may lack some functionality you're asking for, so cnr may be of help too.


Override drupal form output. Place two input fields side by side I am building a form using the FAPI and so far it is going fine.

I do however have a requirement for two tightly coupled values (currency and amount) that I wish to appear side by side in the form and not on separate lines.

What I need is something very similar to the way Drupal handles dates (3 inputs side by side, Im not sure, but are their input values added together to produce one value?)

Im sure this is possible using the FAPI but I cant see how off hand.

I would like to avoid any extra modules if possible.

Any takers?

thanks

Kevin

You can groupe the two fields into a field group. This gives HTML code wrapped around the fields. Just change the CSS settings of this HTML to your needs.


The best way to generate buttons and apply visibility restrictions based on roles I want to generate about 40 buttons on the same page, every button should be visible to only a certain group of people based on their Drupal roles.

What the best way to do it ? I thought about creating a bloc for every button but to display them with visibility restriction in the Block layout and restrict every bloc by role..but it's not very efficient and the Block layout page will be full of those blocs.

Does anyone have any suggestions ?

Thank you

you can simply create different class for each type color and based on the role you can add the class to the button.


Custom template for displaying inner blog contents I am trying to create a custom layout for my blog listing and blog content display pages.

The following url will display all the latest blogs based on the conditions that I have set.

http:///general-blog

When I click on the 'Read more' button corresponding to a button, it will display the full blog contents in another page.

Sample format : http:///general-blog/tourist-details

I am able to modify the layout of the page corresponding to blog listing. For this, I have created a custom tpl file : page--general-blog.tpl.php.

What I want is to create a new template file for displaying the contents of individual blogs.

The individual blog content display page is not entering - page--general-blog.tpl.php file. It's always using the template - page.tpl.php.

I tried creating separate tpl files like :

page--general-blog--%.tpl.php

But, the changes in this template is not getting effect in the individual blog content display page.

How should I move forward. Has someone had any similar situations?

Declare your template using 'theme_suggestion` in your page preprocess function. like the following:

function THEMENAME_preprocess_page(&$vars){
  // Page template suggestion based on node type
  if (!empty($vars['node'])) {
    $node_type = $vars['node']->type;
    $vars['theme_hook_suggestions'][] = 'page__node__' . $node_type;
  }
}

if your node type is blog then your template will page--node--blog.tpl.php
Don't forget to clear cache after adding this code and your tpl file


Creating list of content for each user I have a custom content type named Movie.

Every user must have 2 lists of movies:

Seen movies
Not seen movies

For this purpose, I am using the Flag module to attach 2 links ("Seen" and "Unseen") on every movie page; with those, users can add the corresponding movie to their list.

I successfully made the two lists using the Views modules; users can see them when they are logged-in.

What I need is allowing users to see the movie lists of other users. How can I achieve this?

The "seen" and "unseen" lists should be mutually exclusive; if a movie is in the "Seen" list for user A, it cannot simultaneously be in the "Unseen" list for the same user.

How can I do this? Is there any other module, apart the Flag module, that could help me?

I am using Drupal 7.

Rather than using a filter like "current user" which would display uniquely for the logged in user, you will need to attach the view to each members profile with a "contextual filter" (under advanced on the right hand side). Use "User: Uid", then select"Provide default value" and "User ID from URL".

The above will mean that each view is unique to the user profile and any user can see another users list by going to their profile page.


How to get the fields of the entity? I need to get all the names of the entity, my entity is called 'a_process'?
How can I write such query in Drupal 8?

$nodes = entity_load_multiple('a_process', $name);

You can use the entity type manager to load entities of any type:

$entities = \Drupal::entityTypeManager()
  ->getStorage('a_process')
  ->loadMultiple();

foreach ($entities as $entity) {
  // ...
}

If your code is in a container aware context, be sure to inject the entity manager as a service instead of referring to \Drupal explicitly.

Of course if you always know the entity type up-front you can use the method on the entity class itself, eg

$entities = \Drupal\foo\Entity\AProcess::loadMultiple()


How do I show Device Geolocation share location prompt only on specific pages? I am working with the Device Geolocation module packed with Smart IP. I got all the functionality working great, but I would prefer if the prompt to share your location wasn't given on every page of the website. The location service is only needed on two pages of the site, so I was wondering if there's any way to only load the Device Geolocation service on those pages, or somehow limit it to only ask to share location on one page and remember that (independent of browser settings).

In the smart ip setting pages there is a setting to limit asking on specific pages.

Ask user's geolocation on specific Drupal native pages

Specify pages by using their paths (not the aliased path). Enter one path per line. The '' character is a wildcard. Example paths are blog for the blog page and blog/ for every personal blog.  is the front page. Leave blank if all pages.


How to configure webform with smtp I have create a webform and i want to configure it sending emails with smtp authentication. I have install the SMTP authentication module also, but i cant find any option that allows me to setup webform for using smtp.

Is this possible? Any advice?

Webform module uses the mail() for sending the mails. SMTP Authentication Support module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server.

Along with SMTP Authentication Support module you would need to install the Mail system module and configure it to assign a smtp class to webform which is  step by step explained in this tutorial.

If you have SMTP module installed in your drupal site than you would have to configure the SMTP settings (/admin/config/system/smtp) for sending the email

Example (Configuring SMTP for GMAIL):

A. INSTALL OPTIONS:
 1. Turn this module on or off: (SELECT "ON")

B. SMTP SERVER SETTINGS:
 1. Server: smtp.gmail.com
 2. Backup server: (LEAVE BLANK)
 3. Port: 465
 4. Use encrypted protocol: (SELECT "Use SSL")

C. SMTP AUTHENTICATION:
 1. Username: (ENTER YOUR GMAIL EMAIL ID)
 2. Password: (ENTER YOUR ABOVE EMAIL ID PASSWORD)

D. E-MAIL OPTIONS:
 1. E-mail from address: (ENTER YOUR GMAIL EMAIL ID AS ENTERED ABOVE)
 2. E-mail from name: (ENTER SITE NAME, ITS DEFAULT VALUE IS DRUPAL VERION)
 3. Allow to send e-mails formated as Html (ENABLE CHECKBOX IF YOU WANT)

E. SEND TEST E-MAIL:
 1. E-mail address to send a test e-mail to:
   (ENTER YOUR EMAIL ID AT WHICH YOU WANT TO RECEIVE TEST MAIL)

Instead of GMAIL if you want to use some other service provider than check their server details and the port details.


Get Field Collection Array From Field Collection ID I'm using the following code to return array of all field collection IDs for a node's field collection. How do I use these IDs to get an array of the values of the fields within the field collection?

case 'field_collected_dates':
$fid = field_get_items('node', $node, $key, $node->language);
$return[ $key_clean ] =  $fid;
break;

this is how you can get values from field collection

if(isset($node->field_field_collection['und'])) {
  foreach($node->field_field_collection['und'] as $field){
    $colection_node = entity_load('field_collection_item', array($field['value']));
    $name_from_collection = $colection_node[$field['value']]->field_field_name['und'][0]['value'];
  }
}

now you can understand how to get value from field collection try to fix this in your code

THANKS


How to determine module path in drush which is outside of Drupal root? I've downloaded Coder (7.x-2.x) module in the following way:

drush -y dl coder-7.x-2.x --destination=~/.drush && drush cc drush

And I would like to call function (coder_review_reviews()) from drush (using eval) which is defined in ~/.drush/coder/coder_review/coder_review.common.inc and I need to include that file first, but I don't know how to determine my module path.

Normally when module is within Drupal root, you can use module_load_include() for that, but this function is not available when you're calling drush outside of your core. It seems I can't use dd either.

How can I achieve that without hardcoding the path to the module?

In Drush, the right way to do this is to use drush_invoke_process() to call a Drush function in coder that calls coder_review_reviews() for you, and returns the result as the function result of the Drush command implementation.  I did not check to see if coder does this.

If the service you need is not exported, the alternative is to call drush_get_commandfiles().  The result you will get is a key / value pair, where the key 'coder' has the value of the full path to the coder.drush.inc file.

When commands do not export the functionality you need, it is better to submit a patch on their project providing the access you need. Directly including .inc files and calling internal functions is fragile, and at risk of breaking in new versions of the project.


how to select a non-drupal (souce db) database in a migrate module can i still use a db_select(); if my source database is a non-drupal site? how can the migrate module know what database im referring? i cant see any configuration for migrate module on how to change database selection.

$query = db_select('sourcedb.brands', 'b');
$query->addField('i1', 'foreign_key', 'foreign_key');
$query->addField('i1', 'locale', 'locale');
$query->addField('i1', 'content', 'brand_description');
$query->addField('b', 'name', 'brand_name');
$query->addField('b', 'owg_id', 'owg_id');
$query->join('sourcedb.i18n', 'i1', 'i1.foreign_key = b.id');
$query->condition('i1.locale', 'spa', '=');
$query->condition('i1.model', 'Brand', '=');
$query->condition('i1.field', 'description', '=');
$query->orderBy('i1.foreign_key', 'ASC');

is the "sourcedb" in 'sourcedb.brands' a keyword in drupal? or can i replace it directly with the table name?

It would probably be better if you looked at the Feeds module using the Feeds Database fetcher.


Is there any SIMPLE way to hide errors ONLY for anonymous users? In almost all the times I searched for literature about disabling system errors\bad-notifications ONLY for anonymous/non-admin users, the result was large-scale discussions with seemingly pretty different answers involving honorable code changes. But me, I have yet to acquire serious knowledge in PHP... Is there really no SIMPLE solution out there for someone like me? One that will include an external module or pasting a simple code snippet in one of the TPL files?

I do not want to go to `admin/config/development/logging' and then click "none", because this option there cancels errors FOR ALL users, and not just for anonymous\non-admin ones.

Do you have such a simple, detailed explanation of how to do it?

This is a typical error message I would like to hide:

And here are some more details about it:

I think the Disable Messages module is what you need.

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Features

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from
any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the
end users.

-- HOW DOES IT WORKS? --
1. install and enable the Disable Messages module
2. Go to "/admin/config/development/disable-messages", and check the "Enable filtering"
3. Go to "/admin/people/permissions", and give the permission who should "View status messages", "View warning messages", View error messages", and "Exclude from message filtering" if desired.

-- Updated July 31st 2015, 2:23pm --
CSS trick
to not display for anonymous user(not login)

body.not-logged-in div.messages.error { display: none; }

to not display for logged in user(you should not do this for admin user, but here is the trick)

body.logged-in div.messages.error { display: none; }


Download file after fill in email address When anonymous users wants to download e.g a PDF file, they must first fill in their email address. What is best way to set this up?

The easiest way without resorting to coding would be setting up a Webform that the user is required to fill out, containing only one email field, and putting the link to the PDF in the completion message.

If you need strict access control on the PDF, you can setup your site with Email Registration and Generate Password, and redirect the user after registration to a node that is visible only to authenticated users. Add a file field using the private file system to the content type and attach the PDF to the node.