301 redirect one site in multi-site installation I have a drupal 6 installation that is hosting numerous sites. They're all located in the sites/ folder. Like: sites/site-1 sites/site-2, etc.

One of these sites has been discontinued, and we need to redirect from it to a new domain name.

Placing a .htaccess file in the sites/site-1 folder does not work.

How can I redirect ONLY THIS ONE SITE out of a multisite installation to a new domain name?

In the root .htaccess file is a set of rewrite rules. You can add a rule to that to redirect to the new site.

RewriteCond %{HTTP_HOST} ^www\.olddomain\.com
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

untested, but should be about right.


Calling menu in a certain way from page.tpl.php My menu structure looks like the structure in the left part of the image. I want the output to look like the right part of the image when I'm in the 'oranges' page for example. This works great if done from Drupal's admin panel, but is there any way I can code it in my page.tpl.php?

Currently, I'm using the code below to output my menu, but I can't seem to get it to look exactly the way I want.

<?php
  $main_menu = menu_navigation_links('main-menu', 2);
  print theme('links', array(
  'links' => $main_menu,
  'attributes' => array(
  'id' => 'main-menu',
  'class' => array('links', 'clearfix'),

),

  'heading' => array(
  'text' => t('Main menu'),
  'level' => 'h2',
  'class' => array('element-invisible'),
),
));
?>

Any ideas?

You can use menu_tree_all_data function to get all nested menus. And then you can add your own html to display menus with your style

$menutree_produce = menu_tree_all_data('menu-produce');

And if you want to Active current menu on related page you can use menu_get_item and menu_set_item on that page

$menu_item = menu_get_item(drupal_get_normal_path('produce/oranges'));
menu_set_item(NULL, $menu_item);


How to change webform default email address from sender side? I'm using webform module, when somebody submits the form mails will go from address which we mentioned in the custom field, this works fine.

But instead of adding in custom field, I want to change the default from email address. Is there any way to do this?

For reference follow this image:

You can usually find a configure link in the module list.

Looks like in /admin/config/content/webform

and scroll down to default e-mail values.

(For Drupal 6, go to yoursite.com/admin/settings/webform)


Theming output of node_view I'm printing the output as described in here: How to programmatically render a node's teaser using the theme layer? in block using PHP filter.

Also I've a theme implementation file named: views-view-field--field-image.tpl.php in the custom Mobile theme directory with this content:

<?php

?>
<?php /*print $output;*/ ?>

This is hiding all image field output but not the output of drupal_render($view).

How to hide the images in this redered output as well?

Before calling drupal_render($view) inspect the $view array. (Use devel's dmp or print_r to inspect the array.)

Find out what part of the array contains information about your images, and then unset this before calling drupal_render.

E.g.

unset($views['my-image-field']);
print drupal_render($view);


view inside a view with different arguments I try to create a view with NID argument and embedd inside as a field another view with totally ditfferent argument. I used module called views_field_view but it seems that parent view is passing arguments to child view, which cause to break arguments on child view- that is what I do not want. Is it possible to do such combination? Thank you

What I try to do: I try for days to come up with some decent solution to this problem: On each node there is a multivalue field (field_ref) for referrencing 2 nodes (can be left empty as well). Also each node contains another field for (field_par) referrencing parent node. Moreover, each node has taxonomy term.
Now, on current node NID I need to display referenced nodes from field_ref. If the field is empty I need to display the values from the same field - but this time from a node that is referrenced in field_par on current node. If this field is empty, it should display values of the same field but from field_par of the parent node etc. until the node with top term is reached.
My solution was fairly simple - Argument - Content: Has taxonomy term ID (with depth) set to minus values so I get all terms all the way up. Add relationship to field_ref and connect it with fields - for example title. This way I get all results coming from parent nodes with higher taxonomy terms. Then I restrict results only to 2 results and add sorting according to custom integer field that I created on taxonomy terms according their depth (currently there is no other way to sort terms according to their depth) And that is it.
Problem with this solution is that I am not able to get inside current node values because adding another argument like NID breaks functionality of taxonomy argument.

I was also proposed another solution: to add NID as main argument and to get values from parent nodes using combined relationship : Content: Taxonomy terms on node + Taxonomy term: Parent term + Taxonomy term: Content with term. Which works ok but this view is static.

Finally what came to my mind was to combine view with my solution as a field inside a view with NID argument. So that the main view would display current node fields and if empty, it would display the field with embeded view refults. But maybe the solution can be much simpler and I am overcomplicating it:)

I can't immediately think of a simple solution to this problem, but I also don't have VFV installed anywhere, so I can't play around with it at the moment.

What I would probably have done, is created a ctools content type, called both of the views, and manually rendered through a specific template afterwards. This solution however is non-trivial, so perhaps you will need to search for a different one.

See What are Ctools plugin (content type, access, etc), and how does one create them? for info on implementing ctools content types.

Example of adding a specific template on top: Correct way to render a modules output through a template?


How to add a css class to view fileds i have created a view block and added some fields to it,i want to change the style of those fields with css, is there a way that i can do it.
"Thank you"

Click on the field you want to add a css class to, select style settings, and customize field html and check create a css class. Give it a name and simply add the class to the css file of your theme


Apply hook_menu to all nodes except node593 I have 2 separate hook_menu callbacks going on in my code.

I want to apply a function to all nodes and then for node593, I want to apply it's own function but I can't seem to do this.

The function for the % wildcard seems to work for all nodes, including 593.

Anyone know how I can get past this ?

You're probably overthinking it; making that decision in the page callback seems like the easiest solution:

function MYMODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MYMODULE_node_page';
}

function MYMODULE_node_page($node) {
  if ($node->nid == 593) {
    return node_page_view($node);
  }
  else {
    // ...
  }
}


Maintain same node ID's when importing nodes I am using Node Export with Features module, and then importing content while installing my profile. All works fine, but I want the node ID's to be retained while importing. I want it to be in same order as the source site.

Can I do this?

In short no (not easily/safely anyway).

If you're looking for specific content ID's, you may want to look into putting the UUID module on your source/destination site.  As far as I'm aware, this will allow you to keep a unique identifier on your nodes that match across sites, even though the node ID's will be different.


How to update users table including relation tables with entity? I'm currently creating a module which should help me manage users from 1 instance for my other multisite instances.
So there will only be admins/editors and no other user logins.
My goal is now to hook the user create / update function and save same datas on all other databases.

But i'm not able to bring it work.

I started with the update hook because i think it's easier. Here is module function and one of my try:

/**
 * Implement hook_entity_update.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 */
function my_module_entity_update($entity) {

  if($entity->getEntityTypeId() === 'user') {
    $sites = glob(DRUPAL_ROOT . DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);

    foreach ($sites as $site) {
      $siteName = str_replace(DRUPAL_ROOT . '/sites/', '', $site);
      if ($siteName !== 'default') {
        Database::getConnection($siteName)
          ->update('users')
          ->fields($entity->getFields())
          ->condition('type', $entity->getEntityTypeId())
          ->condition('id', $entity->id())
          ->execute();
      }
    }
  }

}

But here i get the error because the $entity->getFields() returns an object instead of an array.

How can i save the whole user entity at once including the roles and other related tables?

Do i really need to assign every single field? Or is there a hopefully easier way?

Long answer short: You can't save them at once and have to synchronize the user fields manually.

Users are fieldable entities and field data is stored in different tables. So in your case you'd have to create all fields you like to synchronize in all your sites and you need to read them from your base site's user entity field by field and write them to the according tables of your target sites.

A very error prone approach on database level (not mentioning the complexity with a growing number of attributes/client sites).

I strongly suggest a less low-level solution. E.g. by utilizing Drupal's REST services, considering OAuth2/OpenID server/client, LDAP or SAML for user authentication. (Just some keywords to use Google with; there are some contrib D8 modules in heavy development for all of these approaches.)


Module that allows access to node based on roles Is there a module that lets me simply select the roles that can have access to a node as I create it?

For example, I have a role named "BUG", I want BUG to be able to access node/5, but not any other role (including authenticated users).

I've been looking and looking and can't find anything.

Drupal offers a wide selection of node access modules.

Many (but not all) of these offer role based access control.

While still only in beta for D7, Content Access is a module I personally use for role based node access control. I regard it as stable for role based access control.  However do not use it for lower resolution (user based) access control, as this mode is not yet stable.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

One of the advantages by this module is that it is fairly straightforward to control access to individual nodes by role.


Javascript translation broken - fixed after cache clear I just encountered a problem with the javascript translation. I have a javascript file where I generate small UI elements using jQuery, and I wrap the label in the Drupal.t function. The site is multilingual NL/FR So e.g.:

$('input.button').val(Drupal.t('Dwork'));

For some reason the translation failed; I only got out what I put in: Dutch in this case. After clearing the Drupal cache everything seems to be back to normal. I assume somehow the generation of the french translation js file failed, but I'm unsure how this could have happened.

Anybody know what could cause this, or how to pro-actively refresh the cache?

You can refresh the cache with drush: drush cc css-js to clear only Javascript (the admin module allows you to do this from config), or you can just go to performance and clear all the cache.

It does seems like clearing cache is important in these cases:
https://www.drupal.org/docs/7/api/localization-api/translating-strings-in-javascript


Allow user to fill out node form, then force registration I'm making a classified website.

Have a button that say "Make a ad"
I would like the Anonymous  user to be able to
fill in the text for the ad.

But the  Anonymous users after filling in advert.
has to sign up for the ad to be posted

How can  do this with drupal please?

many thanks for your help

Best Regards
Charles

There are many ways to achieve this. Two suggestions:

