How to use responsive design with bootstrap views I've come a little confused and stuck with my current learning. Whilst my efforts using Workbench, Panels, Views with Bootstrap 3 looks pretty good on my desktop, when testing the Responsive layout with the Web Developer plugin, it looks pretty dire for use with smaller resolutions ie phones, tablets etc. In this day and age, I'd rather now focus my efforts on those mediums primarily.

My issue is, my Views grids matrix (say 3*4 cells) works well on the (1600*900) desktop, but repeats the Views matrix layout on the smaller mediums, obviously not right; hoping it would be say, a list. I've done a little research and maybe I'm missing an extra enabled module and found this:

https://www.drupal.org/project/views_responsive_grid

Others say it's merely using the CSS (SPAN etc) but I'm confused with what I generally need to do as my findings aren't Drupal specific.

I need to get things like my user dashboard looking well for mobile, tablet layout etc and maybe my approach using Panel pages was now the wrong way, so I'm happy to restart those pages again, or do simply what I may be missing in the first place.

Can someone give me some indicators to the norm one needs to do to get things going?

Thanks for your help.

Please be gentle, I have an ongoing illness and the ongoing meds don't help with my cognitive ability so I'm not that dumb (-;

I think your problem is in using Views grid format. That is table based and not responsive in the way you would want it. Tables can be responsive but in a table way (hiding of columns and inserting sliders etc).

You need to use 'unformatted list' as the format, and then for your 'row class' you need to set appropriate bootstrap col-* classes and you have to get a bootstrap row class in there as well. To do that your best bet is to override the views template files and preprocess functions.

There are plenty tutorials etc available for that on the web.

Bootstrap provides the framework, you just need to make sure your html conforms and that you put the classes you need in the right places. It can be done in views without any major issues.

You should also look at these modules as they definitely will help you (provided you have read the twitter bootstrap documentation and understand at least the basics)

Views Bootstrap, Display Suite Bootstrap Layouts, Panels Bootstrap Layouts


How to send email to multiple recipients on creation of new node using rules module? I have created one node type.
Now, I want to send an email to multiple recipients on creation of new node using rules module.

To send emails to multiple persons on creating a new node, you have to create a new rule and follow these steps :

Create an event After saving a new content type and then select that particular content type.

After that add an action from Select the action to add select list and choose Send Email.

After that you can add multiple email ids in the To textarea separated by comma and space like this :
first_email@mail.com, second@mail.com, third@mail.com


What is the Views 3 equivalent of the MySQL Limit 1 in order to return just the latest record I want to display data from the latest activity record for each contact in a report created using views 3 / Drupal 7

In MySQL I'd use sorts and limit to give me the result I want (the following is not the full query, which of course would have joins)...

SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;

What is the equivalent in Views 3? I know how to sort, but how do I limit?

I don't think that limiting the results on a page is the answer - I'm quite happy with a table with 200 rows, it is just that I want only one row for each contact displaying the data from just the latest activity record associated with that contact.

Any clues anyone?

To get the query in your question you would use a pager:

Select 'Use pager' in the admin UI
Select 'Display a specified number of items'
Click 'Apply'
Enter '1' for "Items per page" on the settings screen.
Save

I suspect you might be talking more about grouping, though, and that the SQL you've got isn't representative of the query you actually want to run.

If that's the case, you should be able to accomplish what you need buy turning on aggregation, and then setting appropriate values for each field's grouping options.


How to add body to field group? I have installed Fieldgroup module to create groups in node edit form.

However, when I am on Manage fields page (for content type) I cannot add body to a group. Is there any workaround using some hook?

thanks
Tomas

The only solution I have found was to replace body with CCK field. The body in D6 is not CCK field, and it cannot be threated as CCK in many occasions


How do I package a distribution on Drupal.org? I am getting some old and mixed documentation issues with building a release for a Drupal 8-based distribution Drupal.org.

The main documentation is How to package a distribution on Drupal.org, which says to use drush make to create a drupal-org.make file. However, when I try to run this command on my site, I get the following error message.

  Make has been removed, in favor of Composer. Use the make-convert command in Drush 8 to quickly upgrade your build to Composer.

That's fine, since I am already using Composer for the project! But how do I actually then publish these dependencies on Drupal.org? Drupal.org is definitely not reading the composer.json file, and building the zip files.

Do I just have to manually make a git tag which includes all the files in the *vendoré directory, so that Drupal.org knows to build this?

I am running Drush version 9.5.2.

On Drupal.org, there isn't yet support for a distribution composer.json file, as reported on Support for distributions.
The package system used from Drupal.org, to be able to build the package files for a distribution, requires just two files: drupal-org.make and drupal-org-core.make. The latter is only necessary when using a Drupal release that is not official.
If your system doesn't allow you to create a .make file as required from Drupal.org, you can manually create it with any text editor, as long as you use the correct file format (see Example drupal.org make file), and you follow what reported in Drupal.org distribution packaging requirements. In particular, see the notes reported at the beginning.

External libraries are validated against a whitelist of GPL-compatible libraries since all code distributed from Drupal.org must be GPL compatible
Git clones from Drupal.org sandboxes (as opposed to full projects) are not supported
Patches hosted on servers other than Drupal.org are not supported
Modules and themes hosted on servers other than Drupal.org are not supported
If you need to specify anything other than an official release of the Drupal core project itself, that needs to go into a separate drupal-org-core.make file
If you request a specific Git revision you must also define the branch that revision came from

In future, some of those restrictions could be lift. There are feature requests / bugs opened in the packages.drupal.org issue queue.


Converting iso code to name How can i convert country iso code to country name while creating a node programatically using node_save? I am creating nodes programatically by fetching contents from secondary database of drupal. When i do this way, am getting country iso code in the country field instead want the name of the country. How can i achieve this?

You can use

$name = location_country_name($iso_code);

For reference http://www.drupalcontrib.org/api/drupal/contributions%21location%21location.inc/function/location_country_name/7


display default values in node form Can  you help me please with node form in the Drupal 7?

I have a three forms (node/add/A, node/add/B, node/add/C).
Values in the node/add/A are created after registration.

How to display a values with node/add/A to the node/add/B like default values a field?

Sorry for my English.
Thank you everyone for your help

well based on your comment:

Use the Computed Field module

  Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of CCK fields. So start cooking up your PHP based values!


Boost not refreshing views page I am using Drupal 7.32 and the latest Boost, Boost Crawler and Cache Expiration modules. My 'normal pages' refresh fine with boost when i amend them ie. articles, Basic Page, Content Type node, but if I change a node which belongs to a Views page (e.g. a News item on a News Blog page contructed with a View), then it does not pull in the latest news item i have just created i.e. does not expire the News Blog page. Within the documentation at https://www.drupal.org/node/545908 it shows the option

[x] Clear all cached views pages associated with a node on update/delete

But I cant see where to set this in the Boost module settings. I think that would fix my problem. Maybe that is referring to old documentation, perhaps the new module does it in a different way.

Can anyone help?

After a bit of digging around I found that this is resolved by adding the URL to the Cache Expiration setting as follows. Go to » Administration » Configuration » System >> Cache Expiration, the under Node Expiration tab, then in the section 'What URLs should be expired when node action is triggered?', tick Custom Pages, then add the URL of your pages that are created with Views, in my case its just the word News. There may be a way to add conditioning on this so it only expires the News page when nodes relating to it are amended. If anyone finds that out, can they let me know. You can also tick under Module Status in the Debug section at the bottom 'Watchdog + site message ', it will display a message show which urls have been expired (cleared).


How do I edit the output of a field? I am creating REST API using Services Module in Drupal 7.

I have created a View to Get lists of Groups. In this views, I have added a Field privacy which will tell if the group is Private or Public.

I am getting this Output if group is Private:

privacy":{"value":"1"},

and if the group is Public :

"privacy":[]

How can I edit the output of this field so that it become easier for app developer ? I want to have something like this in output :

For Private : privacy":{"value":"1"},
For Public  : privacy":{"value":"0"},

Or something like this which look good.

From the code you can use hook_services_request_postprocess_alter() to alter whatever you want from your response.

You can always use arguments to make your changes more specific:

function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  // In my response, I include the request string in the '_links' array.
  // I can use this now to determine which resource was requested.
  if (strpos($result->_links['self']['href'], 'api/1.0/widget')) {
    // Now I know I'm dealing with a widget request, so I'll
    // add the random string here...
    $result->String = "This is a string that I'm adding to the widget response";
  }
}

As result you can see in your response:

Array (
  [_links] => Array (
    [self] => Array (
      [href] => /api/1.0/widget/12345
    )
  )

  [count] => 1
  [_embedded] => Array (
    [0] => Array (
      [id] => 12345
      [type] => widget
      [path] => /node/157601
    )
  )
  [String] => 'This is a string that I'm adding to the widget response'
)

Read more Drupal: Alter API response with Services API, where is this example was taken from.


What can cause Drupal to crash Apache? In my local development environment, Drupal keeps crashing Apache when I try to load admin pages. The user pages all load fine, but any admin page causes apache to reset itself.
In the apache error log I get:

Parent: child process exited with status 255 -- Restarting.

The files were all copied from our test server, although I removed all the cached data inserts from the database while transferring it over.

