How do I increase the character limit for the default "Fixed value" of a contextual filter? I'm trying to make a view of my new products using the Content: Nid contextual filter.

In this filter I opted to provide a default value, with a type of "Fixed value". On the "Fixed value" field, only 27 values are added, after which no more are accepted.

Apart from the character limit for the text field, is there another reason  I can't add more values here? If not, how do I increase the character limit so I can add all the values I wish to?

Why don't you write a small code snippet and pass contextual filters using hook_views_pre_view(), that allows altering a view at the very beginning of processing a preview.

function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'YOUR_VIEW_MACHINE_NAME' && $display_id == 'page_1') {
    $nids= get_nids(); //write a custom function to get nids.
    $args[] = implode('+', $nids);
  }
}


Use webprofiler to see entire query from view I am using Drupal 8. I have webprofiler enabled and am trying to see the entire query from a view since the query that shows on the view is not the complete view, its missing some fields. How do I use webprofiler to get this entire query?

Check the saved profiles by the Webprofiler module via /admin/reports/profiler/list.

Go to the profile with the the same URL as your view and open it. Select the Database option on the left and search (CTRL+F) for the following string: D\v\ViewExecutable::execute.

You will find queries executed by the ViewExecutable class which is responsible for the data generation and query execution of your view.


Using Twig how can I get the summary of the body field to use in a template? So I have a textarea with summary and I want to display the summary before the content.
So if I just use {{ content.body }} the text is displayed without the summary.

How can I get the summary ?

{{ content.body.summary }} doesn't seem to do the trick

The only way I managed to solve this is:

if you only want to target the value of the summary, you can target the entity you're on. If you're on a node then you can do this :

node.body.summary

In a paragraph

paragraph.field_body.summary

You can also get the summary front content like this :

content.body['#object'].body.summary

Not great but will do for now.


How to check a checkbox by default in forms api I wonder how I can check a checkbox by default? Is #default_value the wrong attribute?

 $form['ios'] = array(
            '#title' => t(''),
            '#type' => 'checkboxes',
            '#description' => t(''),
            '#options' => $options,
            '#default_value' => 'checked' // this is not working

        );

Thanks a lot!

See below example...

$options = array();
$options["1"] = "One";
$options["2"] = "Two";
$options["3"] = "Three";
$options["4"] = "Four";

$form['ios'] = array(
  '#title' => t(''),
  '#type' => 'checkboxes',
  '#description' => t(''),
  '#options' => $options,
  '#default_value' => array("1", "2", "3")
);


How to add extra data to a programmatically created node Using Drupal 8 i am importing data from an external source and creating the node programmatically from the controller:

$node = Node::create(array(
  'type' => 'article',
  'title' => 'some title'
));
$node->save();

I want to add some extra field with the external id (e.g. "3cru_81pazBBRbj5e8LZkZ").

Adding of the field should happen programmatically within the module without the need of the user having to add it via the ui.

I have been reading up on this but i have come to the point that tutorials have confused me more then helped me.

Any help would be greatly appreciated.

I found this can easily be done using the Features module. Now i could create the the fields manually and then export them using features and copy the export to my custom module.


$.cookie is not a function from form.js with block cache I am getting this error if I turn my block caches on.
I have traced back the origin back to Drupal core form.js but can't seem to see what's going on here.
Any ideas?

Here is the debug:

form.js?v=7.56:69 Uncaught TypeError: $.cookie is not a function
at String.<anonymous> (form.js?v=7.56:69)
at Function.each (jquery.min.js?v=1.7.2:2)
at HTMLFormElement.<anonymous> (form.js?v=7.56:67)
at Function.each (jquery.min.js?v=1.7.2:2)
at $.fn.init.each (jquery.min.js?v=1.7.2:2)
at $.fn.init.$.fn.once (jquery.once.js?v=1.2:55)
at Object.attach (form.js?v=7.56:65)
at Object.<anonymous> (drupal.js?p3kpc3:76)
at Function.each (jquery.min.js?v=1.7.2:2)
at Object.Drupal.attachBehaviors (drupal.js?p3kpc3:74)

Update: I think I am isolated this problem to a webform in a block on the page. If I get rid of that form, the error goes away. Also, this error doesn't happen every single time. Sometimes I have to change browser or open in incognito for it to crash, and then it happens repeatedly.

I can see that jquery.cookie is there when it works. But when there is a crash and I see the page source it's not there, so somehow it seems it's failing to load and when it happens I get the error. I am using JQuery Update (1.7).

This happens sometimes as $.cookie function is not supported. In those case you can try following approach.
Place this code in your JavaScript file
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i var c = ca[i];
  while (c.charAt(0) == ' ') {
    c = c.substring(1);
  }
  if (c.indexOf(name) == 0) {
    return c.substring(name.length, c.length);
  }
}
return "";
}

Then you can use, setCookie(cname, cvalue, exdays) and getCookie(cname) to use set and get cookie functionalities instead of $.cookie.
Hope this works.


How to create entity reference field from custom entity to another custom entity? I'm on Drupal 8 and I created a custom entity custom_entity_one following the Drupal 8 examples, the content_entity_example module.
Now, in another custom entity, custom_entity_two I'm trying to create a BaseFieldDefinition like so:

$fields['cid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('custom_entity_one ID'))
  ->setSettings(array(
    'target_type' => 'custom_entity_one',
    'multiple' => TRUE,
    'handler' => 'default'
  ))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'id',
    'weight' => -1,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -1,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

In the add form of the custom_entity_two, the reference field appears, however, it doesn't find any value, even though I have multiple entities of type custom_entity_one.

I thought that it will look for the label propriety of the entity, but it doesn't seem so. What I am missing ? Should I create a custom handler ? I'm not very sure how.

Yes, I was right, right after I posted the question I checked if I'm missing the entity_key label, and I was. I added it in the entity annotation definition, like so:

entity_keys = {
  "id" = "id",
  "uuid" = "uuid",
  "label" = "title",
},


How to theme a link in a D7 render array? I'm trying this:

        $content[] = array(
          '#theme' => 'link',
          '#text' => $row->title,
          '#path' => $base_path . 'node/' . $row->nid,
          '#attributes' => array('attributes' => array('title' => $row->title)),
          '#prefix' => '<h3>',
          '#suffix' => '</h3>',
        );

but Drupal is complaining that "Arg 1 passed to drupal_attributes() must be an array, null given" My array looks fine? ...or does it xD

Here is the API doc I'm looking at

The theme_link() function behaves a bit like the l() function; the attributes array needs to be inside an #options property:

$link = array(
  '#theme' => 'link',
  '#text' => $row->title,
  '#path' => $base_path . 'node/' . $row->nid,
  '#options' => array('attributes' => array('title' => $row->title)),
  '#prefix' => '<h3>',
  '#suffix' => '</h3>'
);

echo render($link);


Private Message with node.js issues setting up I have followed the suggested video tutorials https://www.youtube.com/watch?v=u1sxDaH3Z-U and https://www.youtube.com/watch?v=f8XAT1oB1eA

Im using the node.js watchdog submodule for debugging. That's what the tutorial video did. She didnt have any problems.

Any clues?

backendSettings = {
  "scheme":"http",
  "host":"localhost",
  "port":8989,
  "key":"/etc/nginx/ssl/SECURITY.key",
  "cert":"/etc/nginx/ssl/SECURITY.crt",
  "resource":"/socket.io",
  "publishUrl":"publish",
  "serviceKey":"",
  "backend":{
  "port":80,
  "host":"panduh420.com",
  "messagePath":"/nodejs/message"},
  "clientsCanWriteToChannels":true,
  "clientsCanWriteToClients":true,
  "extensions":"",
  "debug":false,
  "transports":["websocket",
  "polling"],
  "jsMinification":true,
  "jsEtag":true,
  "logLevel":1};

I had problems too. On line 3, for some reason using localhost never worked for me. Change line 3 to

"host":"panduh420.com",

Also, if your server has a firewall, make sure port 8989 is open.

Also, if you are not going to use https, then you don't need a key or cert.

here is mine

backendSettings = {
  "scheme":"http",
  "host":"mywebsite.com",
  "port":8080,
  "key":"/path/to/key/file",
  "cert":"/path/to/cert/file",
  "resource":"/socket.io",
  "publishUrl":"publish",
  "serviceKey":"",
  "backend":{
  "port":80,
  "host":"mywebsite.com",
  "messagePath":"/nodejs/message"},
  "clientsCanWriteToChannels":false,
  "clientsCanWriteToClients":false,
  "extensions":"",
  "debug":false,
  "transports":["websocket",
  "flashsocket",
  "htmlfile",
  "xhr-polling",
  "jsonp-polling"],
  "jsMinification":true,
  "jsEtag":true,
  "logLevel":1};


Can I set a theme's logo_path programmatically? When adding a logo file to a custom theme, I can either

save my logo in the theme folder as logo.png (replacing the default logo.png from the theme starterkit I'm using), or
save my logo in the theme's images folder, using the filename I choose, and use the theme settings page at admin/appearance/settings/themename to set the logo path.

I'm looking for a way to save the logo file in the images folder, while setting the logo path programmatically. This would make sure that the logo is automatically set when enabling the theme. Wouldn't it make sense if that could be done in themename.info, using something like settings[logo_path] = path/to/my/logo-image.png?

In Drupal 6, I believe what you are looking for is

variable_set('logo_path', '/path');

At first glance though, I'm wondering why there is only one such on my site, and not one per theme.
theme_get_settings appears to be grabbing defaults first, and then merging in theme specific settings on top of that.

In D7, the variable is called 'theme_themename_settings'.


How to add and render a region in omega 3.x subtheme? Can anyone let me know as how to render a region in omega 3.x subtheme ?

I have tried creating a region using this command in .info file as  regions[region name] = region name and used render command in page--front.tpl.php  , ,but regions are not getting rendered !

Can anyone please help me with this issue

Clear the cache first.

Go to the subtheme appearance settings, click the "Zone and region configuration" tab, and scroll down to the bottom to find your "unassigned regions". Simply assign it to a zone, configure the options above, and save.

Go to Structure and check "Demonstrate block regions".


Drupal best way to render content type data and meta-data I am new to Drupal and struggling on the best approach to choose, I have several questions which are all related to my approach.

Let say I have a content type "Rooms" and would like to create 2 pages: 1 for listing the rooms and one per room (let's call that one Room A), plus I would like to add some additionnal data for the page listing rooms. Of course I need menu item when being on page "Rooms" but still need the item to be active when on page Room A.

Finally, the page Rooms not only list the room's content type but also display some static blocks which both has and has no relationship to the Room content type.Eg: an image's banner with a small description.

After doing some research, I have found several approach to do this:

Have a taxonomy "Rooms" with no terms and in which I classify all my rooms and add additional field for data specific such as my banner picture. I then create a basic page which I theme to call my blocks and taxonomies. The menu active trail issue is realized by taxonomy-menu trail.

Pro: it works. Cons: the logic bothers me, the purpose of taxonomy is more like a tagging system rather. Therefore I have to tag my content's instance each per each

I create a new content type "Banner" in which I add new fields, an image, a description... Using Node Hierarchy menu, I create a parent relationship for a basic page to a room content type, on that basic page i display all my block...

So, OK the content type is not a page it's an abstract of fields, but what if I want to display in the most efficient way data that are on higher level of abstraction of the content type and that are specific to that content type ?

What's your opinion ?

If I have understood well, here is what I would do:

Create a content type "Room", with specific fields and configuration (I guess you already did that).
Create several nodes of type "Room", one by actual room.
Create a View (using Views module) to display a list of all my nodes of type "Room" (I can tell you more about that if you need it) and where you can access the rooms page automatically. Of course, you can create a menu item in the same time. Very easy.
Create a custom static block with the banner, text, or whatever you want to be displayed on your View page.
Configure the block to be displayed only on your View page (path/to/your/view).

This is how I would have do that if I had to. I don't know if there is a better way but it seems quite logic and simple to me.

I hope it was the answer you wanted!

EDIT: I just remember the active menu item thing. I did that once in a project, it is a bit tricky but I can explain to you my method.


How can I assign values to radio buttons with the forms api? I made radio buttons with the forms api using this code:

"sex" => array(
    '#type' => 'radios',
        '#title' => t('Sex'),
        '#options' => array(t('M'), t('F')),
)

It works perfectly, but instead of storing an M or an F in the database, it stores a 0 or a 1. How can I decide what value is stored for each option?

The keys of the array set as #options determine the values and the values determine the labels.

In other words: The example in my question uses a regular array array(t('M'), t('F')) which, behind the scenes, is an associative array using non-negative integers as keys (same as array(0=>t('M'), 1=>t('F')). Since the radio buttons use these keys to know what to store in the database, the solution is simply to change them: array('M'=>t('M'), 'F'=>t('F')).


Custom form to modify only some fields of an EntityForm I generated an Entity following this guide. Now I would like to create a custom form to modify only some fields inside a single entity.
I was thinking to create an action inside the controller calling a new/custom form:

I created the routing file to open the form with the specified path (I know I can also create an action inside the controller to open the form with a custom template)
I created the form that extends the main EntityForm:

class DetailedForm extends CompleteEntityForm{
    public function getFormId() {
       return 'detailed_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state){
        $form = parent::buildForm($form, $form_state);
        return $form:
    }
 }

I put some lines of code inside the functions getFormId(), buildForm(), validateForm() and submitForm().

But in the end the result is an error:

  Call to a member function getEntityTypeId() on null in
  \drupal\core\lib\Drupal\Core\Entity\EntityForm.php on line 79 #0
  \drupal\core\lib\Drupal\Core\Form\FormBuilder.php(196):
  Drupal\Core\Entity\EntityForm->getBaseFormId()

Any suggestions?

Based on the comments on the question, I fixed my issue.

I created the routing path to call the controller:

mymodule.manage_detailed:
  path: '/mes-detailed/cp/{eid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DetailedController::manageAction'
    _title: 'Detailed'
  requirements:
    _permission: 'access content'

Controller:

class DetailedController extends ControllerBase implements ContainerInjectionInterface {

public function manageAction($eid) {

    $entityForm = \Drupal::entityTypeManager()
        ->getStorage('main_entity')
        ->load($eid);
    $finalform =  $this->entityFormBuilder()->getForm($entityForm);

    $render['form'] = $finalform;

    $render['#theme'] = 'manage_detailed';
    return $render;

}

}

Then I put inside the template all the form with:

{{ form }}

Because using only some fields inside the template didn't allow to save data.
And finally I create the submit function to define the redirect:

public static function manage_form_submit(&$form, &$form_state) {
        $url = \Drupal\Core\Url::fromUri('internal:/link-to-go');
        $form_state->setRedirectUrl($url);
    }

To call the submit function I used the alter form function inside the module file:

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

 //drupal_set_message($form_id); //to show id of the form

 if ($form_id == 'name_of_entity_form'){

    $form['name']['#type'] = 'hidden';
    $form['status']['#type'] = 'hidden';
    $form['new_revision']['#type'] = 'hidden';
    $form['revision_log_message']['#type'] = 'hidden';
    $form['field_n1']['#type'] = 'hidden';
    $form['field_n2']['#type'] = 'hidden';
    $form['field_email_']['#type'] = 'hidden';
    $form['field_nd']['#type'] = 'hidden';
    $form['actions']['delete']['#type'] = 'hidden';

    $form['actions']['submit']['#submit'][] = 'Drupal\mymodule\Controller\DetailedController::manage_form_submit';

  }
}


How to create a chart using an uploaded CSV file as input? I wish to generate a table and chart using an uploaded csv file (in Drupal 7).

I have uploaded the CSV file using the Feed Importer module and created a view (using the Views module). The view uses a display format of 'Chart', which is one of the possible views 'styles' you will have after enabling the Chart module.

My question: I don't know how to apply this to the uploaded CSV file.

You might want to use the Google Chart API module with Views integration. Here is a post that might help you - Add Charts To Your Drupal Site. It uses the Node Import module to create a node of statistics by way of importing a CSV file.


Problem setting user specific cache tags on custom block with user context I have a simple custom block with a user cache context and a specific user specific cache tag:

/**
 * Provides a 'User example' block.
 *
 * @Block(
 *   id = "user_example_block",
 *   admin_label = @Translation("User example block"),
 *   category = @Translation("Blocks")
 * )
 */
class UserExampleBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => 'Current User ID: ' . \Drupal::currentUser()->id() . '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts()  {
    return Cache::mergeContexts(parent::getCacheContexts(), ['user']);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags(), ['example_user:' . \Drupal::currentUser()->id()]);
  }
}

The block output varies correctly by the logged in user but the user specific cache tag is not set correctly.

It seems the cache tag is only set once for users with the same role or permissions.

Here is how to reproduce it:

Rebuild cache (drush cr)
Login with User 100 -> The block output is correct. The correct cache tag is set (example_user:100).
Logout
Login with User 101 (same role as User 100) -> The output of the block is correct, but the cache tag was not changed, it still is example_user:100. In fact the getCacheTags, getCacheContexts methods were not even called.

What works is when I put the cacheability meta data in the build method (with the "#cache" element in the render array).

What could be the reason for this?

Thanks for any help.

To sum up the comments: As a general rule, if you render the current user, then always add the correct cache metadata to the render element:

 public function build() {
    return [
      '#markup' => 'Current User ID: ' . \Drupal::currentUser()->id() . '',
      '#cache' => [
        'contexts' => ['user'],
        'tags' => ['user:' . \Drupal::currentUser()->id()],
      ],
    ];
  }

If you have a block, which doesn't return a cacheable render result in all cases, you can add additional cache metadata in the block plugins cacheable dependencies methods. It doesn't harm when you declare a cache tag or context twice.


Multilingual websites- one menu for each language or one menu for all languages? On a multilingual website, why would I use the i18n_menu module to translate the menu items of a menu instead of simply making separate menus for each language?  I read Gabor Hojtsy's excellent article on the menu system in D7 but I still don't understand in what sort of use case I would want to use i18n_menu vs. simply creating separate menus for each language and setting them to display only for their respective languages.

You have a lot more flexibility when using one menu for each individual language. It's a bit more work to setup but it definitivly pays out in the long run.These are the points that are blocking me for using one translatable menu:
You're not able to reorder menu items for only one language.
You can't deactivate one particular link in one language, the content needs to be disconnected from the link.

Bottom line is when you're sure that you have a fixed menu that doesn't need flexibility it's OK to use i18n_menu.
When building a site that could be expanded in the future and has differences between language content avoid the use of i18n_menu and set up a menu for each language.
(You can set a fixed language in order to do some ajax magic and only show the menu items available for each language when creating new content.)


db_query or db_select for getting content type fields Originally I was doing something along the lines of $query = "SELECT {}" and then $result = db_query($query). This method works fine for most of my queries until I needed to get the field values and fid from a specific content type. And then be able to call these values when printing inside HTML. Can anyone provide an example of how I would do this?

I had something along the lines of:

<?php
$query = "SELECT node.nid AS nid, 'node' AS field_data_field_news_node_entity_type, 'node' AS field_data_field_news_date_text_node_entity_type, 'node' AS field_data_field_news_teaser_node_entity_type, 'node' AS field_data_field_news_body_node_entity_type, 'node' AS field_data_field_news_video_node_entity_type, 'node' AS field_data_field_news_video_image_node_entity_type, 'node' AS field_data_field_mypdf_node_entity_type
    FROM node
    INNER JOIN field_data_field_news_is_featured ON node.nid = field_data_field_news_is_featured.entity_id AND (field_data_field_news_is_featured.entity_type = 'node' AND field_data_field_news_is_featured.deleted = '0')";