Check out the Rules module. There's a tutorial for your use case described here.
Or use one of the modules already available, e.g. Inline Registration.


How to show images below a select box according to the value? Let's say I have a select box with values : 1, 2, 3, 4, 5, 6. Every value has it's own image, which I want to display as a description below the select field. Any Drupal / AJAX way to show this?

By the way this is NOT a custom form. This is a node creation and edit form.

As far as I know there are no ready made solutions for this, and you will need to write a custom module. The way to do this would be to implement hook_form_alter to modify the select element and add a #ajax property.

If you've never written a module with hook_form_alter then this article might be of help: very-introduction-drupals-hookformalter

And here are some relevant questions on Drupal answers:

adding-ajax-to-existing-node-form
how-to-use-ajax-in-form-alter-in-drupal-7


How to set Blocks settings in a Drupal Installation Profile? Is there a way to have my blocks pre-assigned a region and also enabled / disabled in a profile installation? I don't want to go to the structure / block page and assign these blocks individually each time, but would rather have them setup on site installation.

You can use hook_block_info inside your custom module to add all of your blocks programmatically. Look at this SE Post for an example to use the hook_block_info to assign it to the right region and also enable/disable it by declaring status=>true/false.


Aggregating by date field I've been trying to aggregate (SUM) by a date field with a custom format (YYYY, MM) but its not working as expected. I tried Views Date Format SQL and Merge rows modules but didn't work for me. Also, some other suggested solution is to group by field (Table settings) which also does not fit my needs.

2014-08-05     12
2014-08-05     15
2014-08-15     20
2014-09-09     10

Im trying to do it as follows:

2014,Aug      47
2014,Sep      10

Note: My collected dates attributes are year, month , day (i.e. 2014-08-05 00:00:00)

I recommend trying the Views Aggregator Plus module. It supports many useful aggregation functions. As an exmaple creating the following output:

Industry    Companies             Turnover
Food (2)    Heiny, McRonalds      $566,000,000
Clothing (1)Cenneton              $99,000,000
IT (2)      AcquiB, PreviousBest  $30,000,000
Totals              5             $695,000,000

From this source table:

Industry    Company Name    Turnover
IT          AquiB           $25,000,000
Clothing    Cenneton        $99,000,000
Food        Heiny           $66,000,000
IT          PreviousBest    $5,000,000
Food        McRonalds       $500,000,000

  With the grouping taking place on, say Industry, and aggregation
  functions TALLY, ENUMERATE and SUM applied on Industry, Company Name
  and Turnover respectively, the final result with a descending sort on
  the last column will display like below. Note that the module
  identified three groups. It also added a totals row, Views Calc style.


Quickest Way To Create a Pre-Register Form I'm looking to allow users to "Pre Register" for a new site (actually I'll use this for a standard 'template' process), I want to get users to sign up so I can keep them informed of news, updates etc on launch and want to get this function installed quickly. I'm not really want to 'hack' template.php at this stage (later maybe with ongoing development) so just need a really simple approach which will sign them up, subscribe to a newsletter and give registrants the normal 'subscribe/'unsubscribe' from within email contents. I have two roles, so can code the layout with simple "Sign Up" links going to relevant registration forms. In your opinion, what would be the best approach, maybe I should use a Rules structure (and tie in things like Coupon Codes/incentives) or would you suggest a different process?

PS:
Just like to add, that I use a process for pre-registration users to sign as up as such: 1st level - as a 'temp' role, then the user cannot go any further until they join one of either 2 roles (one free, one paid for services).

In following the accepted response below, I'll set the Notify up for a 'temp 'user then the user can choice on 'launch'  the Role route they wish to sign up for. Hope that helps readers. (-:

What you suggest (using Rules for this) is far too complicated for me.

To do this with the minimum hassle, I would just set up a standard Drupal site and create a fixed front-page that says: "Pre-register for my great new site."   Configure permissions so that if the logged in user doesn't have admin permissions, all he/she is allowed to see is this fixed front page.

Then use String Overrides to replace the text "Create new account" in the login box with the text: "Click here to pre-register".  I.e. the by "pre-registering", the user really creates a standard account on the site.

Then auto-subscribe everyone that pre-registers to a newsletter (for a newsletter module you can, for example, use  Notify). This will let you post updates on the site about the ongoing development, etc. that also are automatically sent to those who've pregistered as a digest newsletter e-mail.  (Notify let you auto-subscribe new users and also has a master switch to make subscribing and unsubscribing a breeze).

Later, when you've done setting up the site, you can ask the user to confirm his/her committment by ticking some field in the user profile, and silently convert those that confirm to regular users by given additional access permissions (and delete the rest).

Disclosure: I am the maintainer of Notify.


Accessing imagecache path inside template I'm using the ImageField module together with Imagecache to display a picture for one of my content types.

To display the content body I'm using Contemplate, I'm accessing the path to the image in the following way:

'[...]/imagecache/[preset]/[...]/'.$node->field_picture[0]['filename']

This usually works, but it breaks when someone uploads a picture with the same filename as the existing one. The file itself is then automatically named filename_0.jpg instead of filename.jpg, but the filename variable of the ImageField I'm accessing stays filename.jpg.

This of course leads to the old image being displayed. It seems the filename variable does not do what I expected, what would be the correct way to access the Imagecache generated files?

Using the Contemplate module is not recommended since it puts PHP code into the database which is generally considered a security vulnerability and non-performant.

You want to use theme('imagecache', ...) instead, which will return the HTML img tag with the proper path.


Features auto delete field I've been using Feature to provision changes between my DEV, STAGING and LIVE sites.

What I'm finding is when I make a field redundant on a node type on my DEV site, features does not automatically delete is on my STAGING site.

For example: I originally had a field called Key Contact in my Basic Page node type. I created a feature which I uploaded to my STAGING site, the Key Contact field was created and it worked fine.

However, that same field is now redundant. I have deleted it on my DEV site. I re-created the Feature and uploaded to my STAGING site.

The problem is the Key Contact field still exists on the STAGING version of my website.

Can anyone give me some direction to get Features to not just create new fields but remove fields I have deleted on DEV - so I don't have to delete a lot of fields manually on both STAGING and eventually the LIVE site?

As declared in https://www.drupal.org/node/649298#comment-7710069 there won't be any such support in Features module itself. In the same issue, there is also relevant answer in https://www.drupal.org/node/649298#comment-10219951:

  You can instead add a hook_update_N function to a custom module and delete the field with code (see field_delete_field).

This should be used in my_feature.install file. Note that if you go this way, you will probably need to add something like

function my_feature_features_export_files($module_name, $export) {
  if ($module_name == 'my_feature') {
    return array('my_feature.install' => array('file_path' => 'sites/all/modules/my_feature/my_feature.install'));
  }
}

to you my_feature.module file. This ensures that my_feature.install file is added to feature on any further export.


Content types and modules I am new to Drupal and unsure how to add a module to a custom content type. I am currently trying to add the Field Quiz module to a custom content type on Drupal 8. Is it possible for someone to explain how I can do this?

In the context of the question, Field Quiz simply provides a new field type/widget, so you have to edit the content type and add a new field using that type. It will be available after enabling the module.


Adwords conversion tracking on Ubercart store with payment gateway? is it possible to implement Adwords conversion tracking so that it takes into account conversion that come through payment portal (Customer leaves site for a moment and returns after payment, usually conversion is not tracked due leaving site for a moment)?

I have injected adwords tracking code to order completion page but it tracks only orders that come with billing option (customer does not leave the site).

If this is not possible, is it possible to inject code to order review page, if so how? (This is bad as some customers wont complete order so leads to false conversions. Also we are planning skipping order review page for billing)

You have to make users come back to your site adding this query string in the URL:

?utm_nooverride=1

Then Google will discard referral modification caused by leaving the site.

See this question.

You will have to deal with your payment gateway to modify the return URL, I think.


Display the full URL of the home page? Is it possible to display the full, absolute URL of the home page in Drupal 7, like  www.example.com/The-best-example-possible ?

I'd like to display the full URL of the home page, not just the hostname.

In Drupal 7, The front page is normally set via system_site_information_settings().  It is an unaliased URL, so it is best to use the API.  I would do it as:

$home = url(variable_get('site_frontpage', 'node'), array('absolute' => TRUE));

In Drupal 8, there is a special route <front> that you can use with the Url() object

use \Drupal\Core\Url;

$home = Url::fromRoute('<front>')->setAbsolute()->toString();

However, in most circumstances you don't need to explicitly render out Url() objects as strings; you can just use the object itself.


How can I disable or hide warnings and errors shown in the backend? Is there a way to disable or hide warnings and errors shown in the backend? For example when a user creates a node and some error occurs on the live page (image or helper class not found), then there is a big red box with around 25 lines of error message on each page in the backend.

For my editors who have to write 100 nodes a day it's very annoying.

Edit:

logging & error -> error messages is set to display NONE.

You actually should fix the error.

And since it's not a very good idea to globally disable all errors and warnings for all roles, please use Disable Messages to disable error messages based on configurable conditions.

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

  Features

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


set up triggers for items Any way to set up triggers for items in their cart  to remind buyer to check them out after 30 days?

Yep:

Commerce Abandoned Cart Notification

  This module allows you to notify your customers by email about their abandoned their cart.

It's in dev so be warned; I'm not aware of any other pre-existing solutions, but writing your own module for this would also be a pretty straightforward option if that module doesn't work for your needs.


Language paths per country- how to redirect users to their respective language's path on login? I have a website that is available in both English and Japanese.

English is the default language and has a path prefix of "en".

Japanese has a path prefix of "ja".

Users can log in from the front page via a block.