We're running a separate admin theme (Garland for admin, custom theme for all other pages).  The custom themed pages work fine. I haven't found a way to determine if its the theme or the admin pages that are causing the problem.

I'm using Drupal 6 with WAMP, on Windows 7.

I'm looking for suggestions about what's causing the resets.

In your settings.php add this line ini_set('memory_limit', '128M'); and disable update module.


Adding text to a field before save (Drupal 7) I run into a situation where I need to wrap text inputted into a field before it is saved. I'm not sure the best way to do this, seems pretty straightforward but I'd like to find the "recommended way", to pull this off.

I have a node type called Post.
There is a field that captures ID -> field_id
Now I want to wrap this in HTML.

For example ->
(some html) . field_id . (/some more html)

Key point is that this append needs to happend before the save, rewritting the field in Views UI happens after the fact.

you could create your own module and implement this hook:

hook_node_presave

This hook allows you to modify the node object (and corresponding fields) before it is saved or updated within the database.


How to set different cache mobile and desktop based on header HTTP for one URL? Here is the problem we're facing :

I have one url : www.example.com/my-page with a different HTML footer for mobile and desktop.

To know which HTML to use we look for HTTP Headers sent by one CDN (Akamaï) => $_SERVER['HTTP_X_AKAMAI_DEVICE_CHARACTERISTICS'].

What we want to achieve is to have cache for both mobile and desktop based on that HTTP Header since the URL is the same. Is it possible ? And if yes, how to do it ?

Having both HTML in the DOM is not an option here, for performance reasons.

We played with contexts in the #cache array but no success here. Maybe with using tags, but not sure about how to use it.

Any help would be greatly appreciated.

You have to add a cache context to the page:

/**
 * Implements hook_preprocess_HOOK() for the page template.
 */
function mymodule_preprocess_page(&$variables) {
  if ( ... ) {  // check if this is the page
    $variables['#cache']['contexts'][] = 'headers:X-Something';
  }
}

This adds probably too many variations, so you might need a custom cache context to only vary by two conditions, mobile or desktop. Extend RequestStackCacheContextBase, so that the request stack is already injected and return either 'dc.mobile' or 'dc.desktop':

  public function getContext() {
    $request = $this->requestStack->getCurrentRequest();
    $header = $request->headers->get('HTTP_X_AKAMAI_DEVICE_CHARACTERISTICS');
    if (...) {   // check $header for mobile
      return 'dc.mobile';
    }
    else {
      return 'dc.desktop';
    }
  }

This is a tagged service (tag name: cache.context). See the documentation for more information https://www.drupal.org/docs/8/api/cache-api/cache-contexts, especially the warning about the Internal Page Cache in the last chapter concerning anonymous traffic. In most cases it should be a better option anyway to handle this edge side or even better client side in js, not server side.


Create a slideshow from external links Is it possible to create a slideshow using( slideshow module or views slideshow module or anything else) external image url's  instead of downloading the images, then uploading in the image field?

Also I'm looking for a functionality where there are some image fields( containing uploaded images) and some external image links but all need to be shown in single slideshow.

I've googled this but could not find anything useful ..

The Embedded Image Field module supports third party image content and also you can integrate with views.

Also look into below module

Remote stream wrapper Provides the ability to use external files with file fields without saving the files to your local files directory. Also provides a 'Remote URL' browser plugin for Media. see DEMO


How to empty a taxonomy? I have been messing around with data migration and I ended up with a rather corrupted taxonomy with the wrong terms in it.

I would like to completely delete the terms inside the taxonomy. I have not found any drush command for doing it. A module search was also unsuccessful, in fact I found a dead one named cleantaxonomy.

I can try to build a SQL query to do this but I am sure someone stepped into this before.

Taxonomy Manager makes that pretty easy:

  This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

Or you could do it manually:

foreach (taxonomy_vocabulary_load_multiple(FALSE) as $vocab) {
  taxonomy_vocabulary_delete($vocab->vid);
}

If you have a lot of vocabs/terms it would be better to split that up into a batch job to avoid out of memory errors.


How to create nested paragraphs items programmatically? Basically, i am programmatically generating a node. Those nodes have several anidated paragraphs like this:

-title parent
 -body parent
 -links parent
 -title child
   -body child
   -links child

-another parent
 ..etc..

I'm doing this with paragraphs, i have a parent paragraph that includes another.
At the time of generating the node i'm generating in a sufficient manner the parent paragraph with the following code:
('field_contenido_padre' is the field that contains the parent paragraph)