?>

$result = db_query($query);

<?php foreach ($result as $row) : ?>

    <div class="featuredArticle">
        <?php print $row->field_mypdf_value; ?>
        <?php print $row->field_mypdf_fid; ?>
    </div>

<?php endforeach; ?>

If you have your node object, you can use field_get_items to get the field values from the node.

$items = field_get_items( 'node', $node, 'field_name' );
// now $items is an array of values... you can manipulate...
// then use the field_view_value to build the render array
$specific_item = $items[0];
$item_build = field_view_value( 'node', $node, 'field_name', $specific_item );

Here's a link to the field_view_value API doc.

Use the devel module and sprinkle in some dpm()'s to understand the underlying data. It's pretty neat! :)


Is the #disabled form element property different from the html disabled attribute? Looking at the documentation for #disabled in the form API documentation, one finds this:

  Setting #disabled to TRUE results in user input being ignored,
  regardless of how the element is themed or whether JavaScript is used
  to change the control's attributes.

If I'm reading this correctly, this seems to indicate that this is different from the HTML disabled property.

If I want to make an element disabled, to later enable it via javascript, and have its value come through in $form_state['values'], I should not use this?

Yes it's different, as well as rendering the attribute the form API also ensures server-side validation is taken care of.

As with all Drupal form manipulation, the right way to remove the disabled attribute is with the Ajax API, not by manipulating the input directly with JavaScript.

Once you use that method, you'll be able to get values for the input(s) in the form state as normal.


Can I call drupal_add_css from a block? I'm building an HTML table in a php filter in a block. Can I/is it OK if I call drupal_add_css() from the block php?

Thanks.

Although probably ok, rather than using the PHP filter, you may be interested in using

hook_block_info
hook_block_view

To define your blocks instead. Perfectly fine to use drupal_add_css there.

Eg :