If a user whose account is set to Japanese lands on the English front page and logs in, he/she will be taken to /en/mylogindestination instead of /ja/logindestination.

How can I redirect users with Japanese-language acconts to /ja/mylogindestination (and users with English-language accounts to /en/mylogindestination)?

I already have a number of login-related fixes in Rules so if this can be done in Rules that would be a plus, but a custom module is also ok.

function module_user_login(&$edit, $account) {

     drupal_goto($user->language."/logindestination");

    }

Also, iirc, if your user has a language set, you can set one of the language detection method's to be "user preference", which would kick them over to the correct language after login.


Update query not working for db_update and db_query("update I'm trying to update a field using the Drupal's bootstrapped db_update or db_query library functions for PHP. However, neither of them are working. IF I RUN THE QUERYS MANUALLY, THEY WORK.

These two queries are the exact same. They are equivalent to doing

update field_data_field_department set delta = 4 where entity_id = 10568 and delta = 0;

Please tell me what I need to do to execute this query from PHP and make it work.

db_query("update field_data_field_department set delta = $highest_delta where entity_id = $entityID and delta = $i");

OR

            $num_affected = db_update('field_data_field_department')
              ->fields(array(
                'delta' => $highest_delta
              ))
              ->condition('entity_id', $entityID)
              ->condition('delta', $i)
              ->execute();
            echo "num_affected: $num_affected\n";

num_affected returns 1 every time.

Here is the state of the database before the query is executed.

MariaDB [db]> explain field_data_field_department;
+----------------------+------------------+------+-----+---------+-------+
| Field                | Type             | Null | Key | Default | Extra |
+----------------------+------------------+------+-----+---------+-------+
| entity_type          | varchar(128)     | NO   | PRI |         |       |
| bundle               | varchar(128)     | NO   | MUL |         |       |
| deleted              | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id            | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id          | int(10) unsigned | YES  | MUL | NULL    |       |
| language             | varchar(32)      | NO   | PRI |         |       |
| delta                | int(10) unsigned | NO   | PRI | NULL    |       |
| field_department_tid | int(10) unsigned | YES  | MUL | NULL    |       |
+----------------------+------------------+------+-----+---------+-------+
8 rows in set (0.08 sec)

MariaDB [db]> select * from field_data_field_department where entity_id = 10568;
+-------------+--------+---------+-----------+-------------+----------+-------+----------------------+
| entity_type | bundle | deleted | entity_id | revision_id | language | delta | field_department_tid |
+-------------+--------+---------+-----------+-------------+----------+-------+----------------------+
| node        | person |       0 |     10568 |       25093 | und      |     0 |                   39 |
| node        | person |       0 |     10568 |       25093 | und      |     1 |                   30 |
| node        | person |       0 |     10568 |       25093 | und      |     2 |                   41 |
| node        | person |       0 |     10568 |       25093 | und      |     3 |                   38 |
+-------------+--------+---------+-----------+-------------+----------+-------+----------------------+
4 rows in set (0.00 sec)

Try something like this, It should work.

$num_affected = db_query("UPDATE {field_data_field_department}
SET delta=:highest_delta
WHERE entity_id=:entity_id AND delta=:delta
", array(":highest_delta" => $highest_delta,":entity_id" => $entityID,":delta" => $delta))->fetchAll();


Store the values of a views exposed filter Form I have build a form using the Form API that adds a checkbox to every row in my custom view (the view page can be found here: http://goo.gl/Pg6Ja7).
I want this form to store the values even after I change the exposed filter of the view or change the view page.

I was thinking to create a new submit button that will store the values on the current page, but I don't know how to do that, I googled the whole day. Or maybe some JavaScript ?

I added the View form with a handler, here is the simple code I wrote for it:

/**
   * @file
   *
   * A Views' field handler for adding a checkbox.
   *
   */
class files_download_links_mail_field_handler_checkbox  extends views_handler_field {
  function construct() {
    parent::construct();
    $this->additional_fields['nid'] = 'nid';
    //$this->additional_fields['field_file_download_link'] = 'field_file_download_link';

  }

  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  function render($values) {
    // Render a Views form item placeholder.
    // This causes Views to wrap the View in a form.
    // Render a Views form item placeholder.
    return '<!--form-item-' . $this->options['id'] . '--' . $this->view->row_index . '-->';
  }

  function views_form(&$form, &$form_state) {
    // Create a container for our replacements
    $form[$this->options['id']] = array(
      '#type' => 'container',
      '#tree' => TRUE,
    );
    // Iterate over the result and add our new field to the form.
    foreach($this->view->result as $row_index => $row) {
      // Add a checkbox field to the form.
      $form[$this->options['id']][$row_index] = array(
        '#type' => 'checkbox',
      );
    }
  }

   /**
   * Form submit method.
   */
  function views_form_submit($form, &$form_state) {
    // Determine which nodes were selected.
    $selected_items = array();
    // Iterate over the view result.
    foreach($this->view->result as $row_index => $row) {
      if ($form_state['values'][$this->options['id']][$row_index] == 1) {
        $selected_items[$row->{$this->aliases['nid']}] = $form_state['values'][$this->options['id']][$row_index];
      }
    }
    // Grab the nodes
    $nodes = node_load_multiple(array_keys($selected_items));
    dpm($nodes);
  }
}
?>

Thanks!

This seems like the perfect scenario for a custom module in my opinion. I know it's possible to get this working based on some light research I did (specifically this web page).

Your solution is using a custom module anyway, best to create the form and hooks and sql in the custom module and remove your dependency on views.

Create your hook_menu:

function MODULE_menu()
{
    $items['PATH'] = array(
        'title'            => t('TITLE'),
        'description'      => t('DESCRIPTION'),
        'page callback'    => 'drupal_get_form',
        'page arguments'   => array('MODULE_form_function'),
        'access arguments' => array('access content'),
        'type'             => MENU_NORMAL_ITEM,
    );

    return $items;
}

Create your form function (using the Form API and Database Abstraction Layer):

function MODULE_form_function($form, &$form_state)
{
    // handle creation of your form, including sql to replace views.

    return $form;
}

Create your validate and submit handlers:

function MODULE_form_function_validate(&$form_state)
{
    // handle the validation of your form
}

function MODULE_form_function_submit(&$form_state)
{
    // handle the submission of your form
}

This is a much simpler and proven way to accomplish what you are trying to do.


Zen theme not showing second level menu items I am creating a zen sub-theme and I edited the menu called "Main menu" to have on root level item that has 5 children (second level). The root level item shows up fine but none of the children are ever output in the HTML.

I verified they are all enabled. Just not sure why they aren't being sent back to the client. Does the Zen theme need some modification to support menus that are deeper than one level?

Edit your page.tpl.php

Edit the section where the primary_links are printed to show the whole primary links menu instead of only showing the first level links of your primary links menu.

<?php if (isset($primary_links)) { ?>
     <div id="primary_menu">
<?php print theme('menu_tree',variable_get('menu_primary_menu',0)); ?>
     </div>
<?php } ?>

In Drupal 6

<?php
$menu_name = variable_get('menu_primary_links_source', 'primary-links');
print menu_tree($menu_name);
?>

Drupal 7

<?php

    $menu_name = variable_get('menu_main_links_source', 'main-menu');
    $tree = menu_tree($menu_name);
    print drupal_render($tree);
?>


Twig whitespace controls have no effect on fields I am trying to iterate over a Paragraph field and apply a comma after each Paragraph item.

In the field template that outputs the Paragraph, I am trying:

{%- for item in items %}
  {{ item.content }}{{ not loop.last ? ', ' }}
{% endfor -%}

This puts the comma out, but there is a ton of whitespace all over:

I have tried many whitespace control combinations and none seem to have any effect.

How can I remove this sort of behavior entirely? The paragraph field is an entity reference, that renders a view mode, so I don't want to install field delimeter plugin.

edit: Tried the solutions mentioned here:

How remove whitespace on field in twig?

and here:

https://craftcms.stackexchange.com/questions/2789/whitespace-created-when-using-if-statements

as well as in the documentation.

The structure is as follows:

Node -> Paragraph field -> Paragraph (Entity) -> User Reference + Plain text field + rich text

In this context, only the user field is being rendered, and I want to put a comma at the end of each linked name.

Although the whitespace control modifier is supposed to work for all {{ … }} prints, {% … %} statements and {# … #} comments I'd expect to make your sample work it needs to be put directly into the print like that:

{% for item in items %}
  {{- item.content -}}{{- not loop.last ? ', ' -}}
{% endfor %}

Alternatively you could try to use the {% spaceless %} tag. But again, I'd expect this only works right when placed inside the loop:

{% for item in items %}
  {% spaceless %}
    {{ item.content }}{{ not loop.last ? ', ' }}
  {% endspaceless %}
{% endfor %}

  As of Twig 1.38, use the |spaceless filter instead.


Allow users to uploading videos to vimeo I am totally new at making websites using Drupal. I started on Monday (April 1st) and I've been using drupal.org and drupalize.me to start learning and building some basic stuff.
There is one thing I want to do and I've been stuck for 2 days now.

I want to be allow the users of my site to upload videos which will get stored inside my database and, using the data from my database, upload it to Vimeo site and use vimeo player as the player.

This is my goal right now but I am stuck on the very first step TnT.
I have the module "Media-7.x-1.3" installed on my site and tried using it to upload videos. I know this only allows me to upload videos from the admin end when you are creating a new content and you have to edit the "article" or "blog" post that contains the video file if you want to change something and doesn't allow the users of my site to upload the videos directly but I just wanted to get started on something.

So I followed the instructions and went to
- Structure -> Content Types -> Add content type -> name the content type (video files) -> save and add fields (everything else is left as default) -> add new field (upload videos) -> field type = file -> widget = media file selector -> save -> upload destination = public files (there are no other options for me to choose) -> save

this will bring me to manage fields page
label = upload videos -> allowed file extensions for uploaded files = mp3, mp4, wmv, jpg (i gave it bunch of random extensions so I can test it if it works or not) -> maximum upload size = 50 MB -> every other fields are left as default -> save

inside manage display page
upload videos format = rendered file -> save

after all the configurations, I go to
Add content -> video files -> title = videos -> click on "Select media" at the bottom -> Browse -> select my video file I want to upload (mp4 file, 34 MB) -> Submit
and nothing happens. no error message, no video uploaded or anything. I'm just stuck in the upload overlay page and I would have to hit cancel to get out of the page.

but if I try to upload a image file (jpg file that I allowed earlier), I can see the preview of my image and gives me an option to "Select media" or "Remove media" (the upload overlay page is gone of course).

So I have no idea why it's not working for video files or what is going on. AND this is not even what I want to do...sigh...

Please help me TnT

Thanks!

I don't believe uploading directly to Vimeo is a supported feature. I do see an unmaintained module that claims to do something similar, though: http://drupal.org/project/mm_vimeo

I haven't looked at the code, but you could write a module to accomplish the following:

Use a regular file upload field for videos. Nothing fancy. Use the Media module to enable URL video embedding (as if we've copied/pasted a Vimeo URL directly).
Create a cron job to keep an eye on nodes created/updated of that type, making note of videos that should be uploaded to Vimeo.
Upload videos to Vimeo (see: http://developer.vimeo.com/apis/advanced/methods#vimeo-videos-upload)
Modify the Video nodes to include a Vimeo URL to embed in the player.
Remove the file upload, chances are it's huge and not worth retaining.

I've used a modified approach with this in the past with transcoding services in conjunction with Amazon S3 storage and Cloudfront CDN hosting. Very good combo.


Changing page orientation of a pdf of a views generated by the Print module The Print module (https://www.drupal.org/project/print) allows users to generate a PDF of nodes, views and panels. It allows for the selection of a default page orientation (portrait or landscape), and it allows for administrators to override the default orientation in specific nodes.

However, I can't figure out how to override the default orientation when creating a PDF of a specific Views output. I have one View that needs to be printed in landscape format, the rest in portrait. Perhaps a PHP snippet in the header of the view?

Any help will be appreciated!

If you used MPDF as your library then add this function to your themes' template.php:

function MYTHEME_print_pdf_mpdf_alter(&$mpdf, $html, $meta) {
  //return;
  if(is_view_path()) {
    $paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
    $format = $paper_size . "-L";
    // set document information
    $mpdf = new mPDF('UTF-8', $format);
    $mpdf->SetAuthor(strip_tags($meta['name']));
    $mpdf->SetCreator(variable_get('site_name', 'Drupal'));
  }
}

I could not find a way to alter the paper orientation after the object was instantiated, so I opted to just create it again (orientation is set in class creator).

You should then implement a function called is_view_path that returns true if it detect the printpdf path of the view, so that the code only runs for your specific view.

function is_view_path() {
  $path = current_path();
  return $path == 'VIEWPATH'; // just add your view path here
}

If you used TCPDF you should look at the function print_pdf_tcpdf_print_pdf_generate in print-pdf-tcpdf.page.inc at how to instantiate the $pdf object, and then implement an alter hook similarly to what I did above. I could not do it as for some reason I cannot get the tcpdf library to detect.

For DOMPDF I could not find an alter hook.


User's to edit roles and permissions for any user less privileged Our website needs to allow staff (staff role) and editors (editor role) to be able to edit the accounts and roles of authenticated users and all other users with roles less privileged than their own role, without being able to edit the accounts and privileges of users of a higher privilege level.

Here is an example of hierarchy of our user roles:

admin (super-user, developer only)
editor (organization's admin and non-development high-level user, many privs)
staff (organization's staff users, some special privs)
member (user with special access privs)
authenticated user (regular user)

Currently, if I allow users to edit user accounts and assign roles, they are able to not only assign themselves to top-level administrator account, but also de-assign the administrators and change their passwords, etc.

This post asks a similar/related question which is slightly different but also does not have an answer. I assumed the Drupal Core had a built-in functionality that allows for this by considering the order of roles, so I am wondering if I did something wrong.

Drupal core doesn't have any out of the box functionality to manage roles and permissions in a hierarchical manner.

However, there are a couple modules that provide extra permissions which might be helpful in what your trying to achieve.

Role Delegation gives you a new set of permissions which are very fine-grained. From the module page-

  For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.

Administer Users by Role. From the module page-

  This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

From the readme of the module-

  NEW PERMISSIONS

  Access the users overview page
  See the list of users at admin/people.  Only users that can be edited are shown.

  Create new users
  Create users, at admin/people/create.

  Edit users with no custom roles
  Allows editing of any authenticated user that has no custom roles set.

  Edit users with role XXX
  Allows editing of any authenticated user with the specified role.
  To edit a user with multiple roles, the sub-admin must have permission to
  edit ALL of those roles.  ("Edit users with no custom roles" is NOT needed.)

  The permission for cancel work exactly the same as those for edit.

(1) should give what you need but still including (2) which might have a new permission that you wouldn't want to miss out on.


How do I handle special characters? I use the Display Suite module and I enabled the Display Suite Format module. I use a code field to display a node/edit link, with the following code:

  if (node_access('update', $entity)) {
    print l(t('Modifier'), 'node/' . $entity->nid . '/edit?nid=' . [node:field-construction-fdr-ref:nid]);
  }
?>

The resulting URL is http://localhost/node/11430/edit%3Fnid%3D11419, leading to a Page not found error. I wish to get http://localhost/node/11430/edit?nid=11419.

I tried / before ? and =; I tried &_#63; for ? and &_#61; for =.

How can I get the URL I need?

Query params should be passed to the function in a keyed array:

$query = array(
  'nid' => 123,
  'foo' => 'bar',
);
$params = array('query' => $query);

print l(t('Modifier'), 'node/' . $entity->nid . '/edit', $params);


How do I enable PHP extensions on CentOS to finally finish installing/configuring Drupal? I am trying to install Drupal 8.0.5 (a standard profile) on Apache 2.4.6 on CentOS 7, with PHP 5.6.19.  But in the GUI, I get a problem on the requirements page.  It says "PHP extensions disabled.  Drupal requires you to enable the PHP extensions in the following list... gd"

I have installed, with yum install these packages: gd, gd-devel, php-gd, php-pdo php-mbstring, php-xml.

I have installed various other packages.  I have no reason to think that PHP gd extensions have not been enabled.  They've certainly been installed.  I've restarted Apache services and MariaDB services. I've rebooted the sever.

I reinstalled Drupal and PHP.  I created a php.ini file with "extension=gd.so" as the content.  A minimal installation fails for the same reason.

What should I do to get Drupal working for the first time?  I have never done this before.  How do I enable the PHP Extensions?  Or is the message false?  If it is, what should I do?

On CentOS, you should have an icon in cPanel for "PHP Selector":

In CloudLinux:

Make sure all of the PHP extensions installed by Yum are enabled & save the settings. Then create or open the info.php page for your domain to confirm the configuration. The problem should be fixed on the Drupal 8 status report.

Note: If you are having problems with installing PHP extensions for a web server running Drupal, consider installing Composer on CentOS. Composer is designed to streamline dependency management in PHP and manages the particular download files required by Drupal 8 modules specifically.


Using git over ssh from localhost to my Shared Hosting I managed to install smoothly git and drush on my Shared Hosting. Cool.
Now I created there a git repository:

$cd public_html/drupal
$drush dl drupal
$git init
$git add .
$git commit -a -m "My Project"

A .git folder has been created

Now all I am trying to do is to clone my remotely Drupal installation on my local computers home or whatever:

git clone ssh://username@*.*.*.*:portnumber/public_html/drupal

it connects well I enter the password but then I got the message:
fatal: /public_html/drupal does not appear to be a git repository
fatal: The remote end hung up unexpectedly

What did I do wrong? All I need is to use git (somehow as svn) as versioning. I don't need to post the project on github as it is a private one.

Help appreciated

Perhaps you are looking for

git clone ssh://username@63.23.133.162:portnumber/~/public_html/drupal

Note the ~ which is indicating that the public_html resides in your home directory.


Loading a ctools modal on the home page I have a front page that consists mostly of context rules to load various blocks, and for some users, a requirement to render a Ctools modal with a call to action. We aren't displaying much on the homepage besides a few views, and static blocks. I'm using this guide to build out the actual modal (which itself, will display a view with Contextual rules based on the user's settings) to show content tailored to them. Is there any in-code hooks I can use to activate this modal only on the home page, or should I look into the option of using a custom developed block (using hook_block_info() and hook_block_view()) to activate the modal on that page?

Using ctools modal framework instead of those [insert-fancy-word-here]box JS library. Kudos.

Ctools module uses js/modal.js inside ctools module folder to attach Drupal Ajax events to links with ctools-use-modal class. That is all.

I can think about a few approaches.

1. Do not make them modal-enabled in first place.

If you are calling the ctools_modal_text_button() or the function that adds modal-compatible markup, you can wrap it with an if statement.

<?php
if (drupal_is_front_page()) {
  print ctools_modal_text_button(t('Open the modal'), 'my/path/nojs', '');
}
else {
  print l(t('Open the modal'), 'my/path/nojs');
}
?>

If you are using a block, cache modes DRUPAL_CACHE_PER_ROLE and DRUPAL_CACHE_GLOBAL won't be compatible with this. DRUPAL_CACHE_PER_PAGE would work, but I doubt caching this block would improve performance. It can rather have a negative effect. DRUPAL_NO_CACHE would be best.

If you are hardcoding block contents, you can create two blocks, with different visibility settings based on the path.

2. Change the JS or CSS.

If you can't change the PHP, you still can change the JS and/or CSS.
A CSS solution would be the easiest. Print both modal and non-modal links, and if the body tag has not-front class, you can hide the modal links.

.not-front .ctools-use-modal {
  display: none;
}

You can un-ajax links as well.
Here is a sample code:

(function($){

    Drupal.behaviors.zzzzzz = {
        attach: function (context) {
           $('.not-front area.ctools-use-modal, .not-front a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          var base = $this.attr('href');
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
          delete Drupal.ajax[base]
        }
      });
    }}
})(jQuery);

There are other questions about Drupal behaviors and using jQuery with Drupal 7. Basically, above code finds modal links from non-front pages, and removes the Ajax properties defined in Drupal.ajax, so clicking the item does not trigger the modal.


How to redirect a user to previous page after successful login? I have added flag links to content pages for anonymous user. When user clicks on that link, the user should be redirected to user login page but after successful login the user should be redirect to last visited page.

I have used this code of a previously posted thread:

<?php
  global $user;
  if(!$user->uid) {
  // $flag: bookmark or make_feature, $action: flag, $content_id: $nid.....
  $flag_link = flag_flag_link($flag, $action, $content_id);

  $flag_link = flag_flag_link($flag, $action, $content_id);
  $flag_url = $flag_link['href'];

  //echo implode("/",arg());
    if(isset($flag_link['query']['token'])) {

      $flag_url .= '?'.$flag_link['query']['token'];

    }
  print l(t('SAVE '), 'user/login' , array('query'=> array('destination' => $flag_url)));
  print l(t('LIST'), 'user/login' , array('query'=> array('destination' => $flag_url)));
  } else {
    print render($content['links']['flag']);
  }

By using this code, anonymous user can redirect to login page but not to last visited page.

The following implementation of hook_user_login() will override the redirect path set by user_login_submit().

As with the default behavior, setting the destination in the query string overrides this redirect.

<?php

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {
  $edit['redirect'] = $_GET['q'];
}


Add an image selection list to a content type I'd like to add an image selection to a content type, what would let the user chose
for instance an icon, from a predefined list, to attach to this content type.

Any suggestions on how i could achieve that ?

Thanks,

I Found a way to do so Using Node reference field type, enabled by Drupal 6 CCK module or in Drupal 7 it's with: Reference Module

Once the module enabled, Node reference will be available as CCK field type :)


Get node count for each value of a CCK Options Widgets field Lets say I have a CCK options widget field with 4 options like
1
2
3
4

If I want to get the node count for these values how could I do that?

Also, how would I do it if I would like to put this result in a View and sort on it? Use a computed field?

Views Group By is just what you need. It enriches D6 & Views2 functionality with SQL Grouping and Aggregation capabilities. Once installed, configure it roughly along these lines:

Fields to Group On: Your Field
SQL Aggregation Function: Count
Fields to Aggregate with the SQL Function: Node NID
Fields to Sort Resultset On (after SQL Function is Applied): Your Field
Sort Direction: Descending

Please, note, this will only select those fields that have non-zero number of nodes that they are selected for. To work around that, depending on your scenario you might be able to use a taxonomy vocabulary to replace your options widget and then build a Term View type based on that vocabulary.


How to get Fragment value from url in Drupal 8? I need to get the Fragment value from url like: admin/config/system/meta_custom?query=test#abc=xyz in Drupal 8.

Need value of abc - ideally using Drupal's API, rather than doing my own Url Parsing.

You could use it like this:

$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);

It gives:

Array
(
    [0] =>
    [1] => node
    [2] => add
    [3] => application
)


Prevent Field From Updating On Follow Up Saves? Use Case:

On Page A (Content Type A), there is a select list with options A and B

1st Rule for Choice A

User selects A, and a field "Date You Chose Letter" (a date field) captures the current DateTime.

2nd Rule for Choice B

User selects B, and the same field "Date You Chose Letter" (a date field) captures the current DateTime.

Easy enough.

But, when the User returns to Page A, makes some changes (and assume "A" is still selected) the 1st Rule triggers again, updating the "Date You Chose Letter" field with a new current Date/Time

The goal:  Do not update the "Date You Chose Letter" field after the initial selection. So I need to set in stone.

You can write a small custom module to lock down the original value of the field on edit, probably using hook_form_FORM_ID_alter would be the clearest way.

Difference between create new and edit node in form alter provides a decent example, try that. Basically, you have to check in the $form object for an existing node. If it's an edit form, you have a node id already; if it's a new node, you don't.


Mobile Tools or Media Queries? I have always used CSS media queries on past sites for a responsive layout. Recently bumped into Drupal Mobile Tools dev.7 and liking it thus far. Trying to understand the purpose of it besides another method for a mobile site.

CSS Media Queries: Great if desktop / mobile sites are similar in functionality. Easy.

Drupal Mobile Tools: Need to load a different theme for major desktop/mobile site differences. Contextual layout. Exportable configurations.

Mainly looking for what is best practice out there. Can too many media queries put a major strain on a website with tons of hits or is Mobile Tools bit of overkill for any small/media site?

Thanks.

What about using Adaptive Theme or sky (based off the first)? These are designed with multiple screen sizes in mind and you have a community of folks to share knowledge with.


Anonymous user's can't views/download files uploaded via file field I have a node with a File field and i am using public file system. I have uploaded a file via File field and checked the mark "display" in the list of attached files to node, but still, anonymous user's can't even view it (also they can't download it), till i check this permission:

But i think it's security vulnerability. Is drupal 7 file access system broken? Or am i missing something?

Manage display page

Figured out! I have uploaded a .rar file, so drupal wouldn't recognize this as existed file types e.g. audio, image, document. I had to go in admin/structure/file-types/manage/document

And add mimetypes for .rar and .zip extension:

application/rar
application/zip

Then just reuploaded file and gave anonymous user's permission:

Document: Download any files


Make visible the article in Draft and Needs Review mode to other members of the community group I am facing a permission issue, I found not yet a resolution.
I am using Workbench, Workbench Moderation and Organic Groups.

User1 creates a content in a community (organic groups)
Then he creates content setting its moderation mode to: Draft

Now User2 ask permission to join group, but he is unable to see the above article until is set to Published mode.

How can they share the article set in Draft mode?

Is the below permissions checked from permission tab ? If it's not then set the below permissions:

Workbench Moderation:

View all unpublished content
View the moderation messages on a node
View moderation history
Use "My Drafts" workbench tab
Use "Needs Review" workbench tab

Also let me know which version of workbench moderation module you are using .


Pass variable to drupalSettings I'm using Drupal 8.

What I'm trying to do is:

Access the active node
From the node get the value of field_test and assign it to a variable
Pass the variable to the drupalSettings function and subsequently to a custom module 'mycustommodule' that triggers an alert

In my content type, I created a field_test field, which is the field I reference in my code. The block is placed on a page of this content type.

This is the code I am using.

mycustomblock.libraries.yml

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

MyCustomBlock.php

<?php
/**
 * @file
 *
 */

namespace Drupal\mycustomblock\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Creates a 'Foobar' Block
 *
 * @Block(
 * id = "block_mycustomblock",
 * admin_label = @Translation("MyCustomBlock"),
 * category = @Translation("Blocks")
 * )
 */
class MyCustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */

  public function build() {

  // get the variable from field_test
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $test = $node->field_test->value;
      $variables['#attached']['library'][] = 'mycustomblock/custom';
      $build['#attached']['drupalSettings']['mycustomblock']['test'] = $test;
    }
}

custom.js

(function ($, Drupal, drupalSettings) {
  var testMe = Drupal.settings.mycustomblock.test;
  alert(testMe);
)(jQuery, drupalSettings);

How can I tell if the JavaScript file is being loaded from the block? I checked in the inspector, and do not see it being loaded when the page with the block on it loads.

Furthermore, how can I properly access the field value and pass it to JavaScript?

The code doesn't work because the build() method doesn't return anything, which for PHP is like returning NULL. (In other words, you are telling Drupal not to render anything.)
If you fix that, then you would also have to attach the library to the same variable to which you attach the settings.

public function build() {
  $build = [];
  // get the variable from field_test
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $build['#attached']['library'][] = 'mycustomblock/custom';
    $build['#attached']['drupalSettings']['mycustomblock']['test'] = $node->field_test->value;
  }

  return $build;
}

As side note, as per Drupal coding standards, class names should follow the UpperCamel naming, a.k.a. PascalCase.

As for the JavaScript code, take node.js as guide.

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.nodeDetailsSummaries = {
    attach: function attach(context) {
      var $context = $(context);

      $context.find('.node-form-author').drupalSetSummary(function (context) {
        var $authorContext = $(context);
        var name = $authorContext.find('.field--name-uid input').val();
        var date = $authorContext.find('.field--name-created input').val();

        if (name && date) {
          return Drupal.t('By @name on @date', { '@name': name, '@date': date });
        } else if (name) {
          return Drupal.t('By @name', { '@name': name });
        } else if (date) {
          return Drupal.t('Authored on @date', { '@date': date });
        }
      });

      $context.find('.node-form-options').drupalSetSummary(function (context) {
        var $optionsContext = $(context);
        var vals = [];

        if ($optionsContext.find('input').is(':checked')) {
          $optionsContext.find('input:checked').next('label').each(function () {
            vals.push(Drupal.checkPlain($.trim($(this).text())));
          });
          return vals.join(', ');
        }

        return Drupal.t('Not promoted');
      });
    }
  };
})(jQuery, Drupal, drupalSettings);

Drupal modules should use behaviors.

See the first and the last line of the code I copied here. Your JavaScript code should use the same lines, and access the settings with drupalSettings.mycustomblock.test.


How to delete blocks and why some you can delete and others you can't? I'm probably missing something here....

But there is no delete option for blocks, either enabled OR dissabled.

Additionally, some blocks can be deleted, and some don't , they have the same exact settings.

J. Reynolds is right. These blocks are generated from code. This means this block is added programmatically through hook_block_info(). Some modules use this to define static blocks (like the login block or the "Created with Drupal" block). However some other modules implement this hook in a dynamic way. Views for example uses this to generate a list of all blocks in all (enabled) Views.

So even though you did not create them in code. Some of the modules you use do. Only blocks you have created using the Add block link on admin/structure/block can be deleted.

In order to remove a Views block from the listing, disable the View (or the block display in the view). I have no idea how to hide a block generated from Node as block. And I suppose there is not a real way to remove these blocks from the listing without writing a custom module.

You could attempt to create a custom module and implement hook_block_info_alter(), in which you unset all blocks you don't want. Maybe something like this:

function MYMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  // Attempt to disable the login block by status.
  $blocks['user']['login']['status'] = 0;

  // If above doesn't work unset the block.
  // Array is built like $blocks[module][block_name]
  unset($blocks['user']['login']);

  // Disable all Views blocks (also used ones!!)
  unset($blocks['views']);
}

But to be honest, I doubt if it is worth the effort and it can lead to confusion in the future if expected blocks do not show up. So I'd advice just to leave it.


How to make each header in a table clickable and add a chart to it? I have used the Views module to display an external database (which is working fine), but I want to make each header clickable and add a chart.

Is there a module to do this, or is there a way I can do this?

I found a few charting modules; some are good but they require me to create each chart manually, using the style and the data gets feed to it dynamically. The problem is that my tables have many headers; I flip the rows and columns but there are over 100 headers in it.

There's no drag-and-drop solution. You would either have to create a custom module yourself that would do what you want, modify a module that gets close to what you want or use one of the solutions out there that makes you enter things in manually.


Get the value from module to template I want to pass the value from module to page tpl file in drupal.I have created a custom module 'one_time_popup'.I have created a sample soutput and tried to pass it and print in page.tpl.php after footer section.but doesn't shows any thing.What I did wrong.I'm a newbie

function one_time_popup_menu(){
$items['oneTimePopupData'] = array(
'title' => 'One time Popup',
'page callback' => 'one_time_popup_user_login',
'type' => MENU_CALLBACK,
'access callback' => TRUE,
);
return $items;
}
function one_time_popup_user_login(&$edit, $account){
 ...
$output='value from one time popup module!';
return theme('photo_order',array('results' => $output));
}
function one_time_popup_theme() {
 return array(
'photo_order' => array(
  'template' => 'page',
  'variables' => array(
    'results' => NULL,
  ),
 ),
 );
}

Tpl file(page.tpl)
<?php echo $results; ?>

<?php
/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items = array(
      'custom_menu_item' => array(
        'title' => 'Hello world',
        'page callback' => '_page_hello_world',
        'access callback' => TRUE,
      ),
    );
  return $items;
}

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  $theme = array();
  $theme['mymodule_template'] = array(
    'template' => 'mymodule-template',
  );
  return $theme;
}

/**
 * Preprocessor function for 'mymodule_template'.
 */
function template_preprocess_mymodule_template(&$vars) {
  $vars['hello'] = 'hello!';
}

/**
 * Page callback.
 */
function _page_hello_world() {
  return theme('mymodule_template');

}

A $hello variable is available in your template at path /custom_menu_item


Custom theme function for language switcher block I have a problem with theme hook suggestion for language switcher block.
I just need to place theme_links__locale_block() in MYMODULE.module file

My module:

/**
 * Implements hook_theme()
 */
function MYMODULE_theme() {
  return array(
    'MYMODULE_links' => array(
        'variables' => array(
            'links'      => NULL,
            'attributes' => NULL,
            'heading'    => NULL
        )
    )
  );
}

/**
 * It doesn't work...
 */
function theme_MYMODULE__locale_block(&$variables) {
    // custom function code ...
}

It works in my template.php file:

function MYTHEME_links__locale_block(&$variables) {
    // custom function code ...
}

I don't want to leave it in template.php because it is a part of my module.

Any help would be appreciated.

SOLVED!

adding hook_theme_registry_alter(&$theme_registry) was the answer.

/**
 * Implements hook_theme_registry_alter
 *
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {

  $mod_path = drupal_get_path('module', 'MYMODULE');

  if (isset($theme_registry['links'])){
    $theme_registry['links__locale_block']['theme path'] = $mod_path;
    $theme_registry['links__locale_block']['function'] = 'MYMODULE_links';
  }
}


How to access global variable from within Drupal content I am trying to access a global variable I created using javascript within a content node i created. In an attached js file i have var rootpath = "/clients/UMP/";

Inside of my drupal page i have:

<script>document.write(window.rootpath);</script>

But it just shows the text: undefined

Am i doing something wrong? Is there a more better way to do it using php perhaps?
Thank you for taking the time to read this and respond. I apologize for being such a noob with drupal. I have only been using it for a few weeks.

Based on your comments, you might want to try using Drupals built in functions to retrieve the correct path for your assets.

The 2 you could take a look at are base_path() and path_to_theme().

For example:

<img src="<?php print base_path(); print path_to_theme()?>/images/image1.jpg" />


Validate user required fields I'm using Drupal 7 and I have some PHP pages that depends on my Drupal site.
In the PHP page, I tried to add a user programmatically in order the check the exception:

try {
  $new_user = array(
    'name' => 'user'
  );
  user_save('', $new_user);
} catch (Exception $e) {
  echo $e->getMessage();
}

I didn't give all the required field, like email and some custom fields that I set in Home » Administration » Configuration » People » Account settings, but Drupal still added this user.

I need the following:

Get all user field(s) and check if they are required or not
Get error on exception when I'm trying to add user without required fields

How should I do that?

I think you shouldn't create user this way, as it's bypassing all the controls made by drupal.

You can retrieve registration form this way:

drupal_get_form('user_register_form');

And print it like this:

print(drupal_render(drupal_get_form('user_register_form')));


Field weight in display mode is not respected on custom entity I have a custom entity type with a set of base fields and I can create/view/update/delete entities. However When I create & enabled a custom view mode to the entity type and set to display subset of fields (using Manage display) in a page using below code:
$view_builder = $this->entityTypeManager->getViewBuilder('my_entity');
$build['top_summary'] = $view_builder->view($entity, 'summary');

The fields get rendered, but not in the order they are in the view mode. They are in the order of the IDs of the fields alphabetically. So if the entity has these fields in this order:

First name
Last name
Email

They get displayed as

Email
First name
Last name

I can hide fields using the hidden section, but can't change the visible fields' order.
Updating the fields' order in core.entity_view_display.[ENTITY_TYPE].[BUNDLE].[VIEW MODE] does not help as the fields are sorted alphabetically on config import/export

After debugging the Drupal\Core\Field\FormaterBase on how the fields getting rendered, it seems the weights are getting applied to each field in Drupal\Core\Entity\EntityViewBuidler, but they are not getting rendered in the order at the entity level.
So providing a theme for the entity using hook_theme and a preprocess solves this issue. Here is the code:
// mymodule.module

use Drupal\Core\Render\Element;

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'myentity' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for myentity templates.
 *
 * Default template: myentity.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the entity
 *     information and any fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_myentity(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

<!-- myentitty.html.twig -->
<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>


Importing large datasets via HTTP I'm having trouble importing a very large dataset with feeds. It's about 8mb of text in XML format. It imports impossibly slow (I started it about a month ago and it's still not finished).

However, if I run the exact same importer with the same file I upload from my computer, it runs in about two minutes.

The thing is, I need to check the stock of my products from my supplier through this file every hour. Most of the data is irrelevant other than stock info.

Are there any good alternatives to do what I'm trying to do? (Drupal Commerce)
I've been thinking that if I have another module retrieve the file from my supplier every hour, then I could just point feeds to the file on my own server. However, I'm having trouble finding a module that does that file retrieve.

Any ideas?

A month-long operation is a good sign that something went wrong? How did you launch the import? If you used a Web GUI, the operation probably timed-out without updating the UI. I doubt your webserver is configured to allow a month-long HTTP request processing. Are you able to connect to the server to check if a PHP process is indeed still running?

Instead of looking for a module to download the imported file every hour, you could rely on a simple cron job using curl or wget to download the file:

0 * * * * wget http://my.supplier.com/products.xml -a /var/log/supplier-products-download.log --no-verbose -O /some/path/products.xml

If I remember correctly, the default XML parser for Feeds uses SimpleXML. It will load the complete XML tree in memory beofore processing it. For a 8Mb file this could start to be an issue (depending on your PHP memory configuration). A beast approach would be to write your own Feed parser (as a Feeds plugin) using the XMLReader API which support a streaming mode (ie. data are processed when reading the file).


After moving Drupal 7 site, adding /user or /?q=user to base URL simply reloads maintenance page I've just moved a Drupal 7 site from Bluehost to Inmotion (by reinstalling the latest core and adding the 'sites' directory from the old server account, then uploading the database). Since the move I can't log in from the browser.

The DNS has transitioned. At the new location Drupal is installed in a subdirectory -- public_html/sub. I've altered the .htaccess file at the level above (public_html/.htaccess) as per these directions https://support.lunarpages.com/knowledge_bases/article/549 so that the site will open there with the base url in the browser.

That does happen, with the base URL currently showing the under maintenance message, just as the site was left. But when I attempt to go to /user or even /?q=user to log in and resolve any last errors from the move, then bring the site back online, I am not given a login form. It simply continues to show the under maintenance message.

I'm guessing this problem is somehow related to .htaccess and/or settings.php, but I can't seem to find the right combo of changes that will allow me to log in. Any suggestions? (I did clear the cache and sessions tables in the DB when this error first occurred, but no help.)

Update your settings.php to this:

$conf['site_offline'] = 0;

From https://www.drupal.org/node/276457#comment-901392


Creating a view of child groups in Organic Groups How do you create a View showing all the child groups of a group in Organic Groups?

I've started off with the 'OG Extras Groups' view, which shows all groups. I thought it'd be simple to then just add a filter for 'Content: Parent group', and that would show the children of a selected group. It returns no results, though.

I've tried all sorts of relationships but can't get the child groups to show. This thread is the only information I've found:
https://www.drupal.org/node/159988. The explanation is for D6, though, and I can't see an easy translation to D7.

I've only got five groups so I don't need to set a contextual filter - I can hard code the parent group value (either name or ID).

Answering my own question: it was as simple as adding the 'Content: Parent group' filter. For some reason I'd added a relationship I didn't need, which I was using on the filter. In fact you don't need any relationships at all. You can delete the 'OG membership: OG membership from Node' relationship from the default 'OG Extras Groups' view.


jQuery_ui slider doesn't load for anonymous user In my recent drupal 7 install... I've installed jquery_update. I configured it, and added a little module with a js.

jQuery_ui is not loaded for anonymous use. I've done some researches on the web ... for most people jquery doesn't load for anonymous user because it wasn't called. But for me jquery loads correctly I can alert(jQuery("#amount")) succesfully.

My error message is TypeError: jQuery(...).slider is not a function : jquery_ui slider method is not loaded for anonymous user... I searched in permissions too.. no jquery_ui permission configuration.

What did I missed ? Couls anyone help ?

Thanks in advance.

I found the quick answer : Add this line in the module using jquery_ui to call jquery_ui when needed.

drupal_add_js('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js', 'external');

or this:

drupal_add_js(drupal_get_path('module', 'jquery_update') .'/replace/ui/ui/minified/jquery-ui.min.js');

The question now is : is this the best way?


How to get granted and expires fields of commerce license updated? I have similar problem as described on Commerce License Billing: How do I charge or refund a prorated amount when the user's plan changes and the billing cycle is prepaid? by @wizonesolutions, but with different goal.

On a Drupal 7 website with the Commerce License Billing module used for subscriptions, the changing subscriptions plan by saving the new product_id on the license entity ($license->product_id) does in fact update the license and the due amount on the next recurring payment order, however, it does not update the granted and expires fields of the license.

So I tried to get those fields' values from the license, make my calculations and save them together with the whole license entity like so:

$bct=$form_state['storage']['target_product']->cl_billing_cycle_type[LANGUAGE_NONE][0]['target_id'];
    if ($bct == '1') { // hourly
      $target_date = strtotime('+1 hour', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '2') { // daily
      $target_date = strtotime('+1 day', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '3') { // monthly
      $target_date = strtotime('+1 month', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '4') { // quarterly
      $target_date = strtotime('+3 months', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '5') { // biannually
      $target_date = strtotime('+6 months', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } else { // biannually
      $target_date = strtotime('+1 year', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    }
    $license[arg(1)]->granted = strtotime("now");
    $license[arg(1)]->product_id = $form_state['storage']['selected_plan'];
    entity_save('commerce_license', $license[arg(1)]);
    drupal_set_message('License has been updated.');

And the admin/commerce/licenses page after saving the license entity shows that all the relevant fields - new product_id, granted and expired fields have been in fact updated.

But the problem is that when expire time comes, the granted field reverts back to initial value and the expired field's value is calculated based on the initial granted field.

In other words, guess I have two billing cycles - hourly and daily - and if an initial order is placed with hourly billing cycle, then license with the following fields is created:

Cycle: Hourly
Granted: 15 January 2018 - 17:50
Expires: 15 January 2018 - 18:50

If I update the license with the new product id, granted and expires field then the admin/commerce/licenses shows:

Cycle: Daily
Granted: 15 January 2018 - 17:52
Expires: 16 January 2018 - 17:52

And when 16 January 2018 - 17:52 comes and all the relevant cron tasks are processed then the same page shows:

Cycle: Daily
Granted: 15 January 2018 - 17:52
Expires: 15 January 2018 - 20:48

Meanwhile bunch of extra orders are charged and the new recurring order with Recurring: Open status are created and then only the license admin page showing the granted and expires fields (with values behind from 16 January 2018 - 17:52) constantly changing with every cron execution:

Cycle: Daily
Granted: Active 15 January 2018 - 17:52
Expires: 16 January 2018 - 01:48

So my question is:

If changing the values for the granted and expires fields in license entity does not take effect, where else I should be looking for changing those values?

After monitoring how database tables change with recurring products, I've noticed that saving license with the new data was not sufficient and that the cl_billing_cycle should also be updated with the new granted and expire dates.

I am doing that with a direct database query for now. Let me know if there is a better way to update the cl_billing_cycle.


Views list with picture as left, title and content as right How to make such a layout as on example screenshot?
Picture on left, Title and truncated content on right.

What view format i need to use?

If you are just trying to create a layout for a node, not a view, then take a look at Display Suite. You can choose a simple layout in the settings e.g Header with left and right columns, then drag and drop which node fields you want into those areas.

There are lots of good help videos too.


Calendar as view's pager (passing arguments between views?) I have a view paged by week. Users are a bit disappointed by the pager: they find clumsy to navigate to weeks that are far in time (more than 1 month from today's date).

The idea is to keep the weekly pager for small jumps in time and add a month calendar, so when you click a day on the calendar, the corresponding week is shown in the view. If this is too complicated, I think that a drop-down with a list of weeks could be enough, at least for now.

I was thinking that a possible solution could be creating two views and display them in one page. When you click a cell in the first view (which shows the month calendar), the date is passed to the second view (the main view, paged by week), which accepts a date as a contextual filter. But is this possible to do?

Your two Views should be possible with the Views Field View module:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

or the side by side could be accomplished by integrating the Views into the Panels Module:

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.


Getting the pretty value of a Select field in Node twig template I would like to get the pretty value from a field in my content.

Here is the structure of the select box field when I add a content :

00|Ground
01|Apartment
02|House / Cottage
03|Business premises
06|Attachments

In my node--content-type.html.twig, when I call the field with :

content.field_*machine_name*.value

It display the key of the selection (00, 01, 02,...). I would like to have Apartment, House / Cottage, ....

When I call just this :

content.field_*machine_name*

It display the pretty value but wrapped in a div that I don't want.

When I call just this :

content.field_*machine_name*

  It display the pretty value but wrapped in a div that I don't want.

This is the correct way, you should if possible render a field in node twigs like this.

The div, that you don't want, is probably in the field twig, that gets invoked by using {{ content.field_*machine_name* }}.

You have to put a copy of field.html.twig in your theme and name it:

field--field_*machine_name*.html.twig

And look there for the div.


How to style a custom theme setting form I have a set of custom theme settings defined in my theme.

They are fully integrated into my theme and appear on the theme's setting page but they are not styled. I use the seven admin theme.

I would like to style the forms on the admin pages; similarly to how other core modules like color, logo etc are styled.

How does one go about this?

Ideally, I would group my settings, place them in a div and give the entire group a title and help.

Basically it's just these two steps:

Define a library from MYMODULE.libraries.yml.
Attach the library to your form.

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

  Attaching a library to a form

  As forms are just render arrays, attaching a library works just the same:

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $entity */
  $formObject = $form_state->getFormObject();
  if ($formObject instanceof \Drupal\Core\Entity\EntityFormInterface) {
    $entity = $formObject->getEntity();
    if (
      $entity->getEntityTypeId() === 'node'
      && in_array($entity->bundle(), ['organisation', 'location', 'event', 'article'])
    ) {
      $form['#attached']['library'][] = 'yourmodule/yourlibrary';
    }
  }
}

