How to write SQL Statements With Spaces In Column Names Hi I am trying to write a Dynamic Query to get data from the database but I am facing issues to write a query for column names with white spaces.

My Product_Details Table looks as below:

| S.No.  | Product line   | Product type  | Product   | Year  |

| ------ |:--------------:| -------------:|----------:|------:|

|   1    | Camp Equipment |  Cooking Gear | Cook Set  | 2015  |

|   2    | Golf Equipment |    Irons      | Titanium  | 2014  |

My SQL Looks as below:

$query = \Drupal::database()->select('Product_Details', 'n');
$query->addField('n', 'S.No.');
$query->condition('n.Product type', 'Irons');
$results = $query->execute()->fetchAll();

But I am getting  Syntax error or access violation.

While looking into the error log after SQL Query executed I found out this:

  1: SELECT n.S.No. AS SNo FROM  {Product_Details} n WHERE n.Producttype
  = :db_condition_placeholder_0; Array (
      [:db_condition_placeholder_0] => Irons )

If you look into it  Product type is changed to Producttype and also S.No. is changed to SNo

Anyone got the idea how to write the SQL Query when column names has spaces?

You can use ` try with:

$query = \Drupal::database()->select('Product_Details', 'n');
$query->addField('n', 'S.No.');
$query->condition('n.`Product type`', 'Irons');
$results = $query->execute()->fetchAll();

According to this post https://stackoverflow.com/questions/14190798/how-to-select-a-column-name-with-a-space-in-mysql you can use also [].


EntityQuery does not return values I am trying to get some entities using the "entity.query" service.

What am I doing:

in my module (file "mymodule.module") I execute:

function mymodule_preprocess_page(&$variables) {
  $query = \Drupal::entityQuery('node');
  $query->condition('type', 'article');
  $nids = $query->execute();
}

What I get:

when I browse a page under the name of an authorized user - the request returns the results

when I browse the site as a guest, the query does not return any results.

Why am I not getting any results when I browse the site as a guest? Any ideas?

Entity query respects access by default. Add the ->accessCheck(FALSE) method to prevent access checking. Be careful, removing access checks may expose restricted data. It may be better to configure view permissions or whatever access system you're using to allow anonymous users to access content instead of removing the check.


How to print user role id with dynamic variable of language? How to make this code dynamic  initially its printing only user role id for english language only ,if my current site having more then 10 to 20 languages how to change this code to dynamic

         global $user;
 global $language;
      //$lg =$language->language;
     dpm(user_load($user->uid));
    $user_fields = user_load($user->uid);
      //echo $user_fields->field_role['en'][0]['value'];

       $lg = $user_fields->language;
         //echo $lg;

     echo $user_fields->field_role['$lg'][0]['value'];

if i replace the ['en'] with ['$lg'] nothing is printing

You're using $lg inside single quotes ('), because of which PHP is considering it as static text. If you want to use variable inside quotes, use double quotes ("). Check this ans for more details.

Try below code, to print role based on language:

<?php
global $user, $language;
$user_fields = user_load($user->uid);
// $lg = $user_fields->language;
$role = (!empty($user_fields->field_role[$language->language]) ? $user_fields->field_role[$language->language][0]['value'] : $user_fields->field_role['en'][0]['value'])
echo $role;
?>


How to display an alternative text if the comments are closed for the node? in my node type template, how do I display alternate text if comments are closed for the node ?

  {% if content.comment %}

      {{ content.comment }}

  {% else %}

      {{ content.field_link }}
      {{ content.field_code }}

  {% endif %}

EXAMPLE

  If comments are open :

  {{ content.comment }}

  If comments are closed :

  TEXT

Assuming you're using the default field definitions installed by the standard profile, what you want is the status property of the comment field of the node, which is accessible in twig via node.comment.status.

{% if node.comment.status == 2 %}
   {# comments are open #}
{% elseif node.comment.status == 1 %}
   {# comments are closed & visible #}
{% elseif node.comment.status == 0 %}
   {# comments are closed & hidden #}
{% endif %}


Custom logo for each organic group I want to add a logo (CCK image field) to the group nodes and show it when users visit that group.
Is there any module for that?

I write this module to render custom logo for each Organic Group:

function og_logo_block($op = 'list', $delta = 0, $edit = array()) {
    if ($op == "list") {
        $block = array();
        $block[0]["info"] = t('OG Logo Block');
        return $block;
    } else if ($op == 'view') {
        global $theme;
        global $node;
        $block['subject'] = '';
        $settings = theme_get_settings($theme);
        if (($node = og_get_group_context()) && node_access('view', $node)) {
            $block['content'] = l('title . '" title="' . $node->title . '" src="' . base_path() . $node->field_logo[0]['filepath'] . '" />', "node/$node->nid", array('html'=>true));
        } else if ($settings['default_logo']) {
            $block['content'] = '';
        } else {
            $block['content'] = '';
        }
    }
    return $block;
}


Is there a successor project to Omega 4? I'm a big fan of the Omega base theme, trying to make sense of what's going on with that project.

What I'm trying to do, is work with something similar to Omega 4 that is actively maintained on both 7 and 8 and will be capable of being upgraded to Drupal 8 in future.

I've read that there was a public falling out among the maintainers and that Omega 5 is progressing in a very different direction with different aims to Omega 4. I've also read that the Omega 4 maintainers are giving it minimal maintainence with many hints that their efforts will be focussed on other projects under other namespaces, and there have been no new dev releases since July 2015:

  Omega 4.x is still minimally maintained (I am committing bug-fixes and other critical / major patches). However, I am not interested in further moving on with anything under this namespace as stated previously in other issues. The reasons for that are well known and have been publicly discussed... There won't be any extended effort from me (and probably not from Matt either) to expand on the existing functionality of 4.x or even work on a new version... I will keep maintaining the 4.x version of course though so you can totally feel safe when using that at least.

Is there a new project that continues what Omega 4 was trying to achieve under a new namespace, that will be actively maintained on Drupal 7 and 8?

I've seen Khan described as "the omega 4.x successor for drupal 8", but it's had no work since 2014 and its project page is... baffling. It looks more like a Drupal community in-joke than a serious project. There's a thread with many people asking about this, but no clear answers.

I found what looks like an explanation from 2016. It looks like Omega 4 is not going anywhere.

  ...both new Omega versions (7.x-5.x, 8.x-5.x) probably have nothing in common with (7.x-4.x) and are not the successor of Omega 4.

  The successor to (7.x-4.x) is new project Khan so all the questions about that should be posted there. Truth to be told, there is not much activity there, since.

  So if you wish to make some sort of continuation of current 4.4 code base to D8, probably you will have to do it yourself. Personally, I do not think it will make much sense as the differences between D7 and D8 would not leave much in common.

The same user asked what the status of Khan is two months ago and hasn't received any reply. In another thread, the maintainer posted that Khan is postponed indefinitely:

  ...This is a serious project but since I am currently focusing on GraphQL for Drupal you can consider it postponed until I am done with the first release of that module.

So it seem fair to conclude that there is no Drupal 8 successor to Omega 4 at time of writing.

Life is too short for drama, so I personally am going to (reluctantly) drop Omega and switch over to Bootstrap.


How to enforce minimum height and width for image while resizing anything larger? We have a requirement where the minimum and maximum image resolution 480x480 for an image on upload. The reason is that we want the image to be resized to be exactly 480x480.

However, whenever we upload an image that is larger than 480x480, we are constantly getting the following error message. Even when i modify the maximum to be 640x480 i still get the error message for an image that is 1200x968.

Need some help figuring out what could be the issue as i have tried to modify the maximum image resolution to be slightly larger than the minimum image resolution, but still get the error message.

Reformatting an image won't happen on upload, it will happen on display of the content. If you want to reject anything less than 480x480, set that as the minimum in the field's setting and don't set a maximum size.

To resize the image, be sure there is an image style set to resize an image to 480x480 (which is included by default in Drupal 8). Then under the "Manage Display" field of the content type, click the gear next to the image field and select the desired image style that you want displayed.


Are user browser information and ip address available as tokens in Rules? I am sending an email to admin from contact form. In the email I want to send the user browser information like browser name and version and the user ip address. But I'm unable to see the tokens for these values?

I want the browser info and ip address for both logged-in and anonymous users.

Are these tokens available in the Rules module? Or I will have to create custom tokens?

Use [current-user:ip-address] token for IP address of the current user.

For browser related token you have generate it using token_generate API.

  function token_generate use to generates replacement values for a list of tokens.


Search API Autocomplete does not return any suggestions when input contains ąčęėįšųūž or similar characters I am using Drupal 7, Solr 4.x, search_api, search_api_autocomplete modules in project. We have a page, which contains fulltext search with autocomplete settings. Problem is - it does not return any kind of results, when these contain non utf characters, for example ąčęėįšųūž.

Install the Transliteration module and enable the homonymous processor for the index.


How to assign 2 taxonomy vocabularies in a single field for a node? I have a node. I want to manage fields of this node in the Admin, so I can have a field which is of type Term reference and which uses two or more taxonomy vocabularies. So I can make combinations of 2 vocabularies in the field.

Let's say I have vocabularies A and B. I want to have the field "Categories", which gives the option of choosing from vocabularies A and B. Now, in the normal behaviour of Drupal, I must select one and only one vocabulary when creating the field.

Usually is is not good to rely on modules what are not widely used (like Combined Termref), because of worse community support and maitainance.

Consider using Entity Reference module what can connect any type of entities together. You can use it almost the same way like Term reference field.

There propably will be some differences in configuration, but nothing critical (blocking use-cases), just less straightforward. Internally it will works the same - is saves entity ID of term into "term reference field".


Core Search Module in Drupal 7.14 and Hidden Fields In one of my content types I have a text field for extra zip codes served by clients that I have set to "hidden". My core search module does not seem to be indexing hidden fields. What's the deal?

This behavior is the correct behavior for Drupal search out of the box. The default search module only indexes fields that are not hidden in the default display view mode as Clive suggested on 8/10. This prevents anonymous users from searching and returning results hidden from their view, yet exposed via search. The exact mechanics of it vary in application from D6 to D7 but both use a concept of search index version of the node which is used to create the indexes in the database.  You can alter what the search indexes by modifying this view of the node.

In D6 you would be able to get around this by altering the node_api for the search index as shown here: http://drupalib.interoperating.info/node/246.

In D7 you can choose to enable fields to be indexed that are normally hidden in the default view.  Edit the content type and go to the manage display tab of that edit screen. Below the fields portion of that edit screen is a collapsed portion of the page for custom display settings.  Open this section and select the Search Index view mode. This will now allow you to alter the fields used to index the node.  Keep in mind the relevant results portion of the node will be blank in search results unless you also alter the search result view mode.  In this way you can have different results indexed than the visible fields in other node view modes.

You may also choose to implement the search api module, or make this field visible to the world in your default view mode and handle obscuring it through css or the theme layer.


When to use a tpl.php file instead of a .css file? This is my first question on Drupal answers, so be kind to me :)

I'm fairly new to Drupal, and indeed web developing in general.  I have been working on my first site for a few months now, learning as I go.

In the past month, I have figured out how to make my own sub-theme of the one I was using.  I have been using the sub-theme to adjust the "little niggles" that I have with page formatting directly.  So far, I have been doing this by adding little snippets of css to a .css file in the sub-theme - and trying to keep this file as DRY as possible.

This has been working well for me, but when reading around, all I see is discussion of modifying/using .tpl.php files, which is making me wonder if I'm missing something and/or setting myself up for major problems as this this .css file grows?

TL:DR What are the problems and/or disadvantages of using a single .css file to make styling adjustments on my drupal site?

If your real question is more along the lines of:

  Should I make the CSS conform to the markup, or make the markup conform to the CSS?

Then that's just a judgment call, there's no right or wrong answer. Go with what you feel comfortable doing. Some people love the plethora of classes Drupal adds by default, some people hate it. Some people prefer the Bootstrap approach (class, class, class), some people prefer the Susy approach (as few classes as possible, ostensibly). Neither is right or wrong, just different.

Read on for answers to the specific posed questions...

  When to use a tpl.php file instead of a .css file?

The literal answer to that is simply "never".

A CSS file and a template file are for different things, and contain different things. You wouldn't put markup in a CSS file, and you wouldn't put CSS in a template file (except perhaps in rare circumstances like if you were inlining the above-the-fold content or something).

  What are the problems and/or disadvantages of using a single .css file to make styling adjustments on my drupal site?

There are no problems or disadvantages per se. It's arguably better to split your CSS into multiple files, simply for modularity's sake, but those are all going to be aggregated back into one when the site goes into production mode anyway (assuming the CSS you're talking about is "every page" CSS; you haven't mentioned otherwise).

Basically go with what feels comfortable, by your organisation's standards, or whatever general advice you find and like about organising CSS files. Drupal doesn't mind how you do it.


How to print uc-auction-bid-table-form seperately in product node template using ubercart? I am trying to print uc-auction bid table separately in product node template. I have printed the add-to-cart button separately like this in the node--product.tpl.php.

<?php
 print drupal_render(drupal_get_form('uc_product_add_to_cart_form_'.$node->nid, $node));
?>

Similarly how can i print uc_auction form(uc-auction-bid-table-form) separately. I can't able to print like above for uc-auction because it doesn't have any nids associated it. Any help will be really appreciated.

Thanks in advance.

In your module which implements hook_node_view, to accomplish this, do something along these lines:

   function module_node_view($node, $view_mode, $langcode) {
      // Do business logic here like if these node should have the form then...
      $node->content['your_from'] = array(
        '#markup' => drupal_render(drupal_get_form('uc_auction_bid_table_form')),
        '#weight' => 10,
        // you may or may not need this based on your implementation : '#theme' => 'theme_uc_auction_bid_table',
      );
    }

Drupal 6: use hook_nodeapi

function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      // Do business logic here like if these node should have the form then...
      $node->content['uc_auction_bid_table'] = array(
        // Try drupal_render if theme does not work
       '#value' => theme('uc_auction_bid_table', drupal_get_form('uc_auction_bid_table_form')),
        '#weight' => 10,
      );
      break;
  }
}


Field modification using PHP I have a content type which contains field_state.  The nodes of this content type store the two letter abbreviation for the state in each node using field_state.  OH is Ohio, CA is California and so forth.  I need to render this field with the full spelling of the state name.  I have a PHP Array that contains all of the 50 mappings that I need like -- $state['CA'] = 'California'; This data structure is wrapped in a PHP function state_full_name($abbreviation).

I created a View which creates a block of everything I need -- except the full spelling of the state name.  I know how to apply a PHP functions to a specific Views field in both D6 and D7. The solution in D8 has been elusive for me.  I believe I need to use a Views plugin in some fashion.  Can you help?  Thanks!

A configurable or a base field? Either way, that's a perfect use case for using a list (string) field type, then you tell Drupal what the allowed values and its keys and labels are. Views will use that when displaying he field and everything will just work.

If you define your field in Code, instead of hardcoding the list in there, you can also specify a callback that will call your PHP function, in case you expect the list to change or if it is dynamic (allowed_values_function in the field storage settings). Although you can also turn that around and treat that field configuration as the canonical source for your information and if you need it in PHP, read it out from there.

If that is for some reason not an option, then you can implement a Views field Plugin and expose it to views using hook_views_data() hook. That's very likely a lot more complicated than using the right field Type for your use case, though.


Creating conditional fields: How should I implement hook_form_alter()? Backstory: I used and highly enjoyed Conditional Fields modules for D6 in the past. Currently using 7.x-3.x-dev. But had some issues recently with it and would rather just learn how to do it manually. Familiar with Devel, but had no luck successfully getting a complex hook_form_alter() to work. Always end up hitting a dead-end.

What are the fundamentals of implementing a hook_form_alter()?

I'd like to get this process laid out and in one single location. Thanks.

The Conditional Fields module's features can be done with using #states attribute from form api in D7.

If you want to implement it, of course you need to use hook_form_alter() to bring additionaly attributes on existing fields. There many tutorials about the usage of hook_form_alter().

Example of using of #states attribute:

  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

Example from Examples for Developers module - form_example module


How do I stop HTML entities appearing in an e-mail client's subject header? If I send an email with drupal_mail with the subject header:

Let's go

It appears in my email client:

Let&#39;s go

This is okay:

Let’s go

The most convincing explanation I've read is:

  The behavior you are seeing is because the subject line is being run
  through check_plain() (via t()), which calls the PHP function
  htmlspecialchars().

Here's the link.

What changes should I make to my hook_mail code to correct my header in the email client:

$message['subject'] = t('Let's go');

Code that threw the error:

$message['subject'] = t('@responder has responded to: @title', array(
  '@responder' => $params['responder'],
  '@title' => $params['title'],
));

you can use !responder and !title instead of @responder and @title in your code (by using ! instead @ or % it tells drupal to use the string as is ; by using @responder Drupal will run the string through check_plain to escape html characters).


How to display only the menu items and not the parent menu? I am trying to build on the footer a set of 3 menu links: About us, Terms of Use, Contact.

The problem is that I want to have only these 3 links as menus and I do not want their parent menu to be displayed. Can anyone help me on this?

When I do it, I can display the 3 links, but also their parent menu is shown.
I want to display only the submenu items:

MenuItem1

submenuitem1
submenuitem2
submenuitem3

Is that possible? Can The Panel module do this?

The Menu block module is the way to go.

Install the module
Go to your blocks page
Click on "Add new menu block"
Select your menu and the level you want it to show
Add that block to your footer region and you're set


Change default date format in input mask: Is it possible? I adapted the default date formats to the German needs, and I created a new date format for output. This works fine.

For the input, the Y-m-d format persists. How do I change this?
I've created a content type: "events".
I defined a field type of DATE:

In the manage form display I've set its witget to "Date and Time. There's no wheel to define dmY or other.

The result in input mask:

The only thing that works at the moment, is the widget switching to "date as a list" to get german notation.

Assuming the machine name of your content type is "test".
Please navigate to:
admin/structure/types/manage/test/form-display
You should see the following form (with different fields, of course).
In my example, the name of the field is simply "date" .
You can change the widget to Select list and then you will see the cog wheel on the right side of the row.
After clicking on it, you shall be able to choose your preferred Date Format.

Hopefully that helps.
Update 1: Regarding Update
In my default Drupal installation when I try to add date-based fields, I do have the following 2 options:

Date
Timestamp

Option Date
I have suboptions, "Date only" or "Date and time"

If I choose "Date and time" -> I am able to see the select widget as
option.
If I choose "Date only" -> I am able to see the select widget
as option.

Timestamp
I am able to see only Datetime timestamp

As a last thing:
Screenshot, showing the different type of fields in Manage form Display:

Update 2:
It seems the following article has it explained how to do the exact thing you are looking for:
https://www.previousnext.com.au/blog/making-drupal-8-datetime-widgets-use-human-formats


How can I adjust the position of a cancel button added with hook_form_alter()? Based on this answer, I added a cancel button to my user picture upload form like this:

  $types = array(
    'profile_picture',
  );

  foreach($types as $type) {
    if($type.'_node_form' == $form_id) {
      if(arg(1) == 'add') {
        // If adding node link to node/add screen
        $link = l(t('Cancel'), 'account/manage-pictures', array('attributes' => array('class' => array('form-submit','cancel'), 'id' => 'edit-cancel')));
      }
      elseif(arg(2) == 'edit') {
        // If editing node, link to node view screen
        $link = l(t('Cancel'), 'node/'.arg(1), array('attributes' => array('class' => 'form-submit, cancel', 'id' => 'edit-cancel')));
      }
      $form['cancel'] = array(
        '#type' => 'markup',
        '#markup' => $link,
        '#weight' => 0,
      );
    }
  }

However, this causes the red cancel button to be placed at the top of the form instead of the bottom of the form next to the purple save button as shown in the screenshot below.

When I examined the CSS in Firebug, I saw that the save button is under this div: <div id="edit-actions" class="form-actions form-wrapper">, while the cancel button is not.  Is there a way to place the cancel button under the same div as the save button?

Use the following code.
$form['actions']['cancel'] = array(
 '#type' => 'markup',
 '#markup' => $link,
);

If it doesn't work, check with print_r() where the submission buttons are added in the form array. Usually, it's $form['actions'], but sometimes can be a different array index.


Views Infinite Scroll content doubles up at end of scrolling I have a View, with Views Infinite Scrolling.  It seems to be working fine, except when I hit the end, the content doubles up.

One interesting thing is they are nodes rendered with Display Suite.  These nodes have an image.  When I hit the bottom and the duplicate nodes display, they are missing the image.  If I go into Firebug, or resize my browser, they display.

How can I fix this behavior?

I'm running Views 3, jQuery 1.8, and Views Infinite Scroll 7.x-1.1+0-dev.

After going through the code, I see it is because they don't handle the Responsive Grid Views extension, which I am using.  I just hid the duplicate items with CSS for now, and I'll go back and submit a patch to the maintainer later.


Validate a path within the site? I'm working on a module that accepts user-specified paths for special treatment. I want to have a validation step where I check whether that path actually exists on the site.

Is doing a query to the menu_router table sufficient? Is there a better way -- say, a Drupal function -- to validate a url?

Looking at the code for menu_edit_item_validate(), which is the function that validates the input from the user when creating a new menu item, you will notice it calls drupal_valid_path(). If that function is not enough, you could look at the code of menu_edit_item_validate() to see if that code can be useful to create your own validation function.

  $normal_path = drupal_get_normal_path($item['link_path']);
  if ($item['link_path'] != $normal_path) {
    drupal_set_message(t('The menu system stores system paths only, but will use the URL alias for display. %link_path has been stored as %normal_path', array('%link_path' => $item['link_path'], '%normal_path' => $normal_path)));
    $item['link_path'] = $normal_path;
  }
  if (!url_is_external($item['link_path'])) {
    $parsed_link = parse_url($item['link_path']);
    if (isset($parsed_link['query'])) {
      $item['options']['query'] = drupal_get_query_array($parsed_link['query']);
    }
    else {
      // Use unset() rather than setting to empty string
      // to avoid redundant serialized data being stored.
      unset($item['options']['query']);
    }
    if (isset($parsed_link['fragment'])) {
      $item['options']['fragment'] = $parsed_link['fragment'];
    }
    else {
      unset($item['options']['fragment']);
    }
    if ($item['link_path'] != $parsed_link['path']) {
      $item['link_path'] = $parsed_link['path'];
    }
  }
  if (!trim($item['link_path']) || !drupal_valid_path($item['link_path'], TRUE)) {
    form_set_error('link_path', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $item['link_path'])));
  }

If you need to verify if the anonymous user has access to the menu item, you can use code similar to the following one:

drupal_save_session(FALSE);
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

$result = drupal_valid_path($link, TRUE);

$GLOBALS['user'] = $original_user;
drupal_save_session(TRUE);

To change the code I shown from menu_edit_item_validate(), you should rewrite the last control statement as the following code.

  drupal_save_session(FALSE);
  $original_user = $GLOBALS['user'];
  $GLOBALS['user'] = drupal_anonymous_user();

  if (!trim($item['link_path']) || !drupal_valid_path($item['link_path'], TRUE)) {
    form_set_error('link_path', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $item['link_path'])));
  }

  $GLOBALS['user'] = $original_user;
  drupal_save_session(TRUE);

This is the only possibility you have, if you don't want to rewrite all the code Drupal uses to verify if a user has access to a menu item, as that code verifies the currently logged-in user has access to the menu item, not a user for which the user object is passed to the code.


Entity Form to insert data into Custom Entities I am finally getting to Entity Construction Kit. I have built out my entity with fields, I have also set up a feed to import data into the entity.

However, I also need to build a form that will push data into the entity fields in the database. I need to know how to do this. I have search and have yet to find anything that explains or shares knowledge on how to handle this.

Has any built a form that will insert data into the database without a custom coded module?

I do not want to add data from the 'entity list' tab. I actually have a use case where I need to insert several rows of the same thing. So, for instance when doctors show up at an event yet they don't give us there information I still need to insert 5 MD's showed up for the event.

Hopefully this makes sense. Any help is greatly appreciated!!!

this sounds like something Views Bulk Operations or Rules could do, eg you make a "url link" (with Rules Link module) to call an action to add a doctor to an event. You could make more than 1 link, and ever link could have a custom ?number_of_doctors=N value on it to update the Entity with N number of blank doctor entries.


how to join two field together i have a content type named product. i need to add product like this:

title: product1

description: this is a product

company:a
price:100

company:b
price:200

company is a node reference field with numbered of values set to unlimited and price is a text field but i don't know how relate price field with company.

if i can't do something like this in drupal 6, drupal 7 help me?

If you use CCK ver 3.x you get the multigroup submοdule. This allows you to create a group of fields like in you case company and price and then create multiple instances of this group.

UPDATE

CCK ver 3.x is alpha. However I have used it in production without problems. You could look into the issue queue for bugs in the 3.x version before you use it.

If you are creating a new site I would suggest going with drupal 7. CCK has moved to core in drupal 7 but the functionality of multigroup does not exist.
However you can achieve a similar result using the Field Collection module. Looking at this http://oliverdavies.co.uk/blog/2011/08/create-multigroups-drupal-7-using-field-collections or this http://mostrey.be/creating-multigroup-widgets-drupal-7 will find out how.


Forgot to do config ignore before building webform. How to correct it and ignore the webform from the export? Complete newbie to Drupal here. I forgot to configure my config ignore before I built a webform.
I have now managed to do add webform.webform* to the config ignore but that doesn't solve my problem since the webform has already been exported.
How do I fix the import/export settings in order to remove the webform?

Thanks all for your reply and apologies for my late response. Yes, I am using config_ignore and config_split module. I just added webform to config_ignore and then deleted the files from the git repository so next time they will not be added to git. Worked.


Removing a field from the new content form I have created a content type which consists of a title a .zip file and a screenshot using Drupal 7's site builder.

When a user adds an instance of this content type I would like for them to only have exposed fields for the .zip file and the title.  I have a custom module that unzips the .zip file and does some analysis and I would like to extract the screenshot at this time.

Is there anyway that I can have the new content form of my content type not show the screenshot field?

Three good options:

Display Suite has a feature to hide fields from the form
You can use hook_form_node_form_alter to remove the field

Edit: per Clive's suggestion, set ['#access'] = FALSE instead of unset($form['field_zip_file'])

Create a new module, (create MY_MODULE.info, MY_MODULE.module), and add this to MY_MODULE.module:

<?php

  function MY_MODULE_form_node_form_alter (&$form, &$form_state, $form_id) {
    if ($form['#node']->type == 'my_content_type') {
      if ($form['nid']['#value'] == '') {
        $form['field_zip_file']['#access'] = FALSE;
      }
    }
  }

Use CSS to make it disappear:

Add this to your theme's CSS file:

body.page-node-add #edit-field-zip-file {
  display: none;
}


How do I export an entity? In Drupal 7, with the aid of features, we could do something like node_export, or uuid_features, etc.

I'm looking for a good way to create content / other entities using the UI and export it to code some how using Drupal 8 so that I can put into an install or update hook so that our site builders don't miss pieces of configuration.

I know we can do it programatically. And I'm all for that. I would just like an easy way to generate the Array we need to stick in our install or update hooks.

You want the Default Content for D8 module, which provides drush commands to export and installs the content on module install. From its project page:

Default content gives your module and install profile a way to ship default content as well as configuration. Powered by core's serialization, rest and hal modules.
Features

Supports entity-references between content.
Supports files if you have File entity
Easily export your content and its dependencies to yml using drush commands.


MAMP Pro and Drush mem exhaustion I have mamp 6.0 installed. When trying to
drush up
and confirming "yes", I get:

  PHP Fatal error:  Allowed memory size of 33554432 bytes exhausted
  (tried to allocate 12288 bytes) in /Users/me/Sites/jla
  copy/sites/all/modules/contrib/ctools/includes/stylizer.inc on line
  911 Drush command terminated abnormally due to an unrecoverable error.
  [error] Error: Allowed memory size of 33554432 bytes exhausted (tried
  to allocate 12288 bytes) in /Users/me/Sites/jla
  copy/sites/all/modules/contrib/ctools/includes/stylizer.inc, line 911
  Your memory limit is set to 32M; drush needs as much memory to run
  as[error] Drupal.  Please check your configuration settings in
  /Applications/MAMP/bin/php/php5.4.10/conf/php.ini or in your drush.ini
  file; see examples/example.drush.ini for details. The external command
  could not be executed due to an application     [error] error. Illegal
  string offset 'site' backend.inc:1013                        [warning]
  The command could not be executed successfully (returned: PHP Fatal
  [error] error:  Allowed memory size of 33554432 bytes exhausted (tried
  to allocate 12288 bytes) in /Users/me/Sites/jla
  copy/sites/all/modules/contrib/ctools/includes/stylizer.inc on line
  911 , code: 255)

This is the result of my drush status:
 Drupal version                  :  7.10
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database username               :  root
 Database name                   :  jla_d7
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  jlasitetheme
 Administration theme            :  seven
 PHP executable                  :  /Applications/MAMP/bin/php/php5.4.10/bin/php
 PHP configuration               :  /Applications/MAMP/bin/php/php5.4.10/conf/php.ini
 PHP OS                          :  Darwin
 Drush version                   :  6.0
 Drush configuration             :
 Drush alias files               :
 Drupal root                     :  /Users/me/Sites/jla copy
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /Applications/MAMP/tmp/php

I know that I have set a 128MB memory_limit in the MAMP php5.4.10 file.

n.b. The error message says that your memory limit is 32MB, not 128MB.  The 128MB setting must be for your web server.  Check the php.ini for PHP CLI; it's quoted in the output of Drush status, above:  /Applications/MAMP/bin/php/php5.4.10/conf/php.ini.  You should find that memory_limit is 32M, or perhaps unset.  Set it to 128M, or perhaps even 256M or more, and you should be fine.


what is the URL I should use to edit a user account? I need to edit user account data via services module

I tried endpoint/user, endpoint/user/UID, endpoint/user/UID/edit, endpoint/user/update, endpoint/user/edit

with args like in user_resources.inc

It returns 404user not registered

despite successfully loggedin

$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;

// User data
$user_data = array();
$user_data['uid'] = $logged_user->user->uid;
$user_data['data']['name'] = 'test4';

$data = json_encode($user_data);

// cURL code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/html/mob/api-    mob/user/".$user_data['uid']);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data), mymodule_get_csrf_header())
);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

what I am missing here or if one could do it via services please provide an example

To update a user with Drupal Services, you make a PUT call to:

?q=[my-endpoint]/user/1.json

Replacing [my-endpoint] with the machine name of your Service endpoint. Here's some example JSON to PUT:

{
  "uid":"1",
  "name":"bob",
  "mail":"bob@hotmail.com",
  "current_pass":"secret",
  "pass_pass1":"new-secret",
  "pass_pass2":"new-secret"
}

You must also attach a header to your call with a name of X-CSRF-Token using a value that can be retrieved here: ?q=services/session/token


In a Rule, how can I prevent executing subsequent actions if the first action fails? In a Rule, how can I prevent executing subsequent actions if the first action fails?

In my case, I want the order to be marked as Processing only if the order was successfully transmitted to the fulfilment center. I've tried returning FALSE from the action but this has no effect.

To provide conditional logic, you need the Rules Conditional module.

There's an open issue to document this further, and there's another meta issue which looks at integrating the conditional logic into the Rules module itself.

  This module provides Rules plugins for conditionally altering execution flow directly inside a group of actions. Provided plugins include:

Conditional
    If/(Else) If
    Else
Switch
    Case
    Default case
While


Contextual Filters in a 'Tree-style' View I am using the Views Tree Module which allows me to create a View that illustrates parent-child relationships.
My 'associations' go like this:
I have 3 content types which entity-reference each to a single direction.

A Sub task has an EntityReference field pointing to a Main
Task and a Main Task has an EntityReference field pointing
to a Project.
  Subtask -> Main Task -> Project. (associations are done with EntityReference fields)

Now I'd like to embed this view as a block within a given Project's page. Naturally I use a Contextual Filter that uses the ContentID from Url setting.
I thought this would allow me to view within that Project's page the Main Tasks and Sub Tasks that belong to it, but since only the Main Tasks are directly connected with the Project itself only the Main Tasks are shown.

The question:
Is there any way to bring the Subtasks(which belong to the Main Tasks that belong to the given Project) to show as well?

Summary of my project
To sum this up:
I have 3 content types

Project
Main Task
Sub Task

A Subtask entity references a Main Task and this in turn entity
references a Project
I use the Views Tree module to list the Main Tasks and the Subtasks
below each Main Task(in a 'tree-style' view
I want to show this view with the appropriate Main Tasks/Subtasks
inside each Project page.
I use the Views Tree module to construct parent-child relationship
Views

I found a rather clean and intuitive solution, however I am very interested in other, more straightforward answers if they exist.

I created a new Computed Field, called parent_project_computed field which:

calculates the parent-project based on the parent_main_task
field(which is entity reference) if it's a Sub Task content type
calculates(basically just copies) the parent_project field if
it's a Main Task content type

This way both the Main Task and Sub task have a field which stores the nid value of the Parent Project. Then I use a contextual filter based on this new parent_project_computed field and both content types match this filter so they show up in the results just fine.

This is the PHP I wrote within this new computed field:

$entity_field[0]['value'] = null; //initial value null, should get overwritten in IF's below

//if field_parent_project exists just copy it's value
if (array_pop(array_pop(field_get_items($entity_type, $entity, 'field_parent_project')))) {
   $entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_parent_project')));
}

// if 'field_main_task' exists get it's value, load the node and get the E-R value within it
if (array_pop(array_pop(field_get_items($entity_type, $entity, 'field_main_task')))) {
    $nid = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_main_task')));
    $node = node_load($nid);
    $info = field_get_items('node', $node, 'field_parent_project');
    $entity_field[0]['value'] =$info[0];//ER fields store data in array, since this is a single value ER field it always sits at position '0'
}

//Note: E-R value means Entity Reference value.

If the PHP code can be made more, err bulletproof, I'd appreciate a comment below.
Thanks.

Update:

On saving each Task you need a post-save custom hook to reload and resave all the Subtasks in order to update their 'Parent Project' computed field which has now changed. We've used this module which provides some nice additional post-save hooks and some more.


Service module costume response after creating node I want to get costume return from services module after creating a node.
I would like to checks if the there is a similar title, and if so, to return the number of times it exists.
(Services 3 / Drupal 7)
What is the way to do this?

You have following hook to do the response modifications,

function hook_services_request_postprocess_alter($controller, $args, &$result) {

}


Is there a way to trigger migration imports from the admin UI? I want to use module WordPress Migrate to import content from WordPress into my new Drupal 8 website. I can use the module's button "+Add import from WordPress" appearing on page admin/structure/migrate to create a new import group from a WordPress XML file. That is working alright.

After I create that Migration group, I can enter its details page. It will then display all migrations I may run from Wordpress.

What I can't do through admin interface is actually running the import. It is said that the absolute best option for this is running the import script on Drush and I can do that on my Docker local environment by running:

drush mi --all

I could also specify the name of the import group I want to use, but this is not the point here.

My question is: although it is not recommended because a PHP script could timeout etc., is it possible to run the import from within UI? I will import ~ 200 posts from Wordpress, which is not a daunting task for the website and I don't see any risk for script timeout.

Anyway, I can't find a command button or link to trigger the import process from UI. Why do I want to do that? Because my website will be hosted on a shared host where I don't have access to Drush commands.

In case such an option isn't available, what would you say are my options here? Create a custom module that would run this import only once? Is this a simple task to take over?

A general migration runner in the UI is not yet implemented - the issue to add this is at https://www.drupal.org/node/2470882.


How does Drupal verify sessions from the cookie value? Sorry, I know it's weird, but I'm trying to integrate another php application with Drupal.  I want to know if the user is currently logged in to the Drupal site, even though the request is going elsewhere.  I'm getting the cookie out of a Guzzle request object.  As far as the application is concerned (because of Nginx proxying), the origin is the same, and the cookie is getting passed successfully.

Here's what I'm getting out of the Guzzle request object:

array(1) {
  ["SSESSdbf18a05343cfb88719ee68ff6159a52"]=>
  string(43) "5eW8YPdDPjojAjuokObuD5R2L7cyOfffmBuVAdHzWwU"
}

The above value is also what the browser reports.

But, in my sessions table in the DB, there is no session that resembles this, either in the sid or the session column.

How does Drupal check the DB for a valid session cookie, and where should I be looking in core to copy this?

I figured it out, but if someone posts a more in-depth answer, I'll accept it.

Drupal has a SessionHandler with a read function:

public function read($sid) {
    $data = '';
    if (!empty($sid)) {
      // Read the session data from the database.
      $query = $this->connection
        ->queryRange('SELECT session FROM {sessions} WHERE sid = :sid', 0, 1, [':sid' => Crypt::hashBase64($sid)]);
      $data = (string) $query->fetchField();
    }
    return $data;
  }

And, if you bootstrap Drupal, or call an external Drush script, you can do this:

$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$logged_in = (bool) $session_handler->read($session);

Here's how I got the cookie out of the Guzzle object:

$request->getCookies();
//var_dump($cookies);
foreach($cookies as $cookie){
  if(strpos($cookie, "SESS") == 0){
    $session = $cookie;
  }
}

If you actually want the UID, you're going to have to not do the (bool) cast and de-blob the thing, because it returns the raw MySQL data.


How to query the last 5 nodes of multiple content types? I want to query last 5 nodes of multiple content types, say, typeA, typeB, typeC, typeD.

It was originally only one content type, and I did it using EntityFieldQuery:

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'typeA')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 5);

$result = $query->execute();

But now I need to include 3 other content types to the list.

Is there any way to expend this query to include the last 5 nodes of the other 3 content types as well. So that the result will have 5 last nodes from all 4 content types, altogether 20 nodes.

Or should I do it with 4 individual queries?

I think the only thing you need is alter the second line of your EntityFieldQuery to this:

->entityCondition('bundle', array('typeA', 'typeB', 'typeC', 'typeD'), 'IN')

Haven't tested this particular though, but you can query multiple content types this way.

Cheers

EDIT: Maybe this can help you more: https://www.drupal.org/node/2048345


Entity Reference. Hide not user referenced terms in node form? This is my 2nd question about my problem, the last was "Users have access to add Commerce Products into the Store and publish it. How to display to user only allowed firms in the product addition form?"
 I am writing my 6th module and I do not know nothing about form fields arrays.
I need to display in node addition form only user referenced terms in field Firms.
Taxonomy "Firms" has field_seller of type Entity Reference. I add to all Firms terms users that must have access to them. How can I display to user only those terms that have reference to this user when he add node Product ?
I've made this code that has only correct name (I've checked this with other funcions that was in it and worked):

/* Displays only terms that have Entity Reference field with current user reference */
function user_referenced_taxonomy_terms_form_node_form_alter(&$form, &$form_state, $form_id) {
  //$form['field_firm']
}

how to get array $form['field_firm'] of terms that have reference to current user if the user role is not admin?

I solved this task with my module:
This code limit radiobuttons of field_firm on the node addition page with only those terms that have entity reference to current user. Admin have access to all. If user has no one term access field Firms hides.

/* BASE_FORM_ID : node_form */
/* Displays only terms that have Entity Reference field with current user reference */
//$form['field_firm']['und'][1551]= array('#access' => FALSE); //hides taxonomy term 1551

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

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }
  if (isset($form['field_firm'])) {
    $query = new EntityFieldQuery();
    $term_entities = $query
      ->entityCondition('bundle', 'firms')
      ->entityCondition('entity_type', 'taxonomy_term', '=')
      ->fieldCondition('field_seller','target_id',$user->uid) // if user has access
      ->execute();
    if ($term_entities) {
        //forming array of firms using $term_entities array
         $items = array_keys($term_entities['taxonomy_term']);
         foreach ($form['field_firm']['und']['#options'] as $key=>$value) {
             if ($key == '_none') continue;
             $delete=true;
             for ($i=0;$i<count($items);$i++) {
                 if ($key == $items[$i])  $delete = FALSE;
             }
             if ($delete) $form['field_firm']['und'][$key]= array('#access' => FALSE);
         }
    }else {
        //hide field firm if user has no access to any term
        $form['field_firm']['#access'] = FALSE;
    }
  }
}


Custom html.tpl.php from module for custom type I have built a module that adds a new custom content type.
I need to use my own html.tpl.php for that content type, and the html template sits on my module folder.

I have done somee xperiments, I was able to replace the template of the node content, but it's not enough, and I can't seem to find some examples or explanatory documentation about it.

If my module is called "tomato" and my custom type is called "sauce", and I already have a file called html--sauce.tpl.php on my module folder, how do I tell Drupal to use that template when a "sauce" node is loaded?

Modules can use hook_preprocess_html() to override theme templates. You need 3 things:

A hook_preprocess_html() implementation
A hook_theme() implementation
A html template in your module dir

Using a module called MYMODULE, with a new node type mynodetype, & a template in the module dir named templates/html--mynodetype.tpl.php, we can add the following hooks to MYMODULE.

/**
 * Implements hook_preprocess_html().
 */
function MYMODULE_preprocess_html(&$vars) {
  $node = menu_get_object();

  // Add a new theme suggestion when viewing node's of mynodetype.
  if ($node && $node->nid && $node->type == 'mynodetype') {
    $vars['theme_hook_suggestions'][] = 'html__mynodetype';
  }
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();

  //Add our templates/html--mynodetype.tpl.php to the theme registry
  $theme['html__mynodetype'] = array(
    'template' => 'html--mynodetype',
    'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
  );
  return $theme;
}


site redirecting to core/install.php after migration I have migrated my site to different server and I am redirected to install.php page.

Here is the steps I have done:

zip whole site and extract it in new server.
export database and import it to new database (using phpmyadmin)
modify database credential in site/defaults/setting.php

any idea why drupal redirects to install page?

I encountered the same issue today (my site kept redirecting to install.php after migration to new host) and spent half-a-day troubleshooting.
The db connection was OK. I double-checked that the db-name, db-user, and db-user-pass are correct in the site/defaults/setting.php
In the end, it turned out that when I exported the database from my previous hosting, the names of the tables were prepended with a prefix. After importing the tables in the new database, I didn't specify the prefix in the settings.php file. Therefore, drupal was not able to locate the correct tables, because it looked for the users table but in the db, that table was actually named prefix_users and so on.
$databases['default']['default'] = array (
'database' => '',
'username' => '',
'password' => '',
'prefix' => '!!!',
'host' => 'localhost',
'port' => '',
'namespace' => 'Drupal\Core\Database\Driver\mysql',
'driver' => 'mysql',
);
Hope it helps!


drupal_add_js settings and working around the anonymous page cache What I'm trying to do is allow registered users to configure a few colors on public facing pages (profiles, etc.) and to do so I'm using the ColorField module and a few theme functions.

My problem is that the anonymous page cache is caching values stored in Drupal.settings, preventing changes from being visible until the page cache is cleared.

Here is the code I currently use to set Drupal.settings:

<?php
function themeName_preprocess_page(&$vars) {
  $branding = array(
      'header_bg' => '#ffffff',
      'accent' => '#0b40ac'
  );
  drupal_add_js(array('pageRebranding' => $branding), array('type' => 'setting'));
  drupal_add_js(drupal_get_path('theme', 'themeName') .'/js/branding.js');
}
?>

Disabling the anonymous page cache (globally or selectively) is not an option.

Is there a way I can pass values to Drupal.behaviors using ajax on page load, or another method to get around the anonymous page cache?

Here is my JS:

(function ($) {

    Drupal.behaviors.pageRebranding = {
        attach: function (context, settings) {
            var header_bg = Drupal.settings.pageRebranding.header_bg;
            var accent = Drupal.settings.pageRebranding.accent;
            /* Do Stuff */
        }
    };

})(jQuery);

You can avoid the cache by calling your file using

drupal_add_js(drupal_get_path('theme', 'themeName') .'/js/branding.js', array('cache' => FALSE));


node form validation not called I would like to add some custom validation to a node form.
But for some reason the validate function is skipped, the submit function does gets called.

/*
 * Custom Form settings
 */
function frontpage_banners_form_promo_banner_node_form_alter(&$form, &$form_state, $form_id) {

  $form['#validate'][] = 'frontpage_banners_form_promo_banner_node_form_validate';
  $form['#submit'][] = 'frontpage_banners_form_promo_banner_node_form_submit';

  dpm($form_id);
  dpm($form);

}

function frontpage_banners_form_promo_banner_node_form_validate(&$form, &$form_state) {

  drupal_set_message('error');

  form_set_error('', t('Email must be valid format if entered.'));
}

function frontpage_banners_form_promo_banner_node_form_submit(&$form, &$form_state) {
  drupal_set_message('submit');
}

I tried several function names but nothing seems the work.

From the $form array:

#validate (Array, 2 elements)
0 (String, 18 characters ) node_form_validate | (Callback) node_form_validate();
1 (String, 54 characters ) frontpage_banners_form_promo_banner_node_form_v... |

Found the problem, i use the More buttons module and there seems to be something wrong with way the hook_form_alter is handled in the module, fortunately there is a fix.


Outputting node fields individually I have a node template but instead of outputting $content, I want to have more control over what the template displays by printing each field individually.

Below are the fields I want to include:

$title
field_img
$body

What code would I replace  with? Also, are there any significant disadvantages to using this method?

If you already have a custom node template (tpl file) to theme your node then you're halfway there.  You can use <?php print_r($node); ?> to see the node structure and find out how to print your fields.

For example, to print those 3 fields, you can use something similar to:
<?php print $title; ?>
<?php print $node-field_img['view']; ?>
<?php print $node->content['body']['#value']; ?>

Remember to use the print_r($node) to check the structure and print the fields similarly as above while including the HTML for the layout.


Panels Custom Context I have created a Panels Everywhere variant that uses a single View with a contextual filter (Content Type). The Panel variant is set to page paths. These paths are related to content types. For example:

Path:

drivers (list of 'driver' Content Type)
lawyers (list of 'lawyer' Content Type)

So if I go to /drivers the Context of Content Type 'driver' should be passed to the View, etc. I know this is possible as %user context is a variable object; therefore, I should be able to create another variable object and pass this to the View. The problem is that I don't know where to start :( Any ideas?

Large parts of the question doesn't actually make sense to me, but...

If you want to pass an arbitrary part of the URL as a string to a View, just assign that variable part to a string in the argument settings, and then set that argument, %url_from_string, as the argument to the View.

The better solution though, would be to create a new context type called 'content type', because I don't think a context like that is available out of the box, and then assign the argument to that instead. That allows you to do validation of the incoming context and gracefully handle an argument that's not valid.

A third solution, though mostly a workaround, is to tell the View to pull it's arguments directly from the URL. This setting is available for all content pane displays under their argument settings.


SQL insert in taxonomy_index doesn't work I used the following code, but it doesn't work, and I get no errors.

$query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
$query->values(array(
  'nid' => $node->nid,
  'tid' => 53,
  'sticky' => 0,
  'created' => time(),
));
$query->execute();

dvm($query);

if (!$query) {
  dvm($query);
}

The output of this code is the following.

$query = db_insert('taxonomy_index')
  ->fields(array('nid' => 27, 'tid' => 53, 'sticky' => 0, 'created' => time()))
  ->execute();

dvm($query);

if (!$query) {
  dvm($query);
}

This code doesn't output any error; dvm($query) outputs '0'.

$row = new stdClass();
$row->nid = 27;
$row->tid = 55;
$row->created = time();
drupal_write_record('taxonomy_index', $row);

This gives the same result of the previous code.

$arr[] = 55;

db_query('INSERT INTO {taxonomy_index} VALUES  (%d, %d, %d, %d)', 27, 55, 0, time());

It doesn't work; It outputs the following error message.

  Recoverable fatal error: Argument 2 passed to db_query() must be of the type array, integer given, called in D:\OpenServer\domains\boobon\sites\all\modules\backup_bike\backup_bike.module on line 214 and defined в функции db_query() (строка 2342 в файле D:\OpenServer\domains\boobon\includes\database\database.inc).

I have installed the Ubercart module.

I think in D7, you can not use db_query() for insert operations - db_query() can be used only for Select and you should use db_insert() for insert operation.

For your 1st code bloc, perhaps the db_insert() causes 1st row with blank values - since it expects fields and values for 1st row. The subsequent $query->values() adds a second row. This may explain the blank values in dvm().


check box with dynamic content and error with submit handler I have written a form that displays data with check boxes, I want the selected values to concatenate into a string. From the submit button the string would be passed as a URL.Inside the submit handler I tried navigating to localhost but the page doesn't navigate.I this error 'An illegal choice has been detected. Please contact the site administrator.'

Note: I am using a third party software which opens a port on the server and accepts the concatenated values.

  function basket_form($form, &$form_state) {
 // Build Breadcrumbs.
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), '');
   // Link to current URL.
    $breadcrumb[] = l(drupal_get_title(), current_path());
   // Set Breadcrumbs.
   drupal_set_breadcrumb($breadcrumb);

   // Check for empty session.
  if (!isset($_SESSION['basket']['items'])) {
      drupal_set_title(t('Your basket is empty'));
      $form['empty'] = array(
      '#type' => 'markup',
      '#markup' => t('There is nothing in your basket at the moment.'),
     );
   }
  else {
    $form['clear'] = array(
    '#type' => 'submit',
    '#value' => t('Clear the basket'),
    '#name' => 'clear',
    '#href' => 'basket/clear',
   );

    $form['items']=array(
    '#type'=>'fieldset',
    '#title'=> t('Select from the following')
    );
    foreach ($_SESSION['basket']['items'] as $nid => $data) {
    GLOBAL $url;
    if(strlen($nid)!=0){
      $values = array(
     'biomaterial_id' => $nid
      );
     $features = chado_generate_var('biomaterialprop', $values);
     foreach($features as $f){
       if (preg_match("/bamURL/", $f->type_id->name)){
          if (preg_match("/http/", $f->value)){
             $url=$f->value;
            }
          }
       }
      if(strlen($url)!=0){
        $form['items'][$nid]['name'] = array(
        '#type' => 'checkbox',
        '#title' => t("$data[name]"."(bam))"),
        '#options' => array (
         $url => $data['name']
       ),
     );
   }
    else{
       $form['items'][$nid]['name'] = array(
       '#type' => 'checkbox',
       '#title' => t("$data[name]"),
     '#options' => array (
          1 => $data['name']),
      );
    }
   }
 }
   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'IGV',
   );
  return $form;
 }

function basket_form_submit($form, &$form_state) {
    //concatenation help, I tried printing $form_state couldn't see
     anything.
    //"drupal_goto('http://localhost')
    drupal_goto('http://localhost:60151/load?file=concatenated string')
   }
 }

Make sure you understand the processing flow of drupal forms. See an illustration here for example: https://www.drupal.org/node/165104

The basic flow is like this:

First request

Form build to represent the form to the user
User hits submit which results in a new request to the server

Second request

Form gets rebuild by calling the form builder (basket_form)
Form gets processed (validate and submit handlers are called)

The error message that you see results from the fact, that after the user hits the submit button, the form is first rebuild. Because you are using the $_SESSION to store your values (you should use the $form_state['values'] array instead) the checkboxes will not be build. And when drupal processes the form after the internal rebuild, it recognizes, that form items have been submitted that are not part of the form.

Also this might help: http://proofgroup.com/blog/2008/jul/debugging_mysterious_illegal_choice_has_been_detected_please_contact_site_administrato


Add another button for UI field set in admin I feel like I must not have the correct terms when searching on this topic.  I am relatively new to Drupal.  What I need to create is a field set in admin which has an Add Another Foo button so any given node could have as many Foo field sets as desired.  These would be draggable to sort for the node and accessible for the public facing twig to display.

Can someone help me with the terminology for this and if there is a tutorial on implementing I would really appreciate a link!

Example gui:

You're looking for the Paragraphs module.

You can use it to create a paragraph type with the required fields in it (reference, specification, etc), than add a multi-valued field to your node type referencing that paragraph type.

Because it's a field, you'll get the standard add another and sorting functionality.

The How to start with Paragraphs for Drupal 8 docs page should get you going pretty quickly.


IE9 & Drupal Form with in iFrame I know, wrap your head around it! Heh. I am having an issue in IE9 when trying to submit a form button via Drupal 7 & Drupal Commerce.

Example: http://www.um-me.com/frame.html

I have the following Drupal form source code

<form class="commerce-add-to-cart commerce-cart-add-to-cart-form-8" enctype="multipart/form-data" action="/band/4/band-ninjas?fb=TRUE" method="post" id="commerce-cart-add-to-cart-form-8" accept-charset="UTF-8">

        <input type="hidden" name="product_id" value="8" />
        <input type="hidden" name="form_build_id" value="form-oJeTHBh1Qn5myvhzMEgLvG5B6zY0vN7So0iQ4M3bazY" />
        <input type="hidden" name="form_token" value="psKsdV22J3T3ybyHXCJifIVlmdjhmlIM8u8iun9WLvQ" />
        <input type="hidden" name="form_id" value="commerce_cart_add_to_cart_form_8" />

        <input type="hidden" name="quantity" value="1" />
        <input type="submit" id="edit-submit" name="op" value="Add to cart" class="form-submit" />

</form>

This is taken directly from Drupal. I am using it as a method to test. The actual live (also non working in IE9 version) of this is here: https://www.facebook.com/dijitl/app_187714134672420 (click the buy button)

This works in all of the other major browsers, but for some reason it does not work in IE. I have tried a "normal" non-drupal form within an iFrame and it worked fine in IE, which leads me to believe that Drupal needs something from the form that IE is not giving it.

This looks like a security problem to me.  I examined the headers being sent by IE and the session variable in the cookie doesn't appear to be getting set/transmitted.  This is because IE has strict rules about cookies in iFrames, whereas Firefox does not.  Without the session variable, your cart is not being saved.  I would take a look at this related question: https://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer and apply the solution presented there.  It should solve your problem.


DrupalDefaultEntityController invalid argument supplied for foreach Been trying for the last hour to work this one out.

$query = new EntityFieldQuery();
$query -> entityCondition('entity_type', 'node')
       -> entityCondition('bundle', 'subscription');

$results = $query->execute();

if(isset($results['node'])) {
    $subscription_nids = array_keys($results['node']);
    $nodes = node_load_multiple($subscription_nids, TRUE);
    return $nodes;
} else {
    return FALSE;
}

This is a very simple version of the entire query, but the error is exactly the same:

Warning: Invalid argument supplied for foreach() in DrupalDefaultEntityController->buildQuery() (line 290 of /var/www/ml/data/www/ml.mailapproved.com/includes/entity.inc).

I don't understand what's wrong here.

The 2nd argument for node_load_multiple() is an array of conditions; currently you're providing a boolean so when the buildQuery function tries to iterate over the variable you get a warning.

The 3rd argument is to reset the cache (I guess that's what you're trying to do), so the call should be:

$nodes = node_load_multiple($subscription_nids, array(), TRUE);


Getting Drush to play with MAMP and Acquia I have a Mac workstation which is shared between two users, User°1 who first installed the machine, and User°2 who came along after, both administrators. User°2 has installed Drush using brew and Acquia Drupal and all this works very nicely. However, when User°1 tries to start Acquia Drupal he just gets an alert box saying that the Apache server failed to start - nothing shows up in the Apache error logs (the MySQL server starts ok though). I can't help thinking this is something to do with permissions, but no idea where to look.

So user n°2 has installed MAMP and that all works ok except for one thing: running Drush.
Here is an example:

imac:~ martinknapp$ drush @eco pm-info views_bulk_operations
Extension        :  views_bulk_operations
Project          :  views_bulk_operations
Type             :  module
Title            :  Views Bulk Operations
Description      :  Provides a way of selecting multiple rows and applying operations to them.
Version          :  7.x-3.1
Date             :  2012-12-03
Package          :  Views
Core             :  7.x
PHP              :  5.2.4
Status           :  enabled
Path             :  sites/all/modules/views_bulk_operations
Schema version   :  6002
Files            :  plugins/operation_types/base.class.php, views/views_bulk_operations_handler_field_operations.inc
Requires         :  entity, views
Required by      :  admin_views
Permissions      :  none
Configure        :  Aucun(e)

It appears to be running PHP5.2.4 (which I believe is almost certainly the reason I am constantly getting errors on db objects).
I've done everything I can to get this working, in particular by using the alias command like so:
alias drush='/Applications/MAMP/bin/php/php5.3.27/bin/php /usr/local/Cellar/drush/6.2.0/libexec/drush.php'
but all to no avail.

Any ideas?

when User°1 tries to start Acquia Drupal he just gets an alert box saying that the Apache server failed to start - nothing shows up in the Apache error logs (the MySQL server starts ok though).

Have you ensured you are only running a single apache process as OSX ships with it's own version and MAMP also has it's own. You can confirm it by running ps aux | grep apache in your shell.

Additionally, you can check which version has priority on the system (based on $PATH) by running which apachectl in a shell (example output).

$ which apachectl
/usr/sbin/apachectl

Which will help you determine that if there are conflicting version trying to run, who will be serving the requests.

  I've done everything I can to get this working, in particular by using the alias command
  like so:
  alias drush='/Applications/MAMP/bin/php/php5.3.27/bin/php
  /usr/local/Cellar/drush/6.2.0/libexec/drush.php'
  but all to no avail.

I am not sure whether you should be executing that drush.php file directly as all of the installations I have ever completed all point to an executable that I usually move the /usr/bin or /usr/local/bin for system wide availability - But then again, I haven't tried installing drush 6 yet so that could have changed.

If you do a bit of development and don't like dealing with issues like this, I recommend you look at virtualising your environments using a tool such as Vagrant. Doing this will allow you to build an isolated development environment where you can configure the environment then package it for reuse should you ever need to reset it.


pathauto_clean_string and accents from a bootstrap PHP file I have a single PHP file which makes a bootstrap of Drupal 7. The code is below. When I try to use pathauto_clean_string in a spanish string with accents (á é ... , etc.) it deletes the character instead of removing the accent using transliteration module (also affects other special chars, obviously). I have included also this module in the bootstrap but cannot have the PHP script to behave exactly as the Drupal site, which is doing properly the transliteration in file names and also from my own custom module.

define('DRUPAL_ROOT','/home/example.com/public_html');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '/sites/all/modules/transliteration/transliteration.inc';
 require_once DRUPAL_ROOT . '/sites/all/modules/pathauto/pathauto.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if(isset($_GET['string'])) echo pathauto_cleanstring(urldecode($_GET['string']));

Result with www.example.com?string=está-cañón : est-can

Result with the same string and module, same function and correct, expected, result: esta-canon

After having a look at the code from the pathauto_cleanstring function, I would suggest testing the following:

Checking the value of pathauto_transliterate prior to calling the pathauto_cleanstring function

variable_get('pathauto_transliterate', FALSE)
If that value is FALSE, you probably found the reason. Try setting that variable to TRUE to force use of transliteration inside the pathauto_cleanstring function. N.B.: You only need to set this value once.

variable_set('pathauto_transliterate', TRUE), or
drush vset pathauto_transliterate TRUE
Try your code again. Fingers crossed!

I suspect that your code never actually uses the transliterate function, but that is something that you can check by dumping the 'pathauto_transliterate' variable in the various scenarios where your code is executed (in-module, custom script, etc.)


Move Drupal site from localhost to remote production server I want to move my Drupal 7 site to a remote server. I searched the Internet for a solution, but the information I found were cluttered. Can someone care to write step-by-step how-to or provide a link?

You can follow this steps and move your site to production server:
On your local site

Install Backup and migrate, which will take the backup of the database (admin/config/system/backup_migrate).
Install Backup and migrate files which will enable you to take a backup of your public files in the directory defined at admin/config/media/file-system.

On the production server

Install fresh copy of Drupal.
Copy the modules and themes from localsite's sites/all/modules and sites/all/themes to the respective folders on the fresh install of dev server.
Enable the Backup and migrate module and backup and migrate files module.
Go to admin/config/system/backup_migrate/restore and restore the backed up database and public files which you exported at your local site.


JS scripts not loading on certain pages When logged in as a user (not admin), some JS scripts do not load on certain pages.
I found out about this issue because I am using the module EU Cookie Compliance and the scripts it uses (eu_cookie_compliance.js, jquery.cookie.shim.js, js.cookie.min.js) aren't always loaded.
I am using a JS method provided by the EU Cookie Compliance module in my custom theme and found out it triggered an error on some pages (because the scripts aren't loaded).
For example, the scripts load on /user/2 but don't on /user/2/orders or /user/2/customer as you can see on the below image. Why does this happen?

I can see no option in EU Cookie Compliance module that prevents loading the script on some pages. Nor did I find anything in the code.

Drupal core: 8.9.3
EU Cookie Compliance: 8.x-1.9

Edit:
I have now included eu_cookie_compliance as a dependency in my theme:
dependencies:
  - core/drupal
  - core/jquery
  - core/jquery.once
  - core/drupalSettings
  - eu_cookie_compliance/eu_cookie_compliance
  - eu_cookie_compliance/eu_cookie_compliance_bare

And this fixed the fact that the scripts weren't loaded on all pages. That said, I now have errors on these specific pages.
All I do in my theme's JS (radix_sub.script.js) is using Drupal.eu_cookie_compliance.hasAgreed() which now triggers the following errors:

I have tried declaring only eu_cookie_compliance and only eu_cookie_compliance_bare and both in my theme libraries, and the errors are identical.

I don't know why it's not loading on some pages, but ultimately it's because the library isn't required for those pages. If a module's library is required by your theme then you need to declare it as a dependency.
You can do this for your library in your theme's libraries.yml file. See the Declaring dependencies documentation.
# my_theme.libraries.yml
# It's not clear if you want the bare or full cookie compliance library
my_library:
  js:
    js/my_libary.js: {}
  dependencies:
    - eu_cookie_compliance/eu_cookie_compliance
    - eu_cookie_compliance/eu_cookie_compliance_bare


How to add data attributes to view list  tags? I have a HTML-list view, which generates li tags for my content. I want to add a data- attribute to each list item dependent on the content. How to achieve this?

Override style output template file using theme information in views.....

Override file with below code..

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */
?>
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li data-attr="" class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>


After drupal 6> 7 upgrade attached pdf links not visible After upgrade fromn 6 > 7  attachment information is not visible in nodes.  Data exists in dbase.  What is best approach to re-connecting pdf, mp3 and other attachments to specific nodes. (2000 or so)

Use CCK migrate module to migrate (import) the D6 fields to D7 . CCK migrate module is the part of CCK module in drupal 7.

Here is the documentation how to do it.


Can I upload Flash (swf) to drupal 7? http://drupal.org/project/flashnode
The module that I found only works for drupal 6.
Is there a module for drupal 7?

Also, there seems to be no tag label called Flash... Maybe an advance user would want to add that?

A Google search for add flash to drupal 7 gives the SWF Embed module as the first result.

You could also look at the Media suite of modules, which can give you a much more user friendly interface at the expense of some additional time invested in figuring out which of the modules you need.


How to programmally add nodes with next nid? i want to create multiple nodes (from csv file) the csv is loaded well, and my table node contains many old records (with nid from 1 to 170) what i want is to record the csv's new nodes with nid strating from the last one on table node (the new nodes would start from 171 on nid)
I've tried db_last_insert_id() with no success.

This is my db_merge part :

 $nodes = db_merge('node')
        ->key(array('nid' => last_insert_id()))
        ->fields(array(
            'type' => 'livre',
            'uid' => 1,
            'status' => 1,
            'comment' => 1,
            'promote' => 0,
            'title' => $new_array['titre_csv']<===from csv
        ))
        ->execute();

Try this way:

  $node = new stdClass();
  $node->title = $new_array['titre_csv'];
  $node->type = "livre";
  node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  $node->language = LANGUAGE_NONE; // Or 'fr' in your case
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  //save the other table

If you want to save it in your custom table you can do a db_insert or EntityFieldQuery.
In that case $node->nid value will be taken after you do the node_save (so do it after you save it with node_save).
You could also use a hook_schema for your table.


How can I edit metadata and custom fields for an embedded image using Media Module in a WYSIWYG in D7 I need the ability to edit custom fields (Caption, Credit) on an image that has been placed in a WYSIWYG. I'm using the latest dev version of the media module and WYSIWYG + CKeditor. I see the fields fine when I add the image, but when I click the media button to edit the image, the custom fields are not accessible.

Adding an image works, but only if you upload a new image.

Editing does not show the fields though.

This seemingly was solved a long time ago... but doesn't seem to be part of the latest dev branch.
https://www.drupal.org/node/835516#comment-7537339

Any direction on how to get the custom file fields to display and be editable with D7?

After a tremendous amount of research and trial & error, I was finally able to figure this out. The "trick" is to make sure you click the "override in WYSIWYG" checkbox on the file field at /admin/structure/file-types/manage/image/fields/field_caption


Drupal7: How to add the alt and title attribute to an image by code I am using the file_create_url() function to create the URL for images.
The code is:

<img src="<?php echo file_create_url($node->field_history_image['und'][0]['uri']); ?>">

But I just noticed that the alt and title attributes are not added to the HTML output, eventhough I added them for the image in the admin.

How would I change the above code, so that it adds the alt and title attributes if they are filled in the Admin interface. Or what other function should I use?

Thanks.

Boutros.

Since you are rendering a field , you can use below code

<?php
$image = field_get_items('node', $node, 'field_history_image');
$output = field_view_value('node', $node, 'field_history_image', $image[0]);
print render($output);
?>

OR

$view = field_view_field('node', $node, 'field_history_image');
print render($view);


drupal 7: trying to make use of Compressing JS and CSS causes Major Error hi I want to enable the compression of my JS and CSS to speed up my drupal site, but when I tick these boxes my site breaks completely. I can't even reload the performance page to remove the tick!! Thankfully I leanred this sometime back so I open the perf page twice tick on one and apply, see error then save the other loaded page which resets the situation.

error message for either CSS or JS tick is

The website encountered an unexpected error. Please try again later.

Also I CAN set these ticks on my localhost verion of the site, I get this problem on the hosted site.

anyone know why I can't use these features?

edit. Also there is nothing in the logs when I get back into the site.

error below was shown when warnings and error were turned on to display

Error
Error message
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'WATCHDOG_ERR' for column 'severity' at row 1: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => The specified file %file could not be copied to %destination. [:db_insert_placeholder_3] => a:2:{s:5:"%file";s:22:"temporary://fileFTC3lH";s:12:"%destination";s:64:"public://css/css_jZfSPTZv1KVtNJ48SyQgcHuPQjmI4wt9aqGhI5N-Vyg.css";} [:db_insert_placeholder_4] => WATCHDOG_ERR [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.martynazoltaszek.com/admin/config/development/performance [:db_insert_placeholder_7] => http://www.martynazoltaszek.com/admin/config/development/performance [:db_insert_placeholder_8] => 87.74.16.7 [:db_insert_placeholder_9] => 1334073447 ) in dblog_watchdog() (line 157 of /home/martynaz/public_html/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.

There is probably an error with the file-system? Go to admin/config/media/file-system, check the settings or just hit the save button again. But backup your site befor you do this. Have you tried to upload a file? Do you get any other cache / temp error? Did you clear the cache?


How to implement apple-touch-icon to a site I'm trying to place an apple-touch-icon on a site.  I have attempted to implement this via the following code block placed in example_preprocess_node()..

function example_preprocess_node(&$variables) {

  ...

  $apple_touch = array(
    'rel' => 'apple-touch-icon',
    'href' => path_to_theme() . '/apple-touch-icon.png',
    'sizes' => '114x114'
  );

  drupal_add_html_head_link($apple_touch);

  ...

}

I cleared the caches and reloaded the page, but I'm not seeing the <link.../> line in my header at all.

Is this this right place to implement the apple-touch-icon?

I enhanced @willtate code a little.
Note: If you need to create the icons quickly use this online generator: http://iconifier.net/

Add the default icon

$apple_icon =  array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => path_to_theme() .'/apple-touch-icon.png',
    'rel' => 'apple-touch-icon-precomposed',
  ),
);

drupal_add_html_head($apple_icon, 'apple-touch-icon');

Loop through to add various sizes

$apple_icon_sizes = array(57,72,114,144);

foreach($apple_icon_sizes as $size){
  $apple = array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => path_to_theme().'/apple-touch-icon-'.$size.'x'.$size.'.png',
      'rel' => 'apple-touch-icon-precomposed',
      'sizes' => $size . 'x' . $size,
    ),
  );
  drupal_add_html_head($apple, 'apple-touch-icon-'.$size);
}

HTML Output

<link sizes="57x57" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-57x57.png"></link>
<link sizes="72x72" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-72x72.png"></link>
<link sizes="114x114" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-114x114.png"></link>
<link sizes="144x144" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-144x144.png"></link>
<link rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon.png"></link>


Is $page only an array important for theming purposes? I know Wordpress theming, but I am a beginner with Drupal theming. Drupal render array totally confuses me.

Do all modules put their content in the $page array?
Is $page only an array that is important for theming purpose? If the answer is no, then what kind of renderable arrays are available in Drupal for advanced theming?

There is just a type of render array, and it is the one described in drupal_render(); the form API extends the render array with properties necessary to validate/submit a form element. The purpose of a render array is just to theme elements present in a page; it is not used for other purposes, if not rendering/theming.

The output of a module is always part of a render array, except when a module implements code similar to the following one.

  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view() {
    echo "<title>Error</title>Error page";
    drupal_exit();
  }

If you visit http://example.com/abc/def, there isn't any render array involved in rendering the page.


PHP Warning SplObjectStorage::offsetExists() expects parameter 1 to be object, null given Updating to 8.5.1 today from 8.4.5, and after a successful update, I start getting the following warnings on every page:

Warning: SplObjectStorage::offsetExists() expects parameter 1 to be object, null given in /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php on line 602

Warning: SplObjectStorage::offsetSet() expects parameter 1 to be object, null given in /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php on line 616

Warning: SplObjectStorage::offsetExists() expects parameter 1 to be object, null given in /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php on line 602

core/lib/Drupal/Core/Render/Renderer.php lines 594 - 618:

/**
   * Returns the current render context.
   *
   * @return \Drupal\Core\Render\RenderContext
   *   The current render context.
   */
  protected function getCurrentRenderContext() {
    $request = $this->requestStack->getCurrentRequest();
    return isset(static::$contextCollection[$request]) ? static::$contextCollection[$request] : NULL;
  }

  /**
   * Sets the current render context.
   *
   * @param \Drupal\Core\Render\RenderContext|null $context
   *   The render context. This can be NULL for instance when restoring the
   *   original render context, which is in fact NULL.
   *
   * @return $this
   */
  protected function setCurrentRenderContext(RenderContext $context = NULL) {
    $request = $this->requestStack->getCurrentRequest();
    static::$contextCollection[$request] = $context;
    return $this;
  }

docroot/vendor/symfony/http-foundation/RequestStack.php line 56 - 62:

/**
 * @return Request|null
 */
public function getCurrentRequest()
{
    return end($this->requests) ?: null;
}

If I dump $this->requests it is an empty array at this point that is causing the SplObjectStorage errors.  I am brand new to Symfony and I do not know how to proceed with troubleshooting. Any suggestions would be welcome.

EDIT 1:

It looks like it might be an issue with the Shield module.

PHP message: Failed to log error:
Notice: Undefined variable: user in Drupal\\shield\\ShieldMiddleware->handle()
(line 79 of /var/www/docroot/modules/contrib/shield/src/ShieldMiddleware.php).

  #0 /var/www/docroot/core/includes/bootstrap.inc(582): _drupal_error_handler_real(8, 'Undefined varia...', '/var/www/docroo...', 79, Array)

  #1 /var/www/docroot/modules/contrib/shield/src/ShieldMiddleware.php(79): _drupal_error_handler(8, 'Undefined varia...', '/var/www/docroo...', 79, Array)

  #2 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\\shield\\ShieldMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)

  #3 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\\Core\\StackMiddleware\\ReverseProxyMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)

  #4 /var/www/docroot/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\\Core\\StackMiddleware\\NegotiationMiddleware->handle(Object(Sy...',

I was able to get this error to go away by deleting my entire project and rebuilding from scratch.  Was not ever able to identify the source for the warnings, so if you come here looking for answers, best of luck.  If you find any, please share!


Drupals clean-urls (.htaccess) breaks with mass vhost Apache has a nifty mass vhost feature. Problem is, when I use this to reach my site, clean-urls stop working. Is there a way to combine this with clean urls?

<Directory /var/www/localhost/htdocs>
  Order allow,deny
  Allow from all
  AllowOverride
</Directory>
UseCanonicalName Off
LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
CustomLog /tmp/access_log vcommon
VirtualDocumentRoot /var/www/localhost/htdocs/%0/web
VirtualScriptAlias /var/www/localhost/htdocs/%0/web

Obviously I've attempted to add

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

to the <Directory/>, but that doesn't help.

I had to add a slash before index.php to get this working for WordPress. Has to do with VirtualDocumentRoot not setting the DocumentRoot to the same value I guess.

RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]


Hide certain views fields only on particular content type I am working in Drupal 7. I have a view that filters on 'Is one of' content type 'blog post' or 'member news story'. I need to adjust the output of the view so that when the content returned in the view is a blog post the author and the author company are shown, but when the returned content is a member news story the author and author company are hidden. My view has a relationship 'Content: Author'.

First of all I tried using Global PHP. I am using the realname module and was able to return the realname of the author by adding the following code to the output field of a Global PHP field:

    <?php
    if ($row->type == 'member_news_story'){
         print ("Author: ");
         print($row->realname);
    }
    ?>

I would have thought that I could just as easily use the replacement pattern for my field for the authors company, but adding the following code beneath 'print($row->realname);' simply prints a number i'm guessing this is a NID.

     print($row->field_guest_blogger_company_or_o);

I tried following advice like that give in questions like returning nod ID in views php and global php in view using print_r($data); to return the available data and then trying to drill down into it to get the variable I need.
Unfortunately I was not able to return the company name. I expect this was more complex as the the company name is not in the returned node, but is a user field. After spending ages on this and getting no where I decided to try a different approach -

I thought that it might be better to work with the template.php file and create a hook for the company name views field. In template.php I added:

    function amrc_new_views_view_field__news_blog_front__block__field_guest_blogger_company_or_o(&$vars) {
       return "views theme view field working";
    }

I could see the text 'views theme view field working' in the correct place showing the hook was working. I was able to use dpm($vars); instead of the return statement above to return a devel/krumo display of the available variables. However I struggled to be able to print any of the variables to the screen, which I would like to be able to do before I try using them to only print the company name if the returned node is of the type 'blog post'.

To recap, my question is: When the content returned in the view is a blog post I need to show the author and the author company, but when the returned content is a member news story the author and author company are hidden. I would like to know whether using global php in views or a hook in template.php would be the best way of going about achieving this. I would also like suggestions on how to access the company name variable so I can work with it. I have been struggling with this for a long time, so your input would be really appreciated.

If required I can easily supply the output of the using print_r($data) in the view and the dpm($vars); in the hook, but left these out for brevity.

Controlling the rendering of information at the views level is preferable. If you control it at template.php it's just one step before the information is going to be displayed to the end user. So, it will be an overload. Just try to render the $data object, you can easily get the required information. Yes, $row has issue of returning nid in D7.

Hope it helps


"Keep me informed" module It is good practice when starting a new web project to begin with an alpha version. I like to add a "Keep me informed" e-mail field for the visitors. I may use the contact module and vary, but maybe there is such a module ?

I will need only field e-mail, a checkbox to accept conditions and a first confirmation mail.

The way I would do this is with a Notification module.  There is a page at Drupal.org that lists the notification modules that exist.  You may want to look at that page to find a module that suits you.

One particular module I would like to suggest (since I maintain it :-) is the one named Notify.

  The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily news letters sent by some websites.

You can set it up so that users become automatically subscribed to notifications when they register at the site.  You may notify about all new content or only specific content types.  I.e. you can create a special content type named "Site updates" and use that to post site updates about your alpha site. Then, all your subscribed users will receive an e-mail update update whenever you post new content of the type "Site updates".


Running drush up to several sites folders at once In my server's root folder I have the folder www that contains sites of all my websites. All of these are Drupal.

Navigating into each folder and doing drush --no-backup up -y each time, can be both time consuming and tiring.

Is there a way to update all sites at once, with drush, instead of installing third-party software (like Ansible, IINW).

The command drush --no-backup up -y @sites won't help in this case, as it is aimed for multisites, and I don't work with multisites at all.

Update 1 - Note (might not be relevant when you read this question):

<?php
$aliases['mine'] = array(
'site-list' => array('@site1', '@site2')
);

The file containing it should be putted under public_html (or www) with permissions as 755 or 644.

First off, look to the trivial solution:

#!/bin/bash
drush @site1 up -y --no-backup
drush @site2 up -y --no-backup

You don't need to install Ansible to start automating; simple bash scripts can be used to combine repetitive tasks very easily.  If you are on Windows, you can install Git for Windows, which includes a Bash shell, or, if you really don't want to install anything at all, use a .bat file.

There is also a Drush solution:  Drush can run the same command on multiple sites if you give it a list of aliases:

drush @site1,@site2 up -y --no-backup

If you have a lot of sites, you can make a site alias that is a list of site aliases:

<?php
$aliases['mine'] = array(
  'site-list' => array('@site1', '@site2')
);

Then:

drush @mine up -y --no-backup