$paragraph = new ParagraphsItemEntity(
      array(
        'field_name' => 'field_contenido_padre',
        'bundle' => 'acordeon'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $parent);
$paragraph->field_titulo_acordeon[LANGUAGE_NONE][0]['value'] = $value["title"];
$paragraph->field_body[LANGUAGE_NONE][0]['value'] = "jajaja";

$ia = 0;
foreach ($value["items"] as $k => $item){
    $paragraph->field_link_archivo[LANGUAGE_NONE][$ia]['title'] = $item;
    $paragraph->field_link_archivo[LANGUAGE_NONE][$ia]['url'] = $value["items"][((int) $k + 1)];
}
$paragraph->save();

OK. this works.
Following further from here is my problem.
Now i would like to attach a child paragraph to this recently generated parent paragraph.
I've tried the following with no success:

first, generate the child paragraph
('field_acordeon_hijo' is the field in parent paragraph that contains the child)

$paragraph = new ParagraphsItemEntity(
    array(
      'field_name' => 'field_acordeon_hijo',
      'bundle' => 'acordeon-hijo'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('paragraphs_item', $parent);
$paragraph->field_titulo_acordeon_hijo[LANGUAGE_NONE][0]['value'] ='TITULAko Hijo';
$paragraph->body[LANGUAGE_NONE][0]['value'] = 'jajaja';
$paragraph->save();

Now i try to save the recent child into the parent's container field:

 $entity = entity_load('paragraphs_item', array($parent->item_id));
 $entity = reset($entity);
 $entity->field_acordeon_hijo[LANGUAGE_NONE] = array(
     0 => array(
       'value' => $id_child,
       'safe_value' => $id_child,
       'format ' => NULL));
 $entity->revision = TRUE;
 $entity->save(FALSE);

I get no errors, the parent paragraph is generated fine, but i don't see the children paragraphs :-/

I guess it's because I'm attaching the child to the parent, while maybe I must attach it to the node; but in that case, how to point the child to the parent?

After two days, finally, i got it working.
Step 3 is not necessary. My error was in step 2, where I wrote badly the bundle name :-(
so it was

new ParagraphsItemEntity(
    array(
      'field_name' => 'field_acordeon_hijo',
      'bundle' => 'acordeon_hijo'))

note the underscore in acordeon_hijo


Modules custom templates I'm currently building a module that has a popup page in it. The popup page is very simple and no real header/footer so I don't want to use the standard html.tpl.php page.tpl.php

How can I override the master templates with my own much simpler ones?

If memory serves me well I think the easiest way is to simply print the output in your page callback function, and not return anything:

function MYMODULE_popup_page_callback() {
  // Your theme variables
  $vars = array('foo' => 'bar');
  $output = theme('MYMODULE_popup_page', $vars);

  print $output;

  // If there's nothing more to be had from this page request you might as well end it (gracefully).
  drupal_exit();
}

The other, more involved way, would be to override the default delivery callback for your menu item. The default is drupal_deliver_html_page(); if you want to go down this route I'd recommend reading and understanding that function to see what you'll need to do in your own function.


Creating custom cron jobs in the same module I have Drupal 7 installation with Feed Import module enabled (not the same as Feeds module!). From this module I need to import data from several xml feeds with a different schedule. For example feed A should be imported once a day, but feed B - once a week.

I have done research and suggestions are that Elysia Cron or Ultimate Cron should help to do this. However I can't figure out what needs to be done to actually achieve that different feeds can be imported on different times.

If I take Ultimate Cron case as an example, then using their API ultimate_cron.api.php https://www.drupal.org/project/ultimate_cron I have found following suggestion:

I create a hook in Feed Import module, and define a new cron task (to import feed which is already defined in Feed Import by name "test API feed RAW"). Code looks like this:

function feed_import_base_cronapi() {
  $items = array();

  $items['test_api_feed_raw_cron'] = array(
    'title' => t('test API feed RAW')
  );

  return $items;
}

However when I go to Cron page in administrative layout and manually execute newly created task, nothing happens. It shows that cron task has been executed successfully, but no data is imported.

It seems that this newly created task is not actually linked with the feed that is defined in Feed Import module. Or that it is not triggering import of that feed.

What am I missing and doing wrong here? I'm not so strong with php and module development, any help will be appreciated.

I have already googled and looked for various solutions, but nothing works. I really feels like I'm missing something very basic and obvious. But of course it could be also opposite and I'm trying to achieve something really complicated..

Found a solution with a help from a colleague. Will post it here if someone would have need for it some day.

I'm missing a callback function here that triggers the actual feed import. And also I changed from Ultimate Cron to Elysia cron. (not sure if that actually makes a difference here though)

the actual function that triggers feed import is from feed_import_base.module

_feed_import_base_process_feed($feed);


Appearance of search in Views I use Views module and I've got search to specify results.

In the search I've got filter for field cena. I set operator between so user can fill in min cena and max cena.

How can I change the appearance of that search? For and foremost I'd like to  remove "And" between inputs for min cena and max cena. If it's possible I also want to create placeholders in inputs for min cena and max cena.

To remove the And title you need to implement hook_form_alter(). It would look something like this.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state){
  if ($form['#id'] == 'views-exposed-form-search-page') {
    unset($form['field_price1_value']['max']['#title']);
  }
}

You will also need to find out the $form['#id'] so that your code doesn't attempt to change all exposed forms generated by views. Install the Devel module and run.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  dsm($form['#id']);
}

The devel module will now set a message with each views exposed form and it's #id. Copy that and replace views-exposed-form-search-page in the first code example. After that you can add a dsm($form); to find out what your field name is called in the array (to replace field_price1_value).


How to remove some comments from a node? I created a new table in the database to associate comments to the node version they were submitted against. Now when the node renders, I only want to display comments that are associated with the specific node vid. I thought about querying the db in hook_node_view to remove the comments that don't apply, but ideally only comments associated with the vid are added to the node in the first place. Is there a better way to implement this? Can I get at the node right before the comments are added to it?

Apparently, the comment metadata populated after node_load comes from comment_node_load(). But indeed the comments themselves aren't added until view time at comment_node_view(), which calls comment_node_page_additions() which adds the renderable comments, which calls comment_get_thread() to load the cids.

So perhaps it would take adding vid column to the comment table, and then adding vid condition in comment_get_thread...hmmm.


Pass multiple sets of variables to theme function If I want to loop through multiple sets of theme variables in my custom theme template, how do I define them in my theme function and pass them to hook_theme?

For instance, in my case, I'm generating an email body to send via drupal_mail(), and the body will contain a list of spa openings. I want to iterate through each set in the mail (the same way views templates iterate over views rows). I have my theme function defined like so:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_module_mail' => array(
      'variables' => array(
        'service_name' => NULL,
        'time' => NULL,
        'therapist' => NULL,
        'booking_link' => NULL,
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

and I can pass one set of variables to the template just fine like so:

foreach ($available_openings[$tid['tid']] as $mail_opening) {
  $variables = $mail_opening;
  $body = theme('my_module_mail', $variables);
}

but what I want to do is pass an array of the variables array so that in my template can do something like this:

<?php foreach ($openings as $id => $opening): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $opening; ?>
  </div>
<?php endforeach; ?>

What do I need to change to do that?

Thanks.

And, the general rule of "post a question and that helps you figure it out yourself" applies here yet again.

All I did was modify my theme hook like so:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my-module-mail' => array(
      'variables' => array(
        'openings' => array(
          'service_name' => NULL,
          'time' => NULL,
          'therapist' => NULL,
          'booking_link' => NULL,
        ),
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

and fill my $variables array like so:

  // Loop through all openings for this category.
    foreach ($available_openings[$tid['tid']] as $mail_opening) {
      $variables['openings'][] = $mail_opening;
    }
    $body = theme('my_module_mail', $variables);
    // Define mail parameters.
    $params = array(
      'subject' => t('Your Available Openings'),
      'body' => $body,
    );
    // Send the mail.
    drupal_mail('my-module-mail', 'featured_openings', $entity->mail, language_default(), $params);

and it works like a charm.


How do I store large volumes or data points using Drupal ( temperature and humidity points ) I'm trying to use Drupal as a headless API, and so far I'm having good results. One of the things I'm collecting is a Temperature and Humidity data. Thus far I've created an entity that can hold the data points, but now that I'm really thinking about it, this is not the most efficient way of doing this, a new entity has to be created for each datapoint. I've contemplated separating off this part of the api, but then I loose all of the Drupal functionality. Is there a better way to store large sets of data points using Drupal? Perhaps I can group the data points within a single field as a JSON string? I'm using D7

This is a large topic, so I will just mention some points and you can make the rest.

You will need a module, so you must have a .info, .module and in your case a .install file.

In the .module file:

Implement hook_field_info to tell Drupal about your custom field. Here is an example of how to use hook_field_info.
You must also introduce a widget and a formatter for your field. The widget is what appears in forms when you want to get data from user, and the formatter outputs data in proper way in view modes.
You need to notify Drupal about these items existence, hook_field_widget_info and hook_field_formatter_info will do the job for you.
After that you must make your widget, hook_field_widget_form is the proper hook here and hook_field_formatter_view will handle your field view.
Another thing is a zero function for your field - this function tells Drupal if the user has not filled or passed any data to your widget, hook_field_is_empty is implemented for that and it is required, else after form submission your users will face an error.
hook_field_validate can also be used to validate the data which is entered.

At this point we are done with the .module file,  but we still have on more step to go: the .install file.

Here we define a place for data to be stored in DB, hook_field_schema will do the job for you.

After this point you are all done.


How to log simpletest test results into files using drush test-run? I would like to save simpletest test results into a log file. What bash commands should I use ?

I tried this command (example) but nothing is saved into /var/tmp folder :

sudo -u apache drush test-run Comment --xml /var/tmp

I use Linux , Drupal 7.12, Drush 4.5

I don't use drush test-run, but Drush options are always in the form --xml=/var/tmp.

c.f. http://drupal.org/node/1416198

From drush help test-run

 --xml      Output verbose test results to a
            specified directory using the JUnit
            test reporting format. Useful for
            integrating with Jenkins.

Try:

sudo -u apache drush test-run Comment --all --xml=/var/tmp


Adding files to a node I am adding files to a file field in my node object.  Do I have to specify a path for the file(s)?  Can't I just add the files to the DB and just add the file objects to the node? I'd rather let Drupal care about the file system.

No, you don't have to specify a folder, file field will use 'sites/default/files' by default. In the file field settings there is a textfield to set a subfolder if needed.


Group Views results by split year (academic, fiscal, etc.) I have several content types with Date fields. I would like to build a View that groups that content by our academic year, e.g. 2015-2016, 2016-2017, 2017-2018, etc.

I realize I would have to define those start and end dates somewhere (i.e. August 1 through July 31). It could be similar to a fiscal year as well.

I could do taxonomy terms, but I was hoping to not have to introduce another field if the date fields can accomplish this.

I am using Drupal 8.

Use Grouped Exposed Filter

Using a Grouped Exposed Filter for the Authored on field is the quickest and easiest way to filter out by academic year.

When you Expose a Filter, you can choose between Single filter and Grouped filters:

If you choose Grouped filters you can define your own items for the Exposed filter. In your case two academic years would be configured like this:

I haven't included time but you probably should to make sure that content created on July 31 and August 1 doesn't get exluded. Maybe something like 2017-08-01 00:00:00 and 2018-07-31 23:59:59 would work.

Add as many entries as you have academic years. Then when viewing your Views results choose the appropriate academic year option:

I've noticed grouped filters have some bugs in D8 when dealing with taxonomy terms, but I haven't noticed any problems with AuthoredOn field.

Contextual Filter Content: Created year + month

If you include this Contextual Filter and choose to Display a summary:

you get links of months and years you click through to see content posted within those dates:

If that alone isn't enough maybe that can inspire you to create a similar custom Contextual filter with a bit more logic inside to do the same but for a configurable set of periods.


Twitter Widget profile script outputting white screen? Does anyone know why I'm receiving a white screen when I added the following code into a page panel?

<script charset="utf-8" src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 4,
  interval: 30000,
  width: 250,
  height: 300,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: false,
    loop: false,
    live: false,
    behavior: 'all'
  }
}).render().setUser('Twitter').start();
</script>

I've used the twitter widgets in blocks almost exactly (eg, different theme settings and users) like the above, and shoving a cut and paste of your code above works fine in a static .htm, so, I'd check your php and other console/error logs to see what drupal is upset about. First idea is an input filter is bolloxing it up.


Views - Test if field is visible via PHP I am developing a custom theme for a specific view. I need to iterate and render each row and field, How can i do that?

Some code:

foreach($view->rows as idx => $row)
{
    foreach($view->field as $name => $handler)
    {
        //I need to check if the field is hidden from
        //display here
        $view->render_field($name, idx);
    }
}

I am going through with the debugger and use $handler array options, but within that I could not find any field that is visible or not.

Can anybody help?

Data that you are looking for is located at $field->handler->options['exclude']. But it is tricky to get to.

When you mark the field as excluded, its data becomes inaccessible at the field's level in your View's template.

$row object also does not have any indication that the field was excluded via Views UI. $row contains only the value data from each field. You can confirm that by doing dsm($row); in your View template file (if you have devel module installed).

If you are overriding you View's template on the "Row style output" level, than the only object you can use to reach options['exclude'] from already excluded fields is $views.

You could do something like this at the top of your .tpl file:

foreach ($view->field as $view_field)
    {
        //check if field is excluded
         if ($view_field->options['exclude'] == 1) {
             // field is exluded - do something
             print $view_field->field.' is excluded from this view'; // print name of excluded field
             print $row->field_field_yourfieldname[0]['raw']['safe_value'];
        }
    }

so, if the field is excluded - it is going to be excluded in each row, according to that you can assign some markup or text to a variable and then print it anywhere down the template.


Filter View based on current user profile info (from Content Profile Module) I have the Content Profile module installed. With this module, each user has 1 to many locations that are attached to them.

These locations are created via a content type called locs.

I have another content type called todays_spot that also has a selectable location (only one) also being dynamically created via locs.

So I'm pulling some of the todays_spot data out via a view, but I need to filter it so it only displays data if the user location(s) match.

Any suggestions, I've looked all over and can't find a thing.

See this post for a solution in Drupal 7, but the same principle applies here.

Create an argument for the related loc of todays_spot.
Choose the the right relationship (node, I think), and select 'provide default argument'
Use 'PHP Code' as your default argument

You'll need to modify the code below to match your system, but it should resemble the following:

global $user;
// the code below loads via the Profile2 module, but something similar
// will work with Content Profile, but you'll need to inspect the code
// to find a function similar to `profile2_load_by_user`
// I'd start by inspecting the $user variable with print_r or dd();
$profile = profile2_load_by_user($user->uid,'facilitator');
if (!$profile) { return ''; }
if (!isset($profile->field_location['und'])) { return ''; }
$locations='';
foreach ($profile->field_location['und'] as $location) {
  $locations.=','.$location['nid'];
}
return substr($locations,1);

Don't forget to select 'Allow Multiple Terms Per Argument' before saving your new argument.


Notice: Use of undefined constant FIELD_LOAD_CURRENT Attempting to use EFQ for the first time. I'm following a couple walk throughs.

I'm trying to query for the content type banner which has an image field:

<?php
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'banner')
  ->propertyCondition('status', 1)
  ->execute();

But after doing so the result of this is an error:

Notice: Use of undefined constant FIELD_LOAD_CURRENT

What is the cause of this particular error?

Discovered that this happens when you're executing this particular function outside of drupal being bootstrapped.

Source: https://drupal.org/node/1286964


Any way to set Drupal theme settings per page? I have a theme which has multiple theme options in its settings page. Is there a way to assign particular theme settings to specific Drupal paths?

For Drupal 7, you can do this by taking advantage of the fact that theme settings are cached by drupal_static(). See theme_get_setting(). I think the same approach would work for Drupal 8 too, but haven't tried it.

// Implement HOOK_init.
// Here we override one of the Bootstrap theme settings.
function MY_MODULE_init() {
  // Only do this if we're actually on the relevant page.
  if ($_GET['q'] == PATH_TO_THE_PAGE) {
    // Override the Bootstrap theme setting 'Smart form descriptions (via Tooltips)'.
    // This because we want to display form input #description as text, not tooltip.
    // This will also affect any other forms on the current page, no easy solution for that.

    // Set the name of the theme we're interested in (the current theme in this case).
    $theme_name = $GLOBALS['theme_key'];
    // Read the setting first to ensure that the drupal_static cache is populated.
    $setting = theme_get_setting('bootstrap_forms_smart_descriptions', $theme_name);
    // Get a reference to the cached settings.
    $cached_settings = &drupal_static('theme_get_setting');
    // Unset the 'bootstrap_forms_smart_descriptions' setting from the cache.
    unset($cached_settings[$theme_name]['bootstrap_forms_smart_descriptions']);
  }
}

I should add, this is arguably a bit of a hack, as it depends on the internals of drupal_static() and theme_get_setting() i.e. not documented API functionality - unless you consider the code to be the documentation :)