To add additional wrapper divs around some single or multiple form elements you can nest them into containers or fieldsets. For example:

  class Container

  Provides a render element that wraps child elements in a container.

  Surrounds child elements with a  and adds attributes such as
  classes or an HTML ID.

  Usage example:

$form['needs_accommodation'] = array(
  '#type' => 'checkbox',
  '#title' => $this
    ->t('Need Special Accommodations?'),
);
$form['accommodation'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => 'accommodation',
  ),
  '#states' => array(
    'invisible' => array(
      'input[name="needs_accommodation"]' => array(
        'checked' => FALSE,
      ),
    ),
  ),
);
$form['accommodation']['diet'] = array(
  '#type' => 'textfield',
  '#title' => $this
    ->t('Dietary Restrictions'),
);

The D7 Form API Reference still is the most useful resource for that. Though you might want to check for changes on the D8 equivalent: Form and render elements.


drupal_http_request and stream_socket_client The D7 core function drupal_http_request uses the stream_socket_client() php function. For many serious web hosters, sockets and stream_sockets functions are a security bad practice and most of them disable these functions.

Why the D7 developpers don't make drupal_http_request rely on cURL functions ?
Is there any alternative ?
Thanks,
J.

The cURL HTTP Request module was built for exactly that:

This is a module intended for developers, as it provides just one API to call: curl_http_request().
The function curl_http_request() is an alternative implementation of Drupal core function drupal_http_request() using cURL.
The function intends to be backwards compatible with drupal_http_request(), by accepting the same parameters in the same form and by returning the response in the same format.