<?php
drupal_add_css(drupal_get_path('module', 'custom') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
?>


How to customize CKEditor format configuration I'm using Drupal 7 with CKEditor module and I would like to delete some formats in the dropdown box that is currently labeled "Format". So I modified the config file which is site/all/modules/ckeditor/ckeditor.config.js. I modified the code like this :

CKEDITOR.editorConfig = function(config) {
   // some code here
   config.format_tags = 'p;h1;h2;h3'; // I added this line
}

Then I flush all caches of drupal and the cache of browser, but it doesn't work. When I create a new content, I always have all the formats. How to make it work?
(Note : I don't want to customize it from admin/config/content/ckeditor/edit page)

To remove entries from "Format" selection list of ckeditor just follow in the drupal admin menu :

Configuration >> Content authoring >> Ckeditor

Edit the concerned profile(s) and within the Cleanup and Output section change the "Font formats" list, removing the tags you don't want.

Save and clear your caches.


Help text blocks show up randomly in node add/edit form with Drupal Bootstrap theme I can't get rid of this display bug.

I set a Help text for all my content-type's fields to guide my users in the node add/edit forms.

However, these text blocks seem to show up randomly in the form page. Illustration:

Yes, I can assure you that all the fields have a help text set up in the administration interface.

There are no similarities between the field's types. There are text, select lists, taxonomy term reference, etc...

I tried without the field groups (we never know). But no luck.

My config is Drupal 7.32 and my theme is based on Bootstrap 7.x-3.0.

Any idea?

EDIT:

No, they not appear in HTML source at all.

Here is a part of the source code showing one field without help text and one field with help text:

      <input id="edit-field-function-title-und-0-value" class="text-full form-control form-text required" type="text" maxlength="255" size="60" value="" name="field_function_title[und][0][value]">

      <input id="autocomplete-deluxe-input--2" class="autocomplete-deluxe-form form-control form-text jquery-once-2-processed ui-autocomplete-input autocomplete-deluxe-form-single" type="text" size="60" value="" name="field_organisme[und][textfield]" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">

Ce champ est destiné à l'organisme, structure, société, entreprise, cause, fédération, etc. à laquelle la personne physique ou l'entité appartient et pour laquelle elle est référencée dans Grape.

The solution was very simple actually. It was a config in theme administration that set all text blocks having less than 200 chars as tooltips and not as help blocks. All I had to do is disabling that config:


In Drupal 7, how to prevent *.php files from being upload to the /files folder when its required to have 777 permissions? Hi one of the sites im working on just recently got comprised and a bunch of php files got upload somehow or someway into the files folder and started sending out alot of spam. I know during installation they ask for the files folder to be set at 777 permissions, but is there a way to prevent any php scripts from ever running in that directory if they were ever to get uploaded.

Drupal file uploads (in core or modules) should use file_save_upload which itself also calls file_munge_filename. Together those two functions should ensure that even if a file contains php it is not named in a way that a typically configured webserver would execute them. They also have protection against pl|py|cgi|asp|js files which can often contain code.

Since you seem to have .php files in that directory you have to start considering other ways the files might have landed there.

A vulnerability in a module that is allowing arbitrary file uploads
A vulnerability in some other code running on the server (outside of Drupal)
An insecure configuration (allowing users to run php) was used to download these files directly, avoiding Drupal's API.
An attack that used a virus to read stored passwords (e.g. out of Filezilla) on your local computer - these are more common than you'd think, but they usually don't target the files directory.

I suggest doing a few things:

Check the permissions and ownership on the files, that will help you know which webserver user uploaded the files and from there you can hopefully narrow which code was used to upload them. Or if, you notice they are owned by a specific unix user other than the webserver then you should worry about that account.
Check when the files were created - go through backups to find when they appeared or check the file timestamps (though on most OS you can only the file last modified and not the file created timestamp)
Check the apache logs for all accesses to these files and see which IP is accessing them and when (especially the first date of access)
Check the apache logs for other accesses to your site from those IPs and on those dates

These investigation steps are meant to help narrow down how the files were uploaded. Ideally you'll find some specific event (e.g. a POST to some url on your site that you investigate and see is a way to execute php, something like the CKeditor/FCKeditor module issue, then you can know that's how your site was exploited.

If you do find out how the site was exploited, please report it as a security issue: http://drupal.org/node/101494


Custom date range format on a node by node basis I'm working on a way to alter the way a date field, field_node_date, is formatted when rendered.

Currently, on the content type I'm working on, the Long format is being used (e.g. Monday 18 January 2016 - 22:55) and "Both Start and End dates" are displayed by default (on Display settings for any view mode this node is using). As a result, in the node's template,

<?php print render($content['field_node_date']); ?>

is rendering the field as expected.

I've added a new checkbox field to the content type. When users check that checkbox, I only want the date part of the field to be rendered, ie without the time, e.g.

"Monday 18 January 2016"

instead of

"Monday 18 January 2016 - 16:55"

when only a start date is entered, the same for a date range, e.g.

"Monday 18 January 2016 to Tuesday 19 January 2016"

instead of

"Monday 18 January 2016 - 16:54 to Tuesday 19 January 2016 - 19:44"

I tried overriding the theme registry to provide my custom theme callbacks for a single date and a date range:

function mymodule_theme_registry_alter(&$theme_registry) {
    if (isset($theme_registry['date_display_range'])) {
        $theme_registry['date_display_range']['function'] = 'custom_range_date_display_format';
    }
    if (isset($theme_registry['date_display_single'])) {
        $theme_registry['date_display_single']['function'] = 'custom_single_date_display_format';
    }
}

and then copying over date's theme_date_display_range() and theme_date_display_single() functions from date.theme and alter them to return the dates without the time. But there's no way to hook into each separate node withing the scope of this functions and see if the "don't show the time" field is checked so the returned date format would always be the same, either with the time or not, for all my nodes.

Another solution would be to go straight into the node's template and replace

<?php print render($content['field_node_date']); ?>

with something like

<?php print format_date(strtotime($date_field_value) ,'custom','whatever format I need for each node'); ?>

and create the same HTML structure for a single date or a range of dates. But that doesn't cover other view modes and it's not very clean.

I also tried to find the node hooks that would allow me to alter the date but I now see that no matter what format is selected, the date item always holds the date field's value as it's saved on the database and then only the markup changes. Programmatically altering the markup of the field would probably not be a preferred solution as any change of the format on the UI under display settings (e.g. from long to short etc) would be ignored.

I'd also like to avoid adding a new date format / type to my db

A good solution that would allow me to hook into my nodes, check if that checkbox is checked and then enforce my preferred custom date format every time the node is rendered would be ideal.

I'd appreciate any suggestions, thanks.

You just need to add template_preprocess_node(&$vars) to your template.php and check the value of checkbox that is controlling the date format

Date object store start date as value key and end date as value2 key. You need to check on that.

if($checkbox) //checked
  //display one format
else
  // display another format

You can use php date api functions to format your date


IMCE: Prevent deletion if file is in use Does any one know of a way to prevent a file from being deleted through IMCE if the file is in use?  I saw this feature requested http://drupal.org/node/628246 and there is a comment to state that this feature is already in dev but I'm not finding that this is the case.

I'm not familiar with IMCE but Drupal core provides a file_usage table that is for locking/unlocking files. These are the functions used to interact with it:

file_usage_add()
file_usage_delete()
file_usage_list()

Drupal's file_delete() then checks the usage table before deleting a file.


How to modify template.php in bootstrap theme, to add a class tag to menu li tag? I am using Drupal 7 with the Bootstrap theme and a customised subtheme.

I would like to modify template.php to add a class for each <li> in the menu. As per instructions provided in:
https://drupal.org/comment/5830446#comment-5830446

Instructions say:

  "...use this snippet in template.php to put a unique id for <a> and <li> elements at the same time"

<?php
/**
* theme_menu_link()
*/
function MYSUBTHEME_menu_link(array $variables) {
//add class for li
   $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//add class for a
   $variables['element']['#localized_options']['attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//dvm($variables['element']);
  return theme_menu_link($variables);
}
?>

Which template.php file should I modify? and how? I have the following template.php available:

./bootstrapMYSUBTHEME/template.php
./bootstrapMYSUBTHEME/templates/template.php
./bootstrap/template.php
./bootstrap/bootstrap_subtheme/template.php

Whenever in a theming guide you see a reference to template.php without a context, it should (and in official documentation does) mean the template.php in the root directory of a theme / subtheme you are developing.

In your case it means ./bootstrapMYSUBTHEME/template.php

Never hack your base theme. Your changes will be lost and gone if someone will decide to upgrade it. And if you will upgrade it, you will have to re-write them into new version after each upgrade. Waste of time, subthemes are there exactly to avoid that burden.


How do I import latitude/longitude into geofield? I have a CSV file with a id column, a latitude and a longitude column, and some other data in each record.  I have created a content type to hold this dataset. Each record will be mapped to a content.  I used Geofield to store the location.  How do I import the CSV file and create these contents?

You can use the Feeds module to import your csv file and map it to your content type.


Add new attributes for rendering? In Drupal 8, how can you add new attributes to be rendered into the twig file?

I want to provide a region.html.twig that can be extended for subtheming.

So, I want the default to be:

{%
  set wrapper_classes = [
    'region',
    'region-' ~ region|clean_class,
    'container',
    'container--100',
  ]
%}

{%
  set outer_column_classes = [
    'container__col',
  ]
%}

{%
  set inner_column_classes = [
    'container__inner',
  ]
%}

<div{{ wrapper_attributes.addClass(wrapper_classes) }}>
  <div{{ outer_column_attributes.addClass(outer_column_classes) }}>
    <div{{ inner_column_attributes.addClass(inner_column_classes) }}>
      {% block content %}
        {{ content }}
      {% endblock %}
    </div>
  </div>
</div>

Simply making them arrays or strings as you would in D7 doesn't work - they never reach the twig template.

I noticed that Bartik uses the Attribute class to create new/empty Attributes. Is this kosher to do, exactly?

use Drupal\Core\Template\Attribute;

function mytheme_preprocess_region(&$variables) {
  $variables['wrapper_attributes'] = new Attribute();
  $variables['outer_column_attributes'] = new Attribute();
  $variables['inner_column_attributes'] = new Attribute();
}

When I do that, my new attributes appear and are rendered in the template. Is this even worth doing, or is it a lot more trouble to extend templates and manipulate them?

Your question is exactly about this issue:

  Allow instantiating Attribute objects within Twig

  Problem/Motivation

  Sometimes you have an array of attributes and it would be nice if you
  could addClass, removeClass, setAttribute, etc. rather than trying to
  do array manipulation.

  Proposed resolution

  Add a function to our Twig extension to allow creating an Attribute
  object from an array of attributes.

Issue: https://www.drupal.org/node/2616756

And the change record for 8.3.x:

{% set my_attribute = create_attribute() %}
{%
  set my_classes = [
    'kittens',
    'llamas',
    'puppies',
  ]
%}
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
  {{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
  {{ content }}
</div>

https://www.drupal.org/node/2818293


Features - Should I go for big or numerous? I have worked on a few Drupal projects that used features.  I am usually perplexed by the way the way functionality is grouped.  I'm guessing that most of them were created as needed and by different developers that did not want to meddle with other people's features.  The outcome is usually a mess of different naming and grouping schemes.  Currently, I have the opportunity to create a site from scratch, and I want to start using a good methodology for creating my feature groups.  I am tending towards making a gigantic feature that contains everything, and only rebuilding one feature every time an update is needed.  What is good/bad about doing this.  Also, I feel more responsible while considering building several different features for each bit of functionality.  However, I am not sure how granular to go, or if this is begging for conflicts later.  How should I be approaching this issue?

It's all up to you. There are pros and cons to both and it depends on your use case.

Generally one would tend toward decoupled functionality with granular features instead of a giant feature. Especially if you wanted to potentially use these features on other sites.

Some information to help you out.

One big feature Pros:

It's quick and easy. If you're just using features to track database changes in code and
don't care about re usability, you can just stick everything in one
big feature.

One big feature Cons:

If you make one big feature, you can't re use it at all on another
site unless that site is almost exactly the same.

Decoupled features Pros:

You can re use features on other sites.
Your features are much more manageable, even it if it takes a bit
longer.
You can keep custom code which is directly related to the feature in
the features module, so you're keeping the feature + custom code in
one nice package.
This model fits in well with programming in general, taking big
problems, breaking them down, abstracting them, using dependencies,
etc. It will definitely improve your programming practising
separating your code logically like this.
Helps the way you think about Drupal components and how they mess
together.

Decoupled features Cons:

Overhead of organizing features structure. This will get easier as
time goes on and you get better.
Can be very hard to decide where to decouple, especially for newbies.


$form_state does not follow same array structure as $form I built a form in a form plugin like so.

public function buildForm(array $form, FormStateInterface $form_state) {
$array[0] = 'value1';
$array[1] = 'value2';
$array[2] = 'value3';
$array[3] = 'value4';

$form['field_1'] = [
    '#type' => 'value',
    '#value' => 'test value',
];

foreach($array as $item){
    $form['fields'][$item] = [
        '#type' => 'textarea',
        '#title' => $item,
    ];
}
    $form['actions'] = [
        '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
        '#type'  => 'submit',
        '#value' => t('Submit'),
    ];

    return $form;
}

The form is built just fine and I can return the values upon submit like so,

public function submitForm(array&$form, FormStateInterface $form_state) {
    die(print_r($form_state->getValues()));
}

This is part of the output I receive

[field_1] => test value
[value1] => User input for value 1 text area
[value2] => User input for value 2 text area
[value3] => User input for value 3 text area
[value4] => User input for value 4 text area
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

The issue is, I want value1,value2,value3, and value4 to appear as children in the ['fields'] part of the array.

To demonstrate, I'd want the output to appear like so.

[field_1] => test value
[fields] => [
    [value1] => User input for value 1 text area
    [value2] => User input for value 2 text area
    [value3] => User input for value 3 text area
    [value4] => User input for value 4 text area
]
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

The ultimate goal is to be able to use a foreach loop on the fields array, like this

foreach($fields as $key => $value){
    print_r('This is the key: '.$key.' and this is the value: '.$value);
}

I also attempted declaring 'fields' as a container first like so

$form['fields'] = [
    '#type' => 'container',
];

but it has no effect. How would I group form elements into an array when parsing the form state?

If you group the fields below $form['fields'] you also have to set #tree at the top of the array:

$form['fields']['#tree'] = TRUE;

Then the values will be structured in the same way as the form elements.


Remove or rename menu's  class .last I need to remove class .last from menu's
. I browsed this nice website for a solution and find some code that removes ALL classes:

function THEME_menu_link(array $variables) {
  //unset all the classes
  unset($variables['element']['#attributes']['class']);

  $element = $variables['element'];

  if($variables['element']['#attributes'])

  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

And:

function mymod_menu_tree__menu_about_us($variables) {
  return '
' . $variables['tree'] . '
';
}

function mymod_menu_link__menu_about_us(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $class = "";
  $classes_of_this_li = $element['#attributes']['class'];
  if (in_array($classes_of_this_li, 'active-trail')) {
    $class = 'active';
  }
  $output = l($element['#title'], $element['#href']);
  return '
' . $output . $sub_menu . "
\n";
}

I need to remove only .last class and also somehow I need it to work only on a selected region. What I mean is that the function must apply to menus that are rendered i.e. in Sidebar region.

You can do it like this:

/**
 * Theme menu links.
 */
function THEME_NAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  // This is the part that removes or changes the last class.
  if (!empty($element['#attributes']['class'])) {
    foreach ($element['#attributes']['class'] as $key => $class) {
      if ($class == 'last') {
        // Use only one of the two following lines.

        // To change the last class.
        $element['#attributes']['class'][$key] = 'new-last-class';
        // To remove the last class.
        unset($element['#attributes']['class'][$key]);
      }
    }
  }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

However, if you are referring to the primary links and secondary links as printed out by default in most themes, they do not run through that function, because they are generated by menu_main_menu() and menu_secondary_menu(), which in turn use theme_links() to generate the links instead of theme_menu_link() - very annoying.

So to get to those you either need to stop using theme default theme menus and use the menu blocks provided by default by the menu module. These blocks use the theme_menu_link() function to generate links so will be affected by the above code.

Alternatively, you would have to override theme_links() also, like so:

/**
 * Theme links.
 */
function THEME_NAME_links($variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  $heading = $variables['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    $output = '';

    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading['level'];
      if (!empty($heading['class'])) {
        $output .= drupal_attributes(array('class' => $heading['class']));
      }
      $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
    }

    $output .= '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class[] = 'first';
      }
      if ($i == $num_links) {
        // *** Use this line to change the last class. ***
        // *** Or comment it out to have no last class. ***
        $class[] = 'new-last-class';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
           && (empty($link['language']) || $link['language']->language == $language_url->language)) {
        $class[] = 'active';
      }
      $output .= '
 $class)) . '>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= l($link['title'], $link['href'], $link);
      }
      elseif (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes.
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '' . $link['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

I have added * to the start and end of comments for the line you need to be interested in.
The problem with this approach (maybe it isn't a problem for your site) is that this affects a lot of other lists of links on the site, not just the two menus in question.

It is possible to use
    if ($attributes['id'] == 'main-menu-links')
and
    if ($attributes['id'] == 'secondary-menu-links')

to distinguish between the main menus however that isn't foolproof and isn't the best idea.

For example, the important part of the above theme_links() would be:

if ($i == $num_links) {
  // This would skip the last class for main & secondary menus
  // but would keep it for other links lists.
  if ($attributes['id'] != 'main-menu-links' && $attributes['id'] != 'secondary-menu-links') {
    $class[] = 'last';
  }
}


\Drupal::currentUser() returns admin account info instead of logged in user The following function resides in a .module file:

function user_menu_avatar_menu_links_discovered_alter(&$links) {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $name = $user->get('name')->value;
    $userMenuAvatar = $user->get('user_picture')->entity->url();

    $links['user.page']['title'] = $name;

}

When logged in as another user, I am only getting the account info from the Admin user account. User name, email, etc..

What am I missing?

hook_menu_links_discovered_alter() is not invoked right before the links are shown, but when the links need to be rebuilt. Using the code you are showing, you are getting values from the user who is currently logged-in when the links are rebuilt; until the next rebuilt, that is the value shown for every user. (This means this is not the right method to dynamically change the menu link.)
If the links rebuilt is caused from a action you take when logged-in as administrator user, that explains why the name shown is taken from the administrator user.

If you need to alter the title used for a page, you need to alter the route and set its _title_callback property. The title callback is invoked right before the title is shown, so accessing there the object for the currently logged-in user would be correct.


How can I pass a value from block to page in a view? I'm trying to create a search in Drupal 7 using views. I can create the basic search easily, but I'm trying to have the search work like http://leg.colorado.gov/.

I have a view created with a block that has an exposed filter, and a page with multiple exposed filters. I'm trying to get the block to pass the searched term to the page where a user can use more filters to specify what they're looking for. However, all I can seem to do is create a block that performs a search within the block.

Is it possible to set this up using admin configuration in Drupal 7 views, and if so, how? Or would this required coding or other modules?

Thanks

I think this question may have some similarities to How to pass a value from form(block) to the page and show this page?

The trouble with what you are asking is trying to have two distinct parts of your page act on one interaction: the block form submit and then the page search view filter form submit. Each is in fact a separate function which have no relationship in the Drupal backend. To get this to work you could use some jQuery magic to get the value selected in Block filter be cloned into the page search and do a submit on the form. You may have to do some coding using cookies or session values to ensure the values are also reloaded into the block filter criteria if you wish to keep those synchronized.

Since you have several ways of going about this, stick to one that is easiest to work with at first. jQuery is often the most convenient though maybe less elegant in some cases.


node/add is breaking menu hierarchy I'm a newbie, and I'm trying to create a site on Drupal7.

I have a taxonomy vocabulary with many terms. Then I use taxonomy_menu and nice_menu to show the terms. This is working perfectly.

The problem comes when I create (or edit) a node (of any type) and I associate it to a term. The menu item(s) corresponding to selected(s) term(s) loses his place in hierarchy. Searching on database I realize the column "plid" on "menu_links" table is set to 0.

Searching on drupal.org I found this post, I think my problem is related to it. On first comment someone gives a solution, but I can't use it, because in this case nodes won't be shown in the menu.

ideas?

P.S.: sorry on my bad english, ask if you don't understand

It looks like this could be a known issue. Please see the below two issues for the taxonomy_menu project - the second contains a patch you could try?

http://drupal.org/node/1208484

http://drupal.org/node/1485198


CSS for specific pages How do I add CSS styles for a specific page?

For example, I want the <body> background color on a specific page to be different from the background color used on the front page.
I've looked into hook_theme_preprocess(), but I am confused on how I should implement it.

You can find totorial for adding specific CSS to specif page to the following links.

Drupal 8 Theming Fundamentals, Part 1, but it is describing how to add specific CSS to front page.
Drupal8 attaching libraries to specific pages, to add the specific CSS to specific node you need to follow tutorial on this page .

To give you example I am explaining with bartik theme for easy understanding.

I have created a css file cssfile.css and pasted at path css/cssfile.css Now this CSS file I want to use in one case to only front page and in otehr case to only specific node.

Step 1: Adding a library to the theme

Add the following code to bartik.libraries.yml.

css-filling:
  css:
    theme:
      css/cssfile.css: {}

The library name I used is css-filling, but you can use other names.

Step 2: Adding the CSS styles to a specific page

Step 2a: Adding CSS styles only to the front page

The following code in the bartik.theme adds the library to the front page.

function bartik_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'bartik/css-filling';
  }
}

Step 2b: Adding CSS styles to a specific node

The following code adds the library only to a specific node.

function bartik_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    if ($node->id() == 3) {
      $variables['#attached']['library'][] = 'bartik/css-filling';
    }
  }
}

In the above code the important thing is path, bartik comes from the theme name and css-filling comes from step 1.


Custom route using access check error with arguments I have a custom route that needs to check if a user can create a certain group_node:article content inside a group (from the group module 8.x-1.0-rc2). The setting is as follows:

mymod.routing.yml

mymod.add:
  path: '/mymod/add/{group}/{plugin_id}'
  defaults:
    _controller: '\Drupal\mymod\Controller\MymodController::addNews'
    _title: 'Add news'
  requirements:
    _group_content_create_access: 'TRUE'

The group.services.yml

  access_check.group_content.create:
  class: 'Drupal\group\Access\GroupContentCreateAccessCheck'
  arguments: ['@entity.manager']
  tags:
    - { name: 'access_check', applies_to: '_group_content_create_access' }

GroupContentCreateAccessCheck.php

 /**
* Checks access for group content creation routes.
*
* All routes using this access check should have a group and plugin_id
* parameter and have the _group_content_create_access requirement set
* to either 'TRUE' or 'FALSE'.
*
* @param \Symfony\Component\Routing\Route $route
*   The route to check against.
* @param \Drupal\Core\Session\AccountInterface $account
*   The currently logged in account.
* @param \Drupal\group\Entity\GroupInterface $group
*   The group in which the content should be created.
* @param string $plugin_id
*   The group content enabler ID to use for the group content entity.
*
* @return \Drupal\Core\Access\AccessResultInterface
*   The access result.
*/
public function access(Route $route, AccountInterface $account, GroupInterface $group, $plugin_id) {
  ...
}

From my understanding these 3 files should be enough to check _group_content_create_access. However, trying to access my route via

localhost/mysite/mymod/add/57/some-plugin-id

always results in RuntimeException: Callable "Drupal\group\Access\GroupContentCreateAccessCheck::access" requires a value for the "$group" argument.

What am I missing here?

UPDATE I tried to investigate this problem in more detail. The full error message is this one:

....requires a value for the "$group" argument. in
Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument()
(line 148 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).
Drupal\Component\Utility\ArgumentsResolver->getArgument(Object) (Line:
54)
Drupal\Component\Utility\ArgumentsResolver->getArguments(Array) (Line:
157)
Drupal\Core\Access\AccessManager-
>performCheck('group_news.custom_access_check', Object) (Line: 135)
Drupal\Core\Access\AccessManager->check(Object, Object, Object, 1)
(Line: 112)
Drupal\Core\Access\AccessManager->checkRequest(Object, Object, 1)
(Line: 107)

The point where it fails in Drupal\Component\Utility\ArgumentsResolver->getArgument(..) is where is_object($this->objects[$parameter_name]) returns false, because my route parameter {group} that should be of type GroupInterface is actually of type String.

However, when testing another group module route that is not using a route-access check class, the {group} parameter gets noticed as GroupInterface. For example in

entity.group.leave:
  path: '/group/{group}/leave'

So the question points more in the general direction of how my route parameter '57' gets noticed as GroupInterface (or more general any specific type), because the same thing also fails when implementing my own little custom access check class (not using the group module at all).

Digging deeper into what causes the error message brought me to the drupal docs about Parameter upcasting in routes. When passing entity parameters to an access check function you need to upcast your parameter and tell Drupal of which entity type your argument is. I.e. in my_mod.routing.yml add options and argument type:

mymod.add:
  path: '/mymod/add/{group}/{plugin_id}'
  defaults:
    _controller: '\Drupal\mymod\Controller\MymodController::addNews'
    _title: 'Add news'
  requirements:
    _group_content_create_access: 'TRUE'
  options:
    parameters:
      group:
        type: entity:group


Update the actual file associated with a file entity while keeping the fid? Media module provides a generic.png file that it copies into /sites/default/media-icons/generic. That file is used on my site ~300 times, but I'd like to replace it with another PNG. Is it possible to replace the actual file that is associated with that file entity? Ideally I'd keep the generic.png name, but I can use an updated file name if needed.

I've tried simply replacing the file in /sites/default but that had no effect.

As @clive noted in the comments, all that is needed is to replace the file itself. We were having some other server issues that were causing the change not to show up. You may need to flush your image styles in order for those to pick up the new image, though.


How to access library version details in JavaScript I have a theme with library file looks like this:

global:
  version: 1.0.0
  js:
    js/global.js: {}

global.js has some functionality specific to version 1.0.0.

Is there anyway to get this version number? Is it available in JS?

Library definitions can be accessed via the library.discovery service (LibraryDiscovery).

$libraryDiscovery = \Drupal::get('library.discovery');
// Where mytheme is the name of your theme.
$definition = $libraryDiscovery->getLibraryByName('mytheme/global');

Then you would need to pull out $definition['version'] into a JavaScript settings or do something with it in your theme.


Make node/field text input format available to Views The standard Content list in Drupal 7 (displayed with the Find content menu item) gives me a table of nodes in the system with various attributes, such as the type. I want to add the text type (e.g. Filtered HTML).

How can I do this? Installing the Administration views module has made the table much more configurable, but there seems to be no way to include data from the field_data_body database table, which contains the information. The Table Wizard and Data modules apparently provide this functionality, but are not done for Drupal 7.

Is there a way to do this without coding?

If I have to code it, do you recommend creating a new module (with which I have no experience) or patching up an existing one until it works well enough, and if so, which one?

PS: this can be regarded as a special case of a (frequently asked) related question.

It is possible to do this with Views 3 in Drupal 7:

Add the field you need the format of to the view (E.g. field_body)
In the configuration form for that field tick the 'Rewrite the output of this field' box
Put the '[field_name-format]' token into the box

It will render the raw name of the input format, instead of the value.


Views rewrite results: div in anchor I am trying to accomplish the following in a views accordion style.

  Here is what I am putting in the rewrite field

[field_event_date_1]

[title]

[field_time_slot_1]

  Here is what gets rendered

        Tuesday, November 3, 2015
Example title description goes here
1A - 10:00 - 11:30 AM

HTML5 spec allows div styling in anchors. Can anyone point me in the right direction?

If this was purely about just views accordian, then the rendering output you show would not be showing a div with a class of panel-heading. I see this as more likely about trying to have a views accordian rewrite into a panel and probably panels accordian at the same time and having the anchor tag reduced to a single line output when the html is stripped out. So without knowing what the full details are I can only suggest trying the rewrite as:

[field_event_date_1]
[title]

[field_time_slot_1]

or if only the div tags are being stripped out then try:

[field_event_date_1]

[title]

[field_time_slot_1]


Error in php snippet using tokens: Show profile field if it isn´t empty I have this core profile field in Drupal7: profile-curso-basico.
I want it to be shown in the user´s profile  only if the field has information in it (it´s a deprecated field, but some old users have data in it, and migrate modules didn´t import it properly, because it´s a hardcoded list).

I´m using panels, token and Display Suite modules.
At the profile page, I have this panel with a special coded DS field, that has dinamic information using tokens.

If I just paste: Mi Curso: %user:profile-curso-basico I get the field information properly, but I want to show it only if profile-curso-basico field isn´t empty.

So I thought of this (the input type is PHP, so I can paste some php code):

<?php if (!empty(%user:profile-curso-basico)): ?>
%user:profile-curso-basico
<?php endif; ?>

And I´ve got this error:

Parse error: syntax error, unexpected T_LNUMBER, expecting T_PAAMAYIM_NEKUDOTAYIM in /home/liga/public_html/modules/php/php.module(80) : eval()'d code on line 9

What´s wrong with that snippet? Maybe I shouldn´t add tokens into (!empty( )) ?
How may I change that in order to work? Thanks!!

You must refer to the actual field in your snippet. Try something like:

<?php
global $user;
if (isset($user->profile-curso-basico[LANGUAGE_NONE][0]['value'])) {
  echo $user->profile-curso-basico[LANGUAGE_NONE][0]['value'];
} ?>


How to export content type with scheduler's settings using features In my dev environnement, I've installed Features module for exporting the content types of my site. I've also installed Scheduler module to schedule for publishing my contents.
On the admin page of my content type, I enabled scheduled publishing for my content type. Then I created the features of the content type. However after importing of features to the prod, I've found that the scheduler's settings to content type were not imported.

Does anybody know why? Is there any module supporting to resolve this problem?
Thanks in advance.

In addition to exporting "Content types", "Field bases" and "Field instances" you should also export all variables named "scheduler_*_[name of the content type]".

To be able to export variables Strongarm module should be installed.
Then on "Create Feature" page you will see section as on this screenshot.

BTW, lot of modules that extend content types save their configuration the same way, so you need include such variables in the the content type feature.


Site works in locale but not in remote I uploaded my site and the database on the remote server; the site is working in locale, but on the remote I get the following error.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'queryfdu_drupal7.watchdog' doesn't exist: 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] => 0 [:db_insert_placeholder_1] => domain [:db_insert_placeholder_2] => Domain access failed to load during phase: bootstrap include. Please check your settings.php file and site configuration. [:db_insert_placeholder_3] => N; [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 122.175.149.244 [:db_insert_placeholder_9] => 1434778958 ) в функции dblog_watchdog() (строка 160 в файле /home/queryfdu/public_html/drupal/modules/dblog/dblog.module).

The watchdog table exists in the database.

How can I fix this problem? What could be causing it?

That is fairly straight forward. The watchdog table - the system log for Drupal - is missing from your production environment. The real question is really how are you deploying your site. Whatever method you are using doesn't seem to be working properly. If this is a brand new site it would be better to deploy as an install and add all of your customizations as Features.


Select data from database For the filter block I need to get the data from database. I have three tables "node", "node__filed_country" and "taxonomy_index". So I need to pull only those taxonomies which are realted to the nodes, which field_country is equal to three particular countries. So I need to provide two joins.

$query = $this->connection->select('node', 'node');
$query->join('node__field_country', $nfc, "node.nid=$nfc.entity_id and ($nfc.field_country_target_id=1 or $nfc.field_country_target_id=2 or $nfc.field_country_target_id=3)");
$query->join('taxonomy_index', $id, "$id.nid = node.nid AND $id.tid = $term->tid AND $id.status = 1 ");
$query->execute()->fetchField();

But something doesnt work in this code. Could you please help me?

You try code

$term_id = 1;
  $query = $this->connection->select('node', 'node');
  $query->join('node__field_country', "nfc", "node.nid=nfc.entity_id and (nfc.field_country_target_id=1 or nfc.field_country_target_id=2 or nfc.field_country_target_id=3)");
  $query->join('taxonomy_index', "tid", "tid.nid = node.nid AND tid.tid =".$term_id." AND tid.status = 1 ");
  $query->execute()->fetchField();


Loading and deleting a cache item I have a render array I'm caching as follows:

$build['friend_link'] = [
  '#type' => 'item',
  '#markup' => $link,
  '#cache' => [
    'keys' => ['friendship', $user->id()],
  ],
];

I need to delete this cache when the friendship is invalidated. However, I'm having a lot of troubles with retrieving the cache in order to invalidate it. I'm attempting to use the following code to retrieve the cache item:

$render_cache = \Drupal::cache('render');
$render_cache->get('friendship:' . $friend->id()); // id = 4

However, this doesn't work, because the actual cache key in the DB is:

friendship:4:[languages:language_interface]=en:[theme]=bartik:[user.permissions]=80e4ddd871aca07e035f618b532bc75cb7c155caaaedd08a4ae17e5e137ca30f

I tried setting the cache contexts to an empty array:

'#cache' => [
  'keys' => ['friendship', $user->id()],
  'contexts' => [],
],

But this didn't change the key. So I set the contexts to a value:

'#cache' => [
  'keys' => ['friendship', $user->id()],
  'contexts' => ['user'],
],

This changed the key to:

friendship:4:[languages:language_interface]=en:[theme]=bartik:[user]=1

So while this does make it potentially easier to build the key manually, it seems like I'm missing something.

I did find RenderCache::createCacheID(), however it's protected so I can't call it.

I'm at a bit of a loss here, is there an API function I'm missing somewhere to retrieve the cache?

What exactly is a "friendship"? You most likely want to use cache tags for invalidation.

One way to do that would be to add the cache tag for the user, then you just have to make sure that you are invalidating that user cache tag. So you add 'tags' => $user->getCacheTags(), and when the friendships of a user change, you use Cache::invalidateTags($user->getCacheTags()). The downside is that this will invalidate too much: It will invalidate all content where the user is displayed, e.g. if he's the author of an article.

You could define your own cache tag; they're really just strings and invalidate just that, e.g. 'tags' => ['friendships:' . $user->uid] and then invalidate that.

Cache contexts are for variations of the same cache entry; it's exactly those things you see in the cache key. Having $user->id() in the cache keys and the user context is practically the same thing. You can do either or the other; you don't need both. (Cache context user and keys just 'friendships' would be the same as what you have now.)


Automatically inheriting title for image Is there a way to inherit the title or copyright field in the properties of a picture on your pc to the title or alt field of an image in drupal?

What I want to achieve is the following:

I want other people to be able to write things on my website, and include a picture to the text. However due to copyrights, I don't want them to be able to upload images. They can only use the images which I have paid for.

This works perfectly, I am using a combination of the following modules:

FileField Sources
IMCE
IMCE for FileField

So far so good, but I also want to be sure that the credits are given to the original authors of the images. I know for sure that people will forget to write that in their text, so I was wondering if it was possible to do this automatically.

If the copyright or title field of the image properties would automatically be added to the picture's title in drupal, I could disable the title field & the credits will always be correctly showed. That is, if I add them to the pictures before uploading :)

This is probably what you are looking for although it uses Media rather than IMCE...
http://webwash.net/tutorials/customize-media-module-image-display-drupal-7

Ok based on your comment I am assuming you have a directory on your computer called: 'images', that contains a bunch of files like 'image-001.jpg', 'image-002.jpg' and properties attached to these files ... on a Windows OS...

You can follow the instructions here: To export your 'images' directory and contents as a CSV (comma-seperated-values) file. This CSV-file can then be 'Read' by Drupal, and it will save you from having to re-enter properties attached to your images manually.

It's important to carefully format your CSV file in Excel  or whatever Spreadsheet software you are using (google docs is good at importing and exporting CSVs) so that there is at least one column with unique elements in it, e.g. Column 'Title' - > Image 001, Image 002, Image 003, etc...
Other columns can have headers that match the image properties, such as 'date created', 'copyright' etc...

You can then use the 'feeds' module to import this CSV to Drupal.
E.g. you can create a content-type 'Image' with fields that match your CSV's headers...like 'Date Created', 'Copyright' etc...

This question will probably help you in making the last stage happen...
https://www.drupal.org/node/1851322


drush sql-sync fails with PHP Fatal Error drush sql-sync @devyau @stageyau returns:

  Unable to load class Drupal\Driver\Database\Drush
   PHP Fatal error:  Call to a member function dump() on a
  non-object in
  /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc on line
  275

Drush command terminated abnormally due to an unrecoverable error.

  Error: Call to a member function dump() on a non-object in
  /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc, line
  275

First you run this command on console. if command is run successfully after then you check your drush library, I think this is drush library problem.

Second is you can try other command like :-

drush ard


How to define alias dependent Drush extensions? I have a stage and an anonymized instance of a project both managed under the same user (www-data). The anonymized instance is taken from production instance and has a drush extension that can have a different version than the stage instance.

With one instance per user I can simply symlink the extension to the ~/.drush folder, but how would I do that with two different versions of the same extensions? Is there a way to define alias dependent extensions in Drush? If Drush does not support this, what would be a good OS work around?

Instead of installing the drush extensions in a user specific scope within your user's profile, you can install them on a per-project (Drupal instance) base in your {PROJECT_ROOT}/drush folder.

Drush 9 checks for the existence of a drush folder one level above the Drupal web root.

This is easiest to manage by utilizing Composer for dependency management and adding a Drush installer path, Drush and any Drush extensions to the composer.json file. But of course you can also setup everything by hand.


MailChimp campaign not showing up in Drupal 7 I set up the MailChimp (https://drupal.org/project/mailchimp) module by following the readme file. I've enabled all the Mailchimp modules and added the API key to my drupal instance. I've created and Sent one campaign through MailChimp however, when I go to /admin/config/services/mailchimp/campaigns the page is blank. I've cleared the cache but the page is still blank. I was expecting to see the campaign I sent earlier but it is not there.

What am I doing wrong or missing?

You need to have libraries 2.0 module installed and download a special mailchimp API library.  https://drupal.org/documentation/modules/mailchimp


Show forbidden content to non-authorized users when viewed in a Panel(-s Node/-ized Node), not when otherwise? I'm using Panels Nodes (Similar functionality to Panelized nodes, if you're more familiar with that) to display a bunch of content from sundry content types -- for instance, I have a content type called Front Page Slideshow, within which each node is a slide that is placed as a piece of Panels content (For simplicity sake, let's just call it a Pane) on the front page.

However, I don't want each individual slide node showing up in either internal or external search results, so I've used Content Access to prevent access to the individual nodes comprising the front page panes but allow access to the Panels Node content type.

Alas, doing this hides all of the panes inside of the Panels as well.

How would one prevent access to specific content types only when they're being viewed individually and not when they're being viewed via a Panel, in a way that also hides them from search results?

N.B. I'm talking about types of nodes that can be created with individual Panels configurations -- NOT Panels pages. So, I don't have access to things like contexts and selection rules and whathaveyou.

Thanks!

I do two things.

I install Rabbit Hole, and configure those nodes/content types to be inaccessible.
I install Custom Search, and configure it to exclude those content types from search results.

IIRC, there is an issue open for Rabbit Hole about excluding nodes/types from search, but I don't think there has been any progress or real discussion on it.

Also take a look at Don't index certain content types for another approach for handling the search results.


How do I solve extra characters in a date format? This seems to be a known issue in drupal, personal commentary redacted.

So I set up a date format, and any non date-format characters get reprinted at the end of the date.

I first had my formatter set up as Y年m月, but read in the issue that I need to escape characters, so:

Format: Y\年m\月

Preview in Date and Time preview area: 2016年08月

Actual output: 2016年08月　年月

Looking in views where the field is being output (to json in case that makes a difference), there is no custom option for the formatter, so I couldn't try recreating the date formatter in views to see if that would work better.

I needed to add the escape characters and then go back in and reassign the format to the type.  Just changing the format didn't solve the problem.


How to validate a form against a custom user profile field? I unsuccessfully tried https://www.drupal.org/project/rules_forms for forms validation so I am writing my own little validation module.
Basically, on node creation I want a validation against a custom user profile field (machine name: field_points). When the user enters on node creation more points then he has on his profile, an error message should appear.
Static validation against a number works just fine, but how can I access custom fields of the user object? Using devel, for some reason they don't show up in dpm($user).

function custom2_form_contenttype_node_form_alter(&$form, &$form_state, &$form_id) {
drupal_set_message("Form ID is : " . $form_id);
dpm($form);
//$form['field_points']['und']['0']['value']['#default_value'] = 164;
$form['#validate'][] = 'custom2_form_contenttype_node_form_validate';
}

function custom2_form_contenttype_node_form_validate($form, $form_state) {
global $user;
dpm($user);
$profilePoints = $user->field_points;
$enteredPoints = $form_state['values']['field_points']['und']['0']['value'];
dpm($form['#validate']);
dpm($form_state);
if ($enteredPoints > $profilePoints) {
   form_set_error('field_points', '"You can only spend" .     $profilePoints . " //points."');
   }

}
EDIT: uploaded devel user screenshot

Try with this code it is helpful for you

<?php

function mymodule_form_alter(&$form, &$form_state, &$form_id) {
      if ($form_id == 'form_id') {
    $form['#validate'][] = 'my_validation';
                                      }
                                                                }

function my_validation($node, $form, $form_state){

    if (!isset($form_state['values']['field_text']['und'][0]['field_text']['und'][0]['value']))
    {
        form_set_error('Text', 'Select text');
        }

}


How can I install a specific core version? Composer always installs the latest version of Drupal core, but I want Drupal 8.6, not Drupal 8.7.
How can I install a specific core version?

Now Drupal recommended project supports version as command line option. If you want to install version 8.8.5 via Composer then command will like as shown below.
composer create-project drupal/recommended-project:8.8.5 <INSTALL_DIR>


Body field data not showing in View or Edit mode but exists in database This is very similar to this question, except there the asker answered with a solution that is not relevant.

Scenario: made a copy of a D7 site in order to apply new theme. All content types etc seem to be fine except one. In that case the body data shows in db in field_data_body table but does not show in View or Edit mode. The node has not been saved since the issue was noticed. There is only one value of revision_id for the node, and is same on both original and copy.

Body field is set to '1' but i believe that is correct, and is the same as on the site we duplicated.

The formats on original and live are both filtered_html and again this is working for all other content types

There are not field based permission modules involved. Thoughts?

here is row from original:

entity_type    bundle  deleted entity_id   revision_id language    delta   body_value  body_summary    body_format
node    committee   0   534 2416    en  0   George ...  filtered_html

here is row from copy:

entity_type    bundle  deleted entity_id   revision_id language    delta   body_value  body_summary    body_format
node    committee   0   534 2416    en  0   George ...  filtered_html

At this point, the issue seems to relate to language. Both live and dev have 'en' as the default language, but any new content on dev is being created as 'und', but as 'en' on live.

By way of a test, i copied the html from the db for one of the problem nodes, pasted it via Edit and saved, and the body then showed, but in the db it was flagged as being 'und'

BINGO - we had pulled a feature on to this site from another site. The other site had all fields set to 'not translatable' (field_config table).

On this 'inherited' site, some of the fields eg Body had been set to translatable, even though there were no other languages on the site.

And yes, the feature overrode the 'translate' setting in the db (there is no where to see this in the UI).

Setting body to '1' in the db has restored body being displayed, and some sanity.


set block to appear after page view This is probably a simple question, but how do you ensure a page view sites above a block on a page? Currently I have a page view which displays some content and then have a block view which holds some other content.This block view was added to the page view via the blocks page. Problem is the block appears before the page view content, any ideas on how to reorder this?

If I understand the question right, the answer should be as simple as changing the block region :
go to:
https://www.example.com/admin/structure/block

and change the specified block region to footer or a region below "main content region".

You may check regions positioning by clicking on "Demonstrate block regions (Your-Theme-name)"


Rules with Commerce Discount for a certain type of product. I'm trying to get a handle on Rules in Drupal.  The concept seems to be very flexible and straight forward for the most part.  However, I'm stuck and hoping someone can lend some assistance.

I have a Drupal Commerce store that sells two items.  Gift cards and books.  The store offers a volume discount of buying 3-5 books at a time. I have got the discount working using Commerce Discount and rules.  The issue is the discount is added to the entire cart, not just books.  Under Rules there is no way, that I can find, to select the content type of the line item being added and compare it to the books custom content type.

Can someone please explain or help me with where to look to only apply the discount to commerce products from the custom content type Books.

Here is the basic setup..
Drupal Core 7.15
Drupal Commerce 7.x-1.3
Drupal Discount 7.x-1.x-dev
Rules 7.x-2.2

Books is a Custom Content Type.
Discount should only be applied to Books.

Rules Setup
1. Event
   + Calculating the sell price of a product
2. Condition:
   + Entity exists by property //This one way I have tried but not working, seems the most reasonable way
   + Total product of type quantity comparison //This counts the total by product in cart
3. + Apply discount to product

You have a rule that reacts on "Calculating the sell price of an item" and a condition of "is of type BookDisplay (whatever the real display is called)". Then in actions you just apply the discount.

I have this working on a site.


How can I limit the number of email sent per hour in a rule? I have installed Mime mail and Mail System modules. I use an action in a rule:

  Send HTML mail to all users of a role

to send an email to a set of users.

Is there anyway I could limit the number of email sent per hour? For example, if the execution of this rule has to send 100 emails, It will be sent in blocks of 50 emails per hour.

I think It should be queue in cron.

Below is a summary of how you can get this to work:

Use the Flag module and introduce a flag to allow "flagging" all those "users of a role" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
Adapt the rule you already have, like so:

Remove the Rules Action "Send HTML mail to all users of a role".
Flag those "users of a role", using the new flag (from step 1) for each of the users. To actually do so create a view of those users (using Views), and use that view in combination with Views Rules to flag each of these users. Refer to my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?" (the option 2-part of it) for an example (with screenprints) about how to use the Views Rules module.

Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged users (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first 50 users only (50 is the value that seems to fit your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

Send HTML mail to each of the users in that VBO list.
Unflag (using flag from step 1) the user for which you just produced an eMail. This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the execution of the same rule within 1 hour (1 hour is the value that seems to fit your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every hour, Rules will notify 50 users "as requested".


Drush with multiple sites (all/modules) I've searched around but found no satisfying answer yet. I have all modules in sites/all/modules, so no site specific modules are present. I'm working on a VM.

First problem - creating a dump file fails:

drush @sites sql-dump --result-file

Second problem - updating the modules:

drush @sites update targets all sites, which is nice. But the modules are in all/modules, individual sites do not have any modules

Side question: Is there a way to update only the core?

I don't really use multi-site, so my answers here are hypothetical.  I recommend using a separate Drupal root for each site, unless you have a very strong reason to share code.

drush @sites sql-dump is not a good idea.  This is going to run sql-dump in turn on each of the databases of each of the sites.  If this worked correctly, you would either get all of the databases concatenated together (e.g. if you sent the dumps to stdout, and saved the result via output redirection), which you could never hope to restore, or, each database would be saved into the same result file, each overwriting the previous.  Drush does not support dumping multiple databases to a single dump file.

drush @sites pm-update will do redundant work.  It will run the code update on each site sequentially; the projects for each site are shared, so sites that are updated after the first will have most or all of their projects already updated.  After updating the code, pm-update runs updatedb on each site, which does need to be done for each site's database individually.  Note, however, that the most important part of an update is testing, so you might as well update each site individually.

If you want to update only Drupal core, use drush pm-update drupal.  To update everything except core, use drush pm-update --no-core.


Proper way to create custom tables I have tried to create custom tables for a module in Drupal via hook_install() and hook_schema() in module.install, and it works fine after disabling and enabling module using drush dre module_name. Is that the proper way to create tables in custom module ?

Can I use config/schema/module_name.schema.yml for creating tables? If not, what is the use of schema files in Drupal 8?

hook_schema() is not used differently from how it was used on Drupal 7, the only difference is that it is not used to create database tables for entities. (See, for example, node_schema().) In particular, you don't need to call drupal_install_schema()) in hook_install() to create custom database tables, which was instead necessary in Drupal 6.

.schema.yml files (for example, user.schema.yml) are used to define the schema for the configuration used in the configuration files from the module. Its purpose is different from defining a database table schema, and they cannot be use for defining custom tables used from third-party modules.


Module Rules-> PHP Code, trying to use a Form Handler from Pardot, but Pardot is not receiving the info I am trying to use the Rules module to send a form-handler to Pardot using a PHP script when a user logs in. I tested my variables to make sure they were valid by seeing them in a message and they appear fine. The problem I am having is that Pardot does not seem to be getting the form.

The Rules module information

Event: 'User Logs in'
Condition: none
Action: Execute custom PHP Code.

Pardot given form handler link

(similar to)

<form action="http://go.pardot.com/5/38543/2014-03-31/xyz" method="post">

Pardot has a link explaining that I could use an IFRAME instead a Form Action to POST.

Custom PHP Code:

$name = [account:mail];
$FName = [account:profile-user:field-profile-last-name];
$LName = [account:profile-user:field-profile-last-name];
echo '<iframe src="http://go.pardot.com/5/38543/2014-03-31/xyz?name='.$name.'&FName='.$FName.'" width="1" height="1"></iframe>';

Any help?

It seems the reason why was, that the Iframe was loading and then the page would redirect to wherever the onSuccess page would be set as. So this worked instead.

1- Created a module that hooked the user_login(&$edit,$account) function.

Within the function I defined my variables needed for the form handler, (this example will be email, first name and last name). In my case the First name and Last name were found in the Profile page so I had to get the Profile Id to find them.

$uid = $account->uid;
$mail = $account->mail;
$Fname;
$Lname;
$pid = db_query('SELECT pid FROM {profile} WHERE uid = :uid', array(':uid' => $uid))->fetchField();
$Fname= db_query('SELECT field_profile_first_name_value FROM {field_data_field_profile_first_name} WHERE entity_type = \'profile2\' and entity_id = :pid', array(':pid'=> $pid))->fetchField();
$Lname= db_query('SELECT field_profile_last_name_value FROM {field_data_field_profile_last_name} WHERE entity_type = \'profile2\' and entity_id = :pid', array(':pid'=> $pid))->fetchField();

2- After I used the user_cookie_save(array()) function so I can send the info to the IFRAME after the page loads. (this is still in the user_login function)

user_cookie_save(
      array(
        'pardotParams' => '?Email='.$mail.'&FName='.$Fname.'&LName='.$Lname.'&RequestUpgrade='.$RequestUpgrade.'&Serial='.$Serial.'&Industry='
        .$Industry.'&Country='.$Country.'&USFedOrg='.$USFedOrg.'&State='.$State.'&Company='.$Company.'&Phone='.$Phone ,
        'pardotUrl' => $url
      )
    );

3- Lastly, I added this bit of code in the page.tpl.php file found in my template. This will create the iframe off screen but still give it time to load.

<?php

  // Comparing the login time to the current timestamp to see if the user just logged in
  if (property_exists($GLOBALS['user'], 'login')
      && (time() - $GLOBALS['user']->login) < 5 ) {
    // Show the ParDot hidden iFrame. Added some css positioning to move the iframe off the screen
    // as it was throwing off the page alignment regardless of where it was shown in the template.
    echo('<iframe src="http://go.pardot.com/l/38912/2014-03-31/cz7' .
     $_COOKIE['Drupal_visitor_pardotParams'] .
     '" width="1" height="1" style="position: absolute; top: -999px; left: -999px;"></iframe>');
  }
?>


Sass/Compass tutorial for Zen? I'm trying to understand sass and compass so that I can take advantage of them when subtheming Zen, but I'm having trouble finding a good tutorial.

All of the documentation I find seems to already expect me to understand what the heck they are talking about. :) I've got a full understanding of standard CSS, that's not the issue.

I'm trying to do just the simplest thing and I'm not sure what the next step is. For example, by default the max-width is 1200 in the sass/layouts/responsive-sidebars.scss. I would like to change it, but when I make changes to responsive-sidebars.scss nothing in my actual presentation changes (I'm assuming because the actual presentation is using the actual css files in css/layouts/responsive-sidebars.css).

What am I missing? Do I need to do something to actively translate the scss file into the css in the other directory?

Nevermind, I finally found this documentation on how to get started and how to automatically convert the scss files into css files:

http://drupal.org/node/1548946


How to change a grouping field in a view programmatically? I've added a custom field to a view and want to display results as a grid grouped by this field. How do I set that "Grouping field Nr.1" option in my code? I tried the following but it doesn't work (probably I'm doing it in the wrong place or change wrong setting...)

function MYMODULE_views_query_alter(&$view, &$query)
{
    $view_name = 'MYVIEW';
    $display_name = 'MYDISPLAY';
    if ($view->name == $view_name && $view->current_display == $display_name)
    {
        $custom_field = 'field_MYFIELD_value';

        //code piece adding this field to a view's SELECT statement, sorting by it etc

        $style_options = $view->display['default']->handler->options['style_options'];
        $style_options['grouping'][0]['field'] = $custom_field;
    }
}

function MYMODULE_views_pre_build( &$view ) {
  $custom_field = 'field_MYFIELD_value';
  $view->display[$view->current_display]->handler->options["style_options"]["grouping"] = $custom_field;
}


Rules condition if user has certain roles not working at all? I have 2 roles:

Customer
Moderator

I have created a Rule:

Event. On account creation

Condition. If user has role: Moderator (and checked reverse, so when user doesn't have a role Moderator it should return TRUE), also as data selector i chose "account"

Action. Assign role: Customer, selector "account"

However, when i logged in with a user with role Moderator and create a new user with role Moderator it automatically adds the role customer as well. So my condition isn't working?

UPDATE I have tried in conditions: [site:current-user], still it adds the "Customer" role to a newly created account with a role Moderator by Moderator

Sorry, ignore my last comment.

You need a condition of "user as role" set to "site:current-user".
Then select the role that is required which is "moderator".
Leave everything else unchanged and save.

You need an action of "add role"
This action defaults to "account" so leave it as is.
Select the role you want to add, and save.


Automatically fill fields taking value from user profile I have a custom content type "Holiday". There is role for users, "Sponsors". Only the sponsor users can create this "Holiday". "Holiday" has many fields. Three of them are:

Sponsor Name
Sponsor About
Sponsor image

Also users have fields as name, about and image. Now i want that when a sponsor user is logged in and he/she creates a "Holiday" then the above three fields, i.e,
 1. Sponsor Name
 2. Sponsor About
 3. Sponsor image
are automatically filled in from the Sponsor user profile information, ie., Sponsor name is automatically filled in as the user name (who is logged in and creating the "Holiday"), Sponsor about from the User:about and Sponsor image from the image field provide for user.  How can i achieve this.

Any suggestions?

Thanks

use the form api and hook_form_alter http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7 and set the values of the form items to the items you specify
WIth form api you can specify a default value which you can set to what is in the user profile.


Allow creation of new content type just like taxonomy I like the way the Taxonomy module allows users to create a new taxonomy term "on-the-fly." Are there any modules that can also allow users to create new "content" of a node "on-the-fly"? Here is my scenario:

Content Type A (Companies)
Content Type B (Users)

Users have node reference to Companies, so every time a new user is added, a company is selected for this user.

I need to be able to just add a user directly on a Drupal 6 site, and if a company does not exist, I can also add a new company right there on the same page while adding that user. This works very similary with taxonomy, but I don't want to reference a taxonomy since Content Type A has also a lot of fields attached to it, which a taxonomy cannot do.

Do you mean the Node Reference Create module?