Showing the description for the term identified by the argument in the Taxonomy Term view I have a view that is a clone of the Taxonomy Terms default view, it has the depth modifier turned on.  I would like to provide the description field for the taxonomy that has been loaded in the header if it exists.  I'm using this with pathauto, so while the actual url may be something like /pub/by/geo-area/ethiopia, views gets the tid (lets say 3046) as the argument.

How can I then put the description field from that taxonomy term into the header of the view?  I tried creating a relationship for the taxonomy term content, but since I don't know at the time of creating the view what vocabulary the term will be from, and because it is possible that there will be multiple terms for that vocabulary attached to some of the nodes, that doesn't seem to be workable.

I considered an attachment, but I'm not sure how I could pull that off either.  Can I do this without an extra module?

I want the description for the term coming in via the contextual
  filter argument

Ok then,

1) Create a new view

Show: Taxonomy Terms.
☑ Create a Block

Display format: Unformated list of Fields

2) Save and Continue.

Add the Contextual Filter.
Add the description field.

3) Go back to your other view and attach view to header.


How to print drupal module version with drush 6.5.0 Here's an example of a module in one of my make files:

projects[views][version] = "3.8"
projects[views][type] = "module"
projects[views][subdir] = "contrib"
projects[views][download][url] = "git://testurl.org/drupal/modules/views.git"
projects[views][download][tag] = "7.x-3.8

Drush 5.7.0 adds information about the module to every module .info file:

; Information added by drush on 2015-01-20
version = "7.x-3.8"
core = "7.x"
project = "views"
datestamp = "1421783211"

I can't find a way to append this information with Drush 6.5.0 and since I am using a git repo, the version is always missing from the .info file.

Is there a way to print that information with Drush 6.5.0?

You can use the following command to check all the info about a module. For this command is :

drush pmi module_name

This command provide info like this :

Extension        :  module_name
 Project          :  module_name
 Type             :  module
 Title            :  module_name
 Description      :  Improves Drupal's login system.
 Version          :  7.x-1.5
 Date             :  2015-05-01
 Package          :  Other
 Core             :  7.x
 PHP              :  5.2.4
 Status           :  enabled
 Path             :  sites/all/modules/module_name
 Schema version   :  7000
 Files            :  none
 Requires         :  none
 Required by      :  module_name
 Permissions      :  none
 Configure        :  admin/config/system/module_name


Using the API of relations module How can I use the API and hooks of a contributed module, I am trying to use relations module to add my functionalities using that module but I could not find any documentation that help me to do that

Any help?

Unfortunately the relation.api.php file included with the module is empty, so it doesn't appear that there's any official API documentation yet. There's the standard documentation but I don't think that covers code.

In this situation I normally head straight for the .test files included with the module. If they've been done properly (and it looks like they have for Relation), you should find all the code examples you need in there.