I can't comment as to the decision the original developers took, but don't forget that cURL isn't necessarily available on every system either.


Drupal 6 exposing fields in views So I have a product content type with a title field and a file upload field and I created a bulk operation to enable the user to upload a single file, selecting which titles to upload that file for.

But what my client really wants is a page (instead of modifying each individual node) with a list of the product titles and a file upload next to each since most of the products use different files.  My view is defined with a table style instead of the bulk operations style and has the title field and the file upload field displayed but in the preview, the file upload field column only shows the file names for the titles which already have a file uploaded and the rest of the rows blank.

Is there a way to expose this file upload field like you do a filter so the user can upload a different file for each title ??

Based on some research, I was able to find Editview for Drupal 6. I'm not quite sure if it's like how Editable views work for Drupal 7.

It states in the Editview's module page that,

  It allows you to create a view in which the nodes are editable, and
  new nodes can be created.

Hope this helps.


Use inline_template instead of markup, or a theme function (as suggested by Ivan Jaros in a comment also).
Refer to class InlineTemplate for way more details. Here is a partial quote of it:

Provides a render element where the user supplies an in-line Twig template.
Properties:

#template: The inline Twig template used to render the element.
#context: (array) The variables to substitute into the Twig template. Each variable may be a string or a render array.

Usage example:
$build['hello']  = [
  '#type' => 'inline_template',
  '#template' => "{% trans %} Hello {% endtrans %} <strong>{{name}}</strong>",
  '#context' => [
    'name' => $name,
  ]
];


Migrating specific nodes from Drupal 6 to Drupal 7 I have an existing Drupal 6 site, and an updated version of the same site running on Drupal 7. Setting up the Drupal 7 site did take a lot longer than I planned, and the old Drupal 6 site accumulated some more content in the meantime. I now want to migrate some new nodes from the old site to the new one, but not all of them as many already exist on the new site in updated versions.

I did find the Migrate module, but from what I can tell this seems to be a framework, and not an out of the box solution.

Is there an easy way to migrate specific nodes, either hand-picked or based on selection criteria like node type and creation date, between two Drupal installations of different major versions?

The easiest way I know is export your nodes from Drupal 6 by using Node Export . Then you can import your node to Drupal 7 by Feeds module. This has update and replace exsisting nodes options. Just make sure you set one of the source as an "Unique" on Mapping setting, like "uid" or "title" of the node. Hope this help


Will image styles be applied when they do not logically apply? I have a set of biography images in the site I'm working on, and I have an image style that will enforce the correct size for these.   Of course I'd rather not have them resized if they don't need it, so I'm wondering if the resize & crop effect will be skipped if the image is already the perfect size.

In other words, if the image is 130 x 170, and the effect of the image style would be to resize & crop it to make it 130 x 170, will the Image module be clever enough to skip that effect and leave it alone (so as not to degrade quality)?