To find out what hooks (if any) the module provides, I usually just grep the module folder for module_implements( and see what hooks are actually invoked. If any are provided by the module you should be able to find them that way.

If that doesn't help it might be wise to re-think your question and make it more specific to what you're actually trying to accomplish in the first instance.


Help Needed Regarding View Module Hi I am a newbie and want to Get Functionality from view module in the form of grid in which i want to show some fields and a main title after clicking on title user will be directed to full post. Can anyone help me how to get this functionality.
In other word i want to change the order of displaying data to end user created by the view module.

If you have already created a view which shows nodes you want to display, in the view settings select Format > Grid, and Show > Fields in the Format area; select the fields you want to display in the Fields area.

If you want other than default sorting options use modules such as the following ones:

the Weight module (It allows you to assign weight to nodes and then sort them by that weight.)
the Menu Node Views module (If you have added your nodes to some menus, then this module allows to sort nodes in the view by that order.)

Note

The Menu Node Views module starts producing duplicate results, if the content of the node is translated to other languages (translated using the Entity translation module).


How to add a local task tab to node view? I'm trying to add an extra tab to the node 'view' and 'edit' tabs.

My module is enabled fine and I have cleared cache, but my new tab doesn't appear. What am I missing?

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

  $items['node/%node/performance'] = array(
    'title' => 'Add a performance',
    'page callback' => 'add_performance_action',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
* Page callback.
*/
function add_performance_action() {
  return t('Hello');
}

Your code looks good but Remember to clear your Drupal caches at admin/config/development/performance after every change to your hook_menu above.

The alternative that comes to mind,would be to use hook_menu_local_tasks_alter, because the menu item we want to use may be already exists.

You can also try this i hope it will help you:

/**
* Implements hook_menu().
*/
function add_performance_menu() {
  $items = array();
  $items['node/%node/performance'] = array(
    'title' => 'Add a performance',
    'access callback' => 'your_module_access_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}
function your_module_access_check($node) {
  if ($node->type == 'page') {
    return TRUE;
  }
  return FALSE;
}

Thanks


Using the Big Pipe approach for listing pages that are driven by Solr Index We are working on a website where we might end up having thousands/lakhs of nodes. So we are planning on using Apache Solr for the listing pages as well.

Having researched a little bit about Big Pipe I was curious if we can use the Big Pipe approach for listing pages that are driven by Solr Index and if Drupal 8 Search/Solr module already supports it.

What exactly do you want to achieve?

That you can scroll endlessly through your nodes and don't have to click on pager links?

That's not related to the big pipe stuff.

Instead, you'll need a views pager plugin for that, e.g. https://www.drupal.org/project/views_infinite_scroll. There is a Drupal 8 version but I haven't used it yet, so I don't know if it's stable.


Show the latest post titles for posts using a specific category I want to get the latest post titles for posts using a specific category, in Drupal 6.

How can I achieve this?

Drupal shows those nodes in http://example.com/taxonomy/term/$tid. If all you want is getting a page listing the nodes using a taxonomy term, that is the page to look at.

If you want to obtain the list of nodes using a taxonomy term with code, you can use the following one, based on taxonomy_select_nodes().

function mymodule_get_node_titles($tid, $order = 'n.sticky DESC, n.created DESC', $limit = 10) {
  $term = taxonomy_get_term($tid);
  $tree = taxonomy_get_tree($term->vid, $tid, -1);
  $descendant_tids[] = array_merge(array($tid), array_map('_taxonomy_get_tid_from_term', $tree));

  $args = call_user_func_array('array_merge', $descendant_tids);
  $placeholders = db_placeholders($args, 'int');
  $sql = 'SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid IN (' . $placeholders . ') AND n.status = 1 ORDER BY ' . $order;

  $sql = db_rewrite_sql($sql);

  return db_query_range($sql, $args, 0, $limit);
}

The code to call that function is similar to the following one.

$result = mymodule_get_node_titles($tid);
$items = array();
while ($row = db_fetch_object($result)) {
  $items[$row->nid] = $row->title;
}

$tid is the taxonomy term ID.


Are there any security concerns with getting the UID by simply querying the sessions table against the visitor's cookie? In the High Performance JavaScript Callback Handler I'm attempting to use my own code to get the current user's ID.

To give a quick rundown, by returning data at a much lower bootstrap level (DRUPAL_BOOTSTRAP_DATABASE) I can return a page in ~90 milliseconds instead of the ~1500 milliseconds that a full bootstrap takes on this server. For simple content that any user can see, such as a published, publicly-viewable node, there aren't any security concerns. But if I need to perform any kind of access check, I need to know the current user's UID. I'm getting the UID by querying the sessions table for their sid/ssid. Consider this code:

  $session_name = session_name();
  if (!empty($session_name)) {
    if ($uid = db_query("SELECT uid FROM {sessions} WHERE sid = :sid", array(':sid' => $_COOKIE[$session_name]))->fetchColumn()) {
      $account = new stdClass();
      $account->uid = $uid;
      $account->roles = array();
      $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      $account->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $account->uid))->fetchAllKeyed(0, 1);
    }
  }

I am not yet including logic for their ssid (HTTPS), as I just wanted to get a proof of concept working quickly.

Are there any security concerns that I'm missing here? I've gone through session.inc and, while I'm completely ignoring the anonymous user handling, page caching, etc., none of those really matter to me within the context of what I'm doing. If I don't have an authenticated user, I don't need to create a new session for them or anything like that, they just get an access denied response from the server.

Edit: I should add that, with the above $account, permissions checks like user_access() and node_access() can be run.

Edit 2: Here's the original issue where I'm dialoging on this particular topic within the js module: http://drupal.org/node/1922406

The approach is vulnerable to a man-in-the-middle attack but just like any connection that isn't encrypted (HTTP). An attacker could use this to read the comments of nodes they otherwise don't have access to.

Otherwise, without knowing more context of how this used and displayed I can't say there are no other security concerns. I'll comment on a possible XSS issue with your comment display code at http://drupal.org/node/1922406.

I would recommend that you check for the session cookie though:

if (!empty($session_name) && !empty($_COOKIE[$session_name])) {


How could I create an iframe page like this in Drupal? I want one of my content type pages to look like this http://flippa.com/auctions/2647380/site
The data at the top would be filled by cck fields from that content type. How could I do this?

Add a field for URL, and then in your theme spit out the URL field value as an IFRAME tag.


how to add custom font files to template I like to add my custom font to my custom theming. All the font-files are in the file FONTS. And I also have a fonts.css file.
Where do I have to declare all this stuff?

You need to use libraries. Take a look here for a detailed explination: https://www.kinetasystems.com/blog/adding-google-fonts-to-a-drupal-8-theme


Customizing views exposed filter drop down list with css I have a view with few exposed filters. They are all "choose 1 term" type of filters with appearing dropdown list when you click on right side of them.

I want to style appearing dropdown lists. It looks ok in  chrome, but it's especially ugly looking in IE. Also, i can't find them in the code, they just dissapear when i try to "inspect" them.

How can i customize those drop-down lists' appearances? Do they have any css classes? Any other ideas?

Unfortunatelly, every browser has its own rendering of drop downs (as well as fileupload boxes). So direct CSS styling of a dropdown element won't work in all browsers.

What you need to do is to use module called Uniform (http://drupal.org/project/uniform). It provides intergration with uniform library which automatically replaces drop downs, fileuploads, checkboxes and radios with custom styled elements.

This will give you ability to style these custom elements and make dropdown lists look the way you want in almost any browser. Just check if this works for you.


Fetch third Level Depth Data from taxonomy with performance I have taxonomy with 4 Level State->District->Block->Villages. I want to get all villages of all Blocks of all Districts of a State.

I have done it by loops but my performance is very slow. please help me this take more time than expectation and very slow process.

You can fetch all child at any level by using this code :

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
      $result[$t]->children = array();
      foreach ($below as $nt => $nd){
        $result[$t]->children[$nt] = $nd;
      }
    }
  }
  return $result;
}

OR

You can do it by adding custom database query using function function taxonomy_get_children


Allow the user to send emails to all or selected rows in a particular views display Salut!

I have been working on a 100% non-profit project for 1 month and now I am facing a problem with the main feature that this project offer for free.

The project is a website about people willing to help other for free so there are two roles on the website: Job helper and Job Seeker

When someone register under the role of Job helper, he will be asked to verify his phone number and email address because at any time he might receive email/sms asking him for help.

When someone register under the role of Job seeker, he will be able to see a list of all available Job helper using a view display and then choose one from two options:

A button or link to Send emails to all the available listed Job helper profiles, or
A button or link to send email to only selected Job helper profiles.

Problem:

How to create such functionality, note that the view is already created and displaying all available users which are registered under the Job helper role but I cannot find a way to place a button or link within the view as well as check box near to every user so a Job Seeker can select all or select few profiles and send a customized email.

Solutions:

1) Using VBO, is possible to do the above, however after selecting users to send emails for them, I want the Job Seeker to be able to customize only the message body being sent, but VBO will display all the field shown in the picture below which will confuse the user of the website.

I want to display only the message text body so the Job Seeker can customize his own message like:

"We need help in cleaning the beach of Florida from any garbage at 14:00 tomorrow 15/Jun/2017, please be there for the beach"

Note the Job Seeker will have to write no recipient and no subject just a message text about the job.

2) I have an idea about using flag module with views, and so the Job Seeker will have to flag every single Job Helper and then write a customized message body to be send via email... But I really have no ideas from where I should start ?

Please note that I need to integrate rules with the solution because if every Job Seeker has the right to send 1000 emails per weeks and so I want to use rules to "-1" for every email being sent by a specific Job Seeker user.

Any suggestion and help will be much appreciated !
Thank you,

I wrote an answer somewhat similar to this functionality.

https://drupal.stackexchange.com/a/195228/53677

Basically, you could create an entityform with an entityreference field for emailable users and a field for your email message.

Then on your view page, provide an email button and use jQuery to create a link to pre-populate the users you want to email. Use Rules to loop this on entityform save.

The link to the form would have to look like /eform/submit/email-form?field_email_uids=10,12,15,201

It's a bit more work but can give a really nice interface if done right. Your view can be anything as long as you can grab the UIDs.

Or you could just hide the fields you don't want with css / jQuery.

Edit: Adding instructions for the jQuery part

Here's a very basic example of the finished result. This can be added to any view setup.

You can of course decide to not use checkboxes and perhaps add a border or background etc. to the whole row. You can do anything you like with jQuery and .parent()etc. to go up the DOM and add/remove classes.

Views Custom Text Field: (The UID and Name fields are hidden above. I use font-awesome on this install. You can use ✓ or something else instead of the )

 [name]

Views Footer Custom Text Field:

Send Email

jQuery:

$('.email_box').click( function() {

    // Check if it's clicked + add / remove classes
    if ( !$(this).hasClass('email_checked') ) {
        // Add Class
        $(this).addClass('email_checked');
    } else {
        // Remove Class
        $(this).removeClass('email_checked');
    }

    // Call function below for Email Link
    build_link();

});

// Get all boxes that are clicked and add their value tags to the link
var build_link = function() {
    var email_uids_array = [];
    // Loop checked and add UIDs to array
    $('.email_checked').each( function() {
        email_uids_array.push( $(this).attr('value') );
    });
    // Split array into uids
    var uids = email_uids_array.toString();
    // Create link
    var link = '/eform/submit/email-form?field_email_uids=' + uids;
    // Alter the Email link's href
    $('#email_link').attr('href', link);
};

Some CSS so it makes sense to the user:

.email_box {
  border: solid;
  border-width: 1px;
  border-color: #c2c2c2;
  color: #ddd;
}
.email_checked {
  color: #444;
}
/* Fix Hover / Focus */
.email_box:focus,
.email_box:hover {
  color: #ddd;
}
.email_checked:focus,
.email_checked:hover {
  color: #444;
}

The benefits here are total customization and it should work pretty well.


Web forms senders to make their email secure Make Web forms secure- can we have an option for senders to make their email secure when sending private information back like account numbers, is there an option for this in Drupal or is it possible to create something,

You can use the SMTP Authentication Support which allows you to send your e-mail via port 587 (TLS), which means your e-mail gets encrypted.


HIde taxonomy menu based on count? Possibly using rules? Is it possible to hide taxonomy menu items based on their node count?

E.g. i have several zounds categories (notebooks, office, health, etc) created but they are just empty taxonomy items because the client has yet to add these products.

I'd like only the taxonomy terms with nodes to be visible.

Is it possible to accomplish this via rules or some other module?

Background:

I have a taxonomy menu created by taxonomy_menu and then it's turned into a menu block and that menu block is turn into a superfish dropdown menu.

There is an option in the taxonomy_menu "Hide empty items" to disable menu options if there are no nodes tagged with the specific term. The option can be found in the admin/structure/taxonomy then the vacab you are using.

Below is an image for reference.

Settings Image


Sending multiple attachment files by email I am trying to send multiple files attached to an email, but I can only make it work when only one file is attached. I am using mandrill mailer, btw.

Here is the code I have on a form submit:

    $attachments = [];
    if ($files) {
      foreach ($files as $key => $value) {
        $file = File::load($value['target_id']);
        $attachments[] = [
          'filepath' => $file->getFileUri(),
          'filename' => $file->getFileName(),
          'filemime' => $file->getMimeType(),
        ];
      }
    }

    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'mymodule';
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $params = [
      'subject' => 'Application from ' . $applying_user->get('field_first_name')->value . ' ' . $applying_user->get('field_last_name')->value,
      'candidate_name' => $applying_user->get('field_first_name')->value . ' ' . $applying_user->get('field_last_name')->value,
      'attachments' => $attachments,
    ];
    $mailManager->mail($module, 'email_application', $user_email, $langcode, $params);

Then using hook_mail():

 case 'email_application':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = $params['subject'];
      $message['body'][] = buildBodyMail($params);
      $message['attachments'] = $params['attachments'];
      break;

The email I receive does not have any attachment, even though there are 4 files in this particular example meant to be attached.

If I change the code to:

    if ($files) {
      foreach ($files as $key => $value) {
        $file = File::load($value['target_id']);
        $attachments = [
          'filepath' => $file->getFileUri(),
          'filename' => $file->getFileName(),
          'filemime' => $file->getMimeType(),
        ];
      }
    }

...then it attaches only the last file of the set. It seems that

$message['attachments']

does not allow a multidimensional array. I've seen examples with

$message['params']['attachments'] = $params['attachments'];

and have tried but to no avail.

How can multiple files be attached to an email? Thanks in advance.

Try as $message['attachments'][] instead of $message['attachments']
example
$message['attachments'][] = $params['attachment2'];


How to render views link field in twig? I have created a view that has many fields including a link field.
I am using a twig template. my view twig name is views-view-fields--dashboard--block_3.html.twig It works nicely but I need to render a path in an anchor tag. here is my code.

{{ fields.title.content }}

        {{ fields.body.content }}
        {{ fields.created.content }}

In the anchor tag, I am getting the link but it has twig debugging wrappers. The result is bellow

and I need only the path. I have already tried the twig_field_value module. but when I {{ fields.view_node.content|field_value}}

  Error: Cannot use object of type Drupal\Core\Render\Markup as array in
  Drupal\twig_field_value\Twig\Extension\FieldValueExtension->isFieldRenderArray()
  (line 171 of
  modules\contrib\twig_field_value\src\Twig\Extension\FieldValueExtension.php).

Now I am looking for how to render the value of an anchor tag without any wrapper.

If you want to remove twig debug comments you can use striptags filter

Like the following:

{{ fields.view_node.content|striptags}}


How to display all children on parent node for custom content type? I have a custom content type, let's call it 'parent'. I have another custom content type, let's call it 'child'.

I created a template file where I can display the 'parent' content type fields any way I want: node--parent.tpl.php. By using code such as...

<?php
  print $content['field_city'][0]['#markup'];
?>

I can move fields around and customize the markup, which is great. But how would I also display the parent's children on the same page?

(I don't use Views. I create a content type template file instead because gives me more flexibility for arranging the HTML).

How are the children linked to the parent? Do you use an Entity Reference field?

Also, what do you want to display from the children? The titles? The entire, rendered nodes?

If you look up entity_metadata_wrapper (see: Entity metadata wrappers) you can see how to access an Entity Reference field.

You also may want to reconsider Views. Overriding templates for Views can give you a lot of flexibility.


Get view output without rendering (with substitutions) I've got a view that I'm accessing via code and used to pull fully rendered view code and work great. But after one of the updates (looking like 6.x-2.15 or 6.x-2.16 maybe changed it?), I can no longer reference fields that are using views' field token replacement logic. All I appear to have access to now is the text that contains the token arguments, and not the final rendered code.

This is the code that used to work:

function _custom_module_get_view_options() {
    $view = views_get_view('VIEW_NAME', true);
    $view->pager['items_per_page'] = 0;
    $view->execute();
    $view->execute_display();

    $items = array();
    foreach ($view->style_plugin->rendered_fields as $display) {
        $items[$display['FIELD_NAME_1']] = htmlspecialchars_decode($display['FIELD_NAME_2'], ENT_QUOTES);
    }

    return $items;
}

The $view->style_plugin->rendered_fields doesn't appear to exist any more in the executed view...

As I mentioned above, anything else I have tried only gets me the un-replaced text patterns.

Site is on Drupal 6, and currently using Views 6.x-2.16 but was previously using Views 6.x-2.12 when it functioned as expected.

There were several changes between these versions. If you check out Releases for Views you can see a list of changes for each version, and you can download each intervening version. I would suggest you peruse the list, and maybe roll back your current version, until you discover the specific change which broke your site. Then open an issue on the Views project page.


Making drupal_goto Ignore ?destination=foo I frequently come across cases in my Drupal 6 sites where a user might encounter my module's pages with the ?destination=foo querystring appended to the URL, from previous interactions on the site. Results of this vary from "inconvenient" to "very aggravating."

The default behavior of drupal_goto() checks for the destination parameter first, and disregards the arguments to drupal_goto() if it is present.

Is there a Drupal-native way to use drupal_goto() in a way that ignores destination?

(Yes, I know I can recreate a version of drupal_goto() in a utility function, but I would prefer a Drupal-native solution if one exists)

It's actually quite simple, just unset $_REQUEST['destination'] before you invoke drupal_goto().


Views "Load More" replacing results instead of appending Views load more is replacing the results rather than appending those below the existing ones.

I am using block for content listing and need a append more option to load more content below the existing one. I tried views show more and views load more extensions.

You can also try Views Infinite Scroll module.

  Views infinite scroll allows you to load and display pages of any view
  inline, using AJAX (this has been called infinite scrolling, load
  more, autopaging, endless pages and more). The pager can be triggered
  with the press of a button or automatically as the user scrolls to the
  bottom of the view's content.


Drupal fboauth module - how to get the friendlist of a user I have checked the friendlist field in configuration settings of the fboauth module. Now what do I do to get the friend list of the logged in user.

You need to know $access_token.

$result = fboauth_graph_query('me/friends', $access_token);

See the Facebook API for a list of commands: http://developers.facebook.com/docs/reference/api/


Adding read more link I have 1 blog block in the home page where i am displaying the title and body of the body of the blog up to 2 lines.After that I want to add read more link which redirect to the blog content type.I am using views there in the preview it is read more link is showing correctly. but not displaying in the content page.
I used this code below  in node.content type.tpl.php to display the read more link. But the read more link is not adding to the blog . but to some other content in that page.
Please suggest how to do this?

<div class="content"<?php print $content_attributes; ?>> <?php hide($content['links']); hide($content['links']['#links']['node-readmore']); print render($content); if($teaser) { print l(t('Read more'), 'node/' . $nid, array('attributes' => array('class' => t('node-readmore-link')))); }?>
 <?php print render($content['links']); ?>

Not Getting your question exactly.But if you want to add read more link in the block then why are you written the code into node tpl file.No need to writing code into tpl file.If views preview shows the link then it will definitely render on the page.Make sure you checked it as admin. If you check it as anonymous user then it may be an issue of menu permission.


drush ard fails with error Database dump failed, drush 5.10.0 drupal 7.39 sudo drush ard -v --destination=sites/default/files/sitearchive.tgz

fails with error "Database dump failed"

Initialized Drupal 7.39 root directory at /var/www/drupal                                                                                [notice]
Initialized Drupal site default at sites/default                                                                                [notice]
php /usr/share/php/drush/drush.php  --backend=2 --verbose --root=/var/www/drupal --uri=http://default  sql-conf   --all 2>&1                                              [notice]
Executing: tar  --exclude "drupal/sites" --dereference -cf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal
Executing: tar  --dereference -rf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal/sites/all
Executing: tar --dereference -rf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal/sites/README.txt
Executing: tar --dereference -rf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal/sites/example.sites.php
Executing: mysqldump --result-file /tmp/drush_tmp_1476823166_5806887e850ef/drupal.sql --no-autocommit --single-transaction --opt -Q  drupal --host=xxxxxx.ceiixl6nbq74.us-east-1.rds.amazonaws.com --port=3306 --user=xxxxxxx --password='xxxxxxxxx'
Database dump failed.                                                                                [error]
Command dispatch complete

I haven't really used Drush, but I'm working through migrating a site to Pantheon and this is the way they suggest.

Here is the output of drush status. (the xs are subbed in for identifiable info)

sudo drush status
 Drupal version                  :  7.39
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  xxxxx.ceiixl6nbq74.us-east-1.rds.amazonaws.com
 Database username               :  xxxxx
 Database name                   :  xxxxx
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  mytheme
 Administration theme            :  mytheme
 PHP configuration               :  /etc/php5/cli/php.ini
 Drush version                   :  5.10.0
 Drush configuration             :
 Drupal root                     :  /var/www/drupal
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp

Attempting to run the mysqldump command as shown in the output of the drush command (as suggested in the comments) simply returns 'mysqldump: command not found'

Can anyone shed some light on this problem? I have zero experience with drush so I'm not even sure how to troubleshoot it.

I'm happy to provide any additional information deemed useful.

If mysqldump is not found, it means that you miss the mysql-client or mysql-client-5.5 package (if you are using Debian). Your version of Drush indicates that you are using Debian as it is severely outdated ;-)