If it will process the image anyway, then obviously I'll want to simply display the original image.  It would be very useful if the module were clever enough to know when not to run, so the image style could be there as a failsafe in case some future content editor is too lazy to crop the images beforehand.

It is all up to the PHP toolkit used to manipulate images. The code that is executed from the image effect is the following one. (See image_scale_and_crop_effect().)

function image_scale_and_crop(stdClass $image, $width, $height) {
  $scale = max($width / $image->info['width'], $height / $image->info['height']);
  $x = ($image->info['width'] * $scale - $width) / 2;
  $y = ($image->info['height'] * $scale - $height) / 2;

  if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
    return image_crop($image, $x, $y, $width, $height);
  }
  return FALSE;
}

The IF-statement is only used because image_resize() can return FALSE if the PHP image toolkit doesn't support the operation being executed on the image. The function called from image_size() (image_toolkit_invoke()) is generic, and it doesn't make assumptions about the operations currently enabled from the selected image toolkit.


How to customize the admin toolbar in Drupal 7? I'm trying to customize the administration toolbar in Drupal 7 but I don't know how to do it.
I'd like to add custom links (e.g node/add/[content-type]) and links that are only available for specific users.

[Edit] Finally, I used admin_menu module and I added a menu item with a custom module using hook_admin_menu_output_alter