How to embed images with blocks Am newbie to Drupal this is my first question

i want to embed my images on the blocks body, so i tried below code to embed

Email :

contactus@xxx.com

          <select name="Country" class="countrylist">
            <option>India</option>
            <option>USA</option>
          </select>

i having page.tpl and page--front.tpl in my custom theme, the images are only loading on page--front.tpl, please refer screenshot

But for other pages for example user login page the images are not loading, please screenshot 2

When i inspect with firebug on the image src the url added with the "user" ,this is the reason behind why the images are not loading

http://localhost/projects/drupal/dev/user/sites/all/themes/custom/themename/images/facebook_top.png

The image links are the problem here, I think. The images are shown on the front page but aren't shown on other pages. So, on the front page it understands the image link (by adding the http://localhost/ in front of the image link you gave) but on the other pages, for example on http://localhost/node/3 it tries to show an image from http://localhost/node/3/sites/all/themes/custom/themename/images/facebook_top.png but there is no image on this address.

Therefore, use the full link (http://localhost/sites/all/themes/custom/themename/images/facebook_top.png etc).


Display Related Nodes by Taxonomy Terms in Block There are numerous articles on how to display related nodes from taxonomy. In all these articles, it states to set contextual filter: Has Taxonomy Term & select option: Taxonomy Term ID from URL.

In my case, I do not have any taxonomy term in the node URL

I want to display nodes which have common terms when the term is NOT in the URL.

I have tried the approach in many articles that require the option: Taxonomy Term ID from URL & select "Load default filter from node page, that's good for related taxonomy blocks" and further to select the Vocabulary.

I have tried this approach, however, it does not show any related content, possibly as I do not have any terms in the URL?

Please advice.

Resolved it by using the following method:

Under Advanced
→ Contextual Filter: "Vocabulary Name"
→ Taxonomy Term ID from URL
→ Load default filter from node page, that's good for related taxonomy blocks
→ Select Limit terms by vocabulary
→ Select the appropriate Vocabulary
→ Under "Multiple-value handling" Select the appropriate option as per your requirement (either "Filter to items that share all terms" OR "Filter to items that share any term".
That's it. It worked for me.


How to redirect user after login I created my site's homepage using panels(disable blocks regions)and there i placed the user login block. When a user is logged in through the block he is redirected to the homepage while if the user use user/login page he is redirected to his profile. Can i make the login through the block redirect also to the user profile?

Take a look at the Login Destination and the LoginToboggan modules. They should do what you want.
The first module allows you to customize the destination to which a user is redirected after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages, or user roles, and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.


Change content of a node What is the best practice to change content links based on a class in drupal? I want to have www.example.org transformed to some text based on foo. Should I use hook_view(), or hook_nodeapi()?

You can only use hook_view() when you are implementing the code for the module that defines a content type.

  Display a node.

  This is a hook used by node modules. It allows a module to define a custom method of displaying its nodes, usually by displaying extra information particular to that node type.

The documentation of hook_view() for Drupal 7 is clearer:

  Display a node.

  This hook is invoked only on the module that defines the node's content type (use hook_node_view() to act on all node views).

If you are writing code in Drupal 6 to alter the content of a content type implemented by another module, you can only use hook_nodeapi('alter'), for which the documentation reports:

  "alter": the $node->content array has been rendered, so the node body or teaser is filtered and now contains HTML. This op should only be used when text substitution, filtering, or other raw text operations are necessary.

As what you are trying to achieve is text substitution, this is the hook you should use.

The equivalent for Drupal 7 is hook_node_view_alter().

  Alter the results of node_view().

  This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

  If the module wishes to act on the rendered HTML of the node rather than the structured content array, it may use this hook to add a #post_render callback. Alternatively, it could also implement hook_preprocess_node(). See drupal_render() and theme() documentation respectively for details.


How can I avoid extraneous divs in my form? When I create a form using the form API, the resulting html includes all sorts of unwanted divs. For example, if I use:

$form = array(
    'myFieldset' => array(
        '#type' => 'fieldset'
    )
);

The resulting html looks like this:

<form action="/drupal-7.15/?q=chercheur" method="post" id="form-chercheur" accept-charset="UTF-8">

        <fieldset class="form-wrapper" id="edit-myfieldset">

        </fieldset>
        <input type="hidden" name="form_build_id" value="form-87Dv5ezVpaLI5mD345ofMkLgPhsv_dawudUp73ePQTc" />
        <input type="hidden" name="form_token" value="sXXINWr7rmParm0tRJoEb6QKGIH_QH-ffRSOtnvxYY0" />
        <input type="hidden" name="form_id" value="form_Chercheur" />

</form>

As you can see, two extraneous divs are added here. They are making the javascript I'm writing uselessly complicated, so I was wondering if there was a way to remove the extraneous divs. Ideally, I would like to obtain something like this:

<form action="/drupal-7.15/?q=chercheur" method="post" id="form-chercheur" accept-charset="UTF-8">
    <fieldset class="form-wrapper" id="edit-myfieldset">
    </fieldset>
    <input type="hidden" name="form_build_id" value="form-87Dv5ezVpaLI5mD345ofMkLgPhsv_dawudUp73ePQTc" />
    <input type="hidden" name="form_token" value="sXXINWr7rmParm0tRJoEb6QKGIH_QH-ffRSOtnvxYY0" />
    <input type="hidden" name="form_id" value="form_Chercheur" />
</form>

Is this possible?

The first
 is hard coded into the theme_form() function, so you can override that in your theme's template.php file if you want to. You should be aware, though, that the wrapping
 is actually there to ensure XHTML compliance; if you remove it your page will fail validation.

That said, this is the code to do it (replacing MYTHEME with the name of your theme):

function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }

  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}

The only change from the original function is the removal of the
 and
 from the last line, and the removal of the XHTML compliance comment as that no longer applies.

Overriding the fieldset theme is pretty much the same, except you'll be borrowing the code from theme_fieldset():

function MYTHEME_fieldset($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }

  $output .= "</fieldset>\n";
  return $output;
}

Once you clear Drupal's caches the extraneous markup should just disappear.


Add an enddate to my date field programmatically I'm using the date field contrib module and added it to my custom module which creates a content type and its fields.

I've successfully added a field(+instance) of date with a popupcalendar to my contenttype with a lot of help of this comment. But I can't figure out how to get the end date working. It's only showing a first date, not value2. I've tried screwing around in the field settings by adding 'enddate'=> 1 to no avail.

What setting should I use to get a start AND enddate to work in my field within my module?

Here are the fields I'm using(Its within a field collection which also works fine)

//Field collection
array(
    'field' => array(
        'field_name' => 'field_available_periods',
        'label' => $t('Available periods'),
        'cardinality' => -1,
        'type' => 'field_collection',
    ),
    'instance' => array(
        'field_name' => 'field_available_periods',
        'entity_type' => 'node',
        'bundle' => 'accommodation',
        'label' => $t('Available periods'),
        'description' => '',
        'widget' => array('type' => 'field_collection_embed'),
        'required' => 1,
    ),
),
array(
    'field' => array(
        'field_name' => 'field_van_tot',
        'type' => 'datetime',
        'label' => $t('From - Until'),
        'cardinality' => 1,
        'settings' => array(
            'granularity' => array(
                'year' => 'year',
                'month' => 'month',
                'day' => 'day',
            ),
            'enddate' => 1,
        ),
    ),
    'instance' => array(
        'field_name' => 'field_van_tot',
        'entity_type' => 'field_collection_item',
        'bundle' => 'field_available_periods',
        'label' => $t('From - Until'),
        'cardinality' => 1,
        'description' => '',
        'required' => FALSE,
        'widget' => array(
            'type' => 'date_popup',
            'settings' => array (
                'input_format' => 'Y-m-d',
                'year_range' => '-0:+2',

            ),
        ),
        'display' => array('default' => array('type' => 'date_default')),
        'settings' => array(
            'default_value' => 'blank',
            'default_format' => 'short',
            'default_value_code' => '',
            'default_value2' => 'blank',
            'default_value_code2' => '',

        ),
    )
),

Finally found it by changing the field settings' "todate":

'field' => array(
                'field_name' => 'field_van_tot',
                'type' => 'datetime',
                'label' => $t('From - Until'),
                'cardinality' => 1,
                'settings' => array(
                    'granularity' => array(
                        'year' => 'year',
                        'month' => 'month',
                        'day' => 'day',
                    ),
                    'todate' => 'required',
                ),
            ),


How do add a condition to check if created node is language source (in a multilingual site)? I need to fire a rule action when a node is created and this node is the original source in a multilingual site. This means that this node is not the translation of other node.

How do add a condition to check if the created node the original source in a multilingual site?

Check your created node if it has a $node->tnid. The tnid (translation id) would be not null if its a translation from another node.


Failed validation redirects to normal path I'm using the sub-pathauto module.

I can edit node 1 of type list from the path list/1/edit. However, when validation fails I'm redirected back to node/1/edit (the normal path).

Is this a known limitation of the module? Something I have to accept?

In your custom module add below code,It check If url not in alias path, redirect it to aliased path.

function mymodule_init() {
    if(module_exists('subpathauto'){
  $alias = subpathauto_lookup_subpath('alias', current_path(), current_path());
  if (!empty($alias) && $alias != request_path()) {
    drupal_goto($alias, array(), 301);
  }
 }
}


JavaScript supposed to always be called on front page, but doesn't always run I have some JavaScript that is called on the front page, and is supposed to execute.  When I go the page initially, it works fine.  Then if I go to another page, then come back, it doesn't show.  It does load, and after other JavaScript files it requires.  It just doesn't execute.  If I refresh, it loads again.

(function ($) {

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

            // .....

            // create the submit handler
            $('#savings-form').submit(function(event) {

                event.preventDefault();
                //alert('Form submitted xxx');

                savingsplot();

            });

            savingsplot();

        }
    }

})(jQuery);

What am I doing wrong?  I don't have any caching enabled, and in drupal_add_js(), I set cache to FALSE.

I think perhaps the issue stems from the browser's "BFCache" which is a browser feature that caches a page for quicker loading when a user presses the Back/Forward button. See below to understand more about this feature.

Try adding the following code inside of your attach function.

// Prevent the bfcache.
$(window).bind("unload", function() {});

The "BFCache" as taken from page:
https://stackoverflow.com/a/2218733/955858

To quote that post:

  The modern browsers (Firefox, Safari/Chrome, and Opera) all support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page very quickly and exactly as the user left it, which is what the user wants.

  The load event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.

  This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.

  For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and some next version of Safari (which contains the fix for bug 28758) supports special events called "pageshow" and "pagehide".

  References: http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ and https://developer.mozilla.org/En/Using_Firefox_1.5_caching.


Comment form is not working with ctools popup I want to display a comment form in popup in drupal 7 website.

I have created a custom module to display comment form in ctools modal and added a link in the views page. Comment form is displaying correctly in ctools modal but comment is not saving when submitting the form.

When we submit the comment form, it does not display any error and redirect to comment form.

I am also using Ajax comments module in the site.

Code snippets for the ctools

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

  $items = array();

  $items['modal/%ctools_js/comment-popup/%'] = array(
    'title' => t('Comment Block'),
    'page callback' => 'custom_feature_comment_callback',
    'page arguments' => array(1, 3),
    'access callback' => TRUE,
  );

  return $items;

}

/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands = ctools_ajax_command_reload();
  }

  //If form is submittedd
  print ajax_render($commands);

}

I have searched in google and follow the below reference but comment form is not saving comment.

http://internetdevels.com/blog/ctools-modal-api
https://drupal.org/node/1196150
http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7

Thanks in advance.

I have found the issue. There is #action property in comment form which was redirecting to same form when we submit comment form. So, it seems that comment form is not working properly.

I have set up a global variable to remove #action property of the comment form if comment form is displaying in ctools popup.

/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  global $comment_popup;
  $comment_popup = 1;

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
    're_render' => FALSE,
    'no_redirect' => TRUE,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed']) || !empty($form_state['ajax_commands'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands[] = ctools_ajax_command_reload();
  }

  //If form is submittedd
  return ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));

}

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

  if ($form_id == 'comment_node_article_form') {

    global $comment_popup;

    if ($comment_popup == 1) {

      $comment = $form_state['comment'];

      // If not replying to a comment, use our dedicated page callback for new
      // comments on nodes.
      if (empty($comment->cid) && empty($comment->pid)) {
        // Change the action to call our function.
        $form['#action'] = url('modal/nojs/comment-popup/' . $comment->nid);
      }

      $comment_popup = 0;
    }
  }

}


Get the ID / class of the part of the form that has been repainted with an AJAX callback? I have an AJAX form with a callback that fires some JavaScript when the form is submitted.

I need to know what has been repainted. Can I get the class / ID of the parts of the form that have been changed by submitting the form?

AJAX callback:

function _my-module_form_process_callback_js($form, &$form_state) {
  $commands = array();

  $commands[] = array (
    'command' => 'customSomething',
  );

JavaScript:

  Drupal.ajax.prototype.commands.customSomething = function(ajax, response, status) {

    console.log(ajax);

  };

By logging ajax I can see the form ID and class. However I don't belive that the entire form is being repainted. Most of the form is unchanged, its only one fieldset that changes.

I don't know if its the best solution but this works:

  Drupal.ajax.prototype.commands.customSomething = function(form) {

    var formId = '#' + form.form.context.id;

  };


Change Drupal Commerce line item titles I'm building a webshop with a lot of promotions in. And some articles in the shopping cart, have a linked promotion. And I want to show this promotion in the shopping cart summary (before the order completion).

Is there a way to change the title of the product in the shopping cart summary?

It's a shop without any visible prices. The total amount of the order is calculated on the servers... (it's a complicated proces). So there is nothing to worry about that...

But how can I display the pink text in a proper way? Would it be best to get this data from the database and place it as a field in a table (since the shopping cart summary is a view)? Or what other options do I have?

Please note that items in the cart are not products, but line_items (referenced to the product of course)

I think this hook can fit your needs, but I haven't tested it (in my situation, I added the line item directly using custom functions in my module)


Custom form that will change the hyperlink inside the email for a chosen radiobutton I would like to alter the content of an email sent to the user after someone choice form radio button list. The altered content of the email would be a hyperlink to a particular version of a software. How do I do it within the submit button with Drupal 7 ? Thanks

To send an email with Drupal, you should first use hook_mail to define the email and then drupal_mail to send it with any variables. There is extensive docs on this on the Drupal API site.


Custom sort criteria for dates in views I've got a website filled with events. Some events have a start date, others don't. I sort my events by date on the frontpage so the event closest into the future shows up first.

But their are some events with no dates. These kind of events take more than one day/week/month/... so it doesn't make sense to add a (single) date.

How can I make a list, by using views, where the dates with a date show up on top and those without close the list by showing up at the end of the page.

Any suggestions on filters or work-arounds where I can specify this kind of sorting criteria?

I haven't tested this, but I would make two views-- View A includes the events with a start date and View B includes the events with no dates.  Then, add View B as the footer to View A.  The events will now be shown on the bottom.


Running Drupal code inspections via PHP Storm returns incorrect results When I run PHP Code Sniffer inspections in PHP Storm (latest version) for Drupal code using the latest Drupal coding standards (from the Coder module), I get incorrect results. Running the inspections manually on the command line seems to return the proper results. I don't know why.

Here's the output of running phpcs manually against this test file from the CAS module:

/Users/bosborne/.composer/vendor/bin/phpcs --standard=/Users/bosborne/.composer/vendor/drupal/coder/coder_sniffer/Drupal tests/src/Unit/Subscriber/CasSubscriberTest.php

FILE: ...ules/contrib/cas/tests/src/Unit/Subscriber/CasSubscriberTest.php
----------------------------------------------------------------------
FOUND 11 ERRORS AND 4 WARNINGS AFFECTING 15 LINES
----------------------------------------------------------------------
  16 | WARNING | [x] Unused use statement
  99 | ERROR   | [x] Expected "MockCondition" but found
     |         |     "MockCondition;" for @var tag in member variable
     |         |     comment
 131 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 132 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 133 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 134 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 135 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: ]
 148 | ERROR   | [x] There should be no white space after an opening
     |         |     "["
 149 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: ]
 162 | ERROR   | [x] There should be no white space after an opening
     |         |     "["
 163 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: ]
 177 | ERROR   | [x] Object operator not indented correctly; expected
     |         |     6 spaces but found 35
 193 | ERROR   | [x] Object operator not indented correctly; expected
     |         |     6 spaces but found 28
 194 | ERROR   | [ ] If the line declaring an array spans longer than
     |         |     80 characters, each element should be broken
     |         |     into its own line
 564 | ERROR   | [x] Inline comments must start with a capital letter
----------------------------------------------------------------------
PHPCBF CAN FIX THE 14 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Lots of errors and warnings!

But when I configure my PHP Storm (latest version) to run the inspections on the same file, I get just two weak warnings, and the filedoc one it complains about is wrong (file docs are not required on namespaced files).

So something is out of wack here, but for the life of me I cannot figure out why PHP Storm is returning the wrong output.

Environment info:

Using version 8.x-2.9 of the Coder module
Using version 2.7 of phpcs
Code Sniffer is setup in PHP Storm using the same exact path that I use when running the command manually (see config image below)
Inspections are setup in PHP Storm to use "Custom" inspections and I proide the path to the Drupal coding standards (the same path that I use when running it manually)

EDIT: I also filed an issue with PHP Storm directly: https://youtrack.jetbrains.com/issue/WI-34029

OK - Embarrassingly enough, this was indeed "user error". The path to the coding standard that PHP Storm was using was indeed slightly different than the path I thought it was using. The paths were quite similar so I didn't catch it during my own reviews.

What helped is that you can configure PHP Storm to output the exact command it runs in the debug log by doing the following: Open Help > Debug Log Settings and add there com.jetbrains.php. Then run the inspection and look at the debug log.