Take a look at the Quickbar module.This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

You could also look at the Manager module. It includes the Manager's Bar. An admin-bar designed for users that aren't familiar with Drupal. It is like the default "Navigation" menu, when we cut off everything that doesn't matter to this users, and it looks like some known admin-bar-modules, like Admin Menu, but a lot more simple.


Programmatically adding registration type (Entity Registration module) I am trying to programmatically add a registration type using the Entity Registration module and Drupal 7.

Currently I am using the following code:

$bundle = array(
    'type' => 'flake',
    'label' => $t('Flake'),
    'base' => 'registration',
    'custom' => TRUE,
);

$registration_type = registration_entity_set_default_settings($bundle);

registration_type_save($registration_type);

Among other thing, I have tried 'name' instead of 'label' and 'entity_registration' instead of 'registration'.

As you can probably gather, I am new to creating types of any sort. I started by working off a tutorial for creating a regular content type and did not run into any problems. Figuring out how exactly that differs from the entity registration type has been a little challenging.

Registration _type is just an entity type so is exactly the same as creating any other entity:

$registration_type = entity_create('registration_type', array(
    'name' => 'flake',
    'label' => 'Flake',
));
entity_save('registration_type', $registration_type);

Sometimes it helps to create an entity via the UI provided with a module and then load and inspect it to help understand what values can be provided.

For example after creating a registration type visit /devel/php (make sure devel module is enabled) and run this code:

dpm(entity_load_single('registration_type', 1));

You should see an output similar to this:


Webservice args types automatic validation It's a Drupal 7 with Webservices module, and there is a service with something like this (example):

'create-product' => array(
  'operations' => array(
    'create' => array(
      'help' => t('Add Product'),
      'file' => array(
        'type' => 'endpoints.inc',
        'module' => 'custommodule',
        'name' => 'custommodule',
      ),
        'callback' => 'custommodule_create_product',
        'args' => array(
            array(
                'name' => 'appID',
                'type' => 'int',
                'description' => t("App ID"),
                'source' => array('data' => 'appID'),
                'optional' => FALSE
            ),
            ...

Okay, so the type here is "int". Is it possible to make Drupal return some error automatically, if it's not an int that is being sent as appID.
Like if it's a string being sent, then it will throw an error.
I can't make it work.
Why else is there a "type" key-value?

Although it appears Services doesn't validate the incoming data based on the type, you can use an access callback to build your own validation.

Add something like this to your Service Resource definition:

// ...
'access callback' => '_example_resource_access',
'access callback file' => array(
  'type' => 'inc',
  'module' => 'example',
  'name' => 'example.resource-access',
),
'access arguments' => array('foo bar'),
'access arguments append' => TRUE,
// ...

Then create a file called example.resource-access.inc with a function like this:

function _example_resource_access($op, $args = array()) {
  if ($op == 'foo bar' && !is_numeric($args[0])) {
    return services_error(t('That is not an integer.'), 406);
  }
  return TRUE;
}

Note, $args[0] will likely come in as a string representing an integer, so using is_numeric() should be accurate, unless you specifically use (int) to cast $args[0] beforehand, then you can run it through is_int() for validation instead.


Errors when Taxonomy is chosen in node's Term Reference field I have created a vocabulary called "Recipes" with several terms underneath (Appetizers, Dinner, etc). I also have a content type called "Recipe" with a Term Reference field for the Recipes vocabulary.
When a term (let's say Appetizers) does not yet have a node referencing it via that Term Reference field, the term's page shows up fine (albeit without any node content). However, when I choose one of those terms on a Recipe node via that Term Reference field, the term's page shows three error messages and various elements of the page (such as the footer and the nav bar) are not displayed. The errors are:

Notice: Undefined property: stdClass::$type in _node_extract_type()
(line 379 of /home/mysite/public_html/modules/node/node.module).
Notice: Undefined property: stdClass::$nid in node_build_content() (line 1417 of /home/mysite/public_html/modules/node/node.module).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7721 of
/home/mysite/public_html/includes/common.inc).

I upgraded from 7.24 to 7.26, but that did not fix the issue. Google has not been particularly helpful. Does anyone here have any feedback on what might cause this issue? FYI, I also added a Term Reference field for the built-in "Tags" vocabulary, and the same issues occurred.

This EntityMalformedException: Missing bundle property on entity of type node errors seems to rear its ugly head in a lot of different contexts.

In my case it was a configuration of the view that showed the related nodes that had a couple of filters set wrong.

I had a relationship to related articles, but then in the filter section, Relationship was set to "Do not use a relationship" instead of using the related article. Setting the correct setting on the filter fixed the issue.


How to convert xml into array in php? I want to convert the XML structure below into a PHP array.

<BillingApplyRq>
    <FatoryId>xxxxxx</FatoryId>
    <TotalNum>2</TotalNum>
    <Records>
        <Record>
            <ReturnMsgNo>1</ReturnMsgNo>
            <ReturnMsg></ReturnMsg>
            <TradeSeq>00001</TradeSeq>
        </Record>
        <Record>
        <ReturnMsgNo>1</ReturnMsgNo>
        <ReturnMsg></ReturnMsg>
        <TradeSeq>00002</TradeSeq>
        </Record>
    </Records>
</BillingApplyRq>

Does anyone know how to do that?

Although this is not related to Drupal but anyway you must convert from XML to array by using the sample code below from PHP.net

$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

Ref: xml_parse_into_struct — Parse XML data into an array structure