Can I simulate a hook using Devel's PHP execution? Let's say, for instance, that I want to quickly view the variables sent to HOOK_preprocess_node(), but I'm too lazy (if I'm just being honest) to edit my template.php file just to do that one check.

Can devel's Execute PHP block allow me to do something like this?

function SOMETHING_preprocess_node(&$vars) {
  dpm($vars);
}

Or is it impossible to use hooks in this context?

To clarify, my somewhat lofty goal is to be able to experiment with virtually any hook function quickly using Devel's PHP execution, and if there's a syntax for doing that. I realize there are some problems with that concept from the get-go, not the least of which is that you need to artificially create a context in which certain hooks will even be called, but I want to see what's available.

EDIT: Tenken's answer got me thinking. I could create a global array called, say, $devel_hooks. In a module, I could populate this variable with the contents of various hooks like so:

$devel_hooks = array();

function devhooks_preprocess_page(&vars) {
  global $devel_hooks;
  $devel_hooks['preprocess_page'] = $vars;
}

The contents of $devel_hooks could then conceivably be accessed at will, BUT there's a problem: Devel's Execute PHP block evaluates its content immediately on form submit and before the page loads again, so I couldn't put, say, dpm($devel_hooks['preprocess_page']); in there and get anything out of it because the page and its hooks haven't been processed yet, so $devel_hooks is completely empty or may even be undefined when that PHP is evaluated.

So maybe I could populate another global array with the information I want to request from $devel_hooks, and have the latest possible page hook (which might be HOOK_page_alter()?) parse that array and run a dpm() on the requested components of $devel_hooks. You would then, obviously, need to execute the PHP on a page that would use the desired hooks, but that's on you. I just haven't quite figured out how to connect those dots.

I could, conceivably, populate the array with strings and map those to array keys, but what if I want to dpm() something deeply nested in one of the hook arrays, like $devel_hooks['preprocess_node]['elements']['body']['#markup'] (just as an example, may not be accurate to what that array would look like)?

The main problem with simulating any hook is that the hook only makes sense in the context of whatever is doing the invoking.

Hooks get fired either from a module_invoke() or a module_invoke_all().  These functions assume that the hooks have already been found and exist in the registry.  They also take into account the invocation order (by weight, then alphabetically by module name).

The process and preprocess hooks are little different as the hook parameters get passed in by reference, and there is a more complex calling scheme, so the order really does matter for what is present in $variables.

The net result is that you can't really fake out a hook without actually implementing the hook somewhere.

Personally, I keep a devel module around with the most common hooks stubbed out as empty functions.  I also stub out common process/preproess and form alters.  This way I can dpm() something whenever I want without needing to do a cache clear.  For example, I have a high-weigh module with

/**
  * Implements hook_form_alter().
  */

function mytestmodule_form_alter(&$form, &$form_state, $form_id) {
  // dpm($form_id, 'form_id');
  // dpm($form, 'form');
  // dpm($form_state, 'form_state');
}

in it.  This way, Drupal already knows about the hook in the registry.  All I need to do is uncomment / edit the function as needed.


Wrapping content in anchor tags with CKEditor I am trying to wrap a block of HTML content in an  tag in a Drupal 8 installation:

Link 1

Subheader link 1

CKEditor changes it to:

Link 1

Subheader link 1

The Limit allowed HTML tags I have set are:

 <s>

How can I wrap content in an anchor tag with CKEditor?

I found a solution. As @Clive said CKEDITOR.dtd.a.h2 = 1; and CKEDITOR.dtd.a.h3 = 1; is the solution.
These need to be declared in a my_module.module file:
function my_module_editor_js_settings_alter(array &$settings) {

  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
        $settings['editor']['formats'][$text_format_id]['editorSettings']['customConfig'] =
        base_path() . drupal_get_path('module', 'my_module') . '/ckeditor_config.js';
}
  }
}

And then we create a file ckeditor_config.js:
CKEDITOR.dtd['a']['h2'] = 1;
CKEDITOR.dtd['a']['h3'] = 1;

Doing this we can wrap h2 and h3 elements with an anchor tag and CKEditor is not going to modify it.


What is the purpose of caches? I was wondering why caches exist. As a Drupal newbie, I often read solutions for all kind of problems that mention "you have to clear caches". Therefore, it appears to me that they only have disadvantages. This may sound a bit naive, but I would like to know what their purpose is.

Caching decrease your page load time and speed up your site. It is used especially when you have images, maps, videos and audio on your page. We can use drupal internal cache or integrate other caching tools like APC, Mem Cache, Varnish with our drupal site.

Why we clear cache?
 When we made some new changes in our theme or code, so to test them we clear old cache so that old data will be removed from cache and new data will be loaded to be displayed changes.


Add 'Or Condition' to specific field in Entity Query I'm building an entity query and I would like to check if one field contains one string or another. I'm building the query like so.

$searchname = 'test';
$searchtype' = 'type_1';

$query->condition('status', NODE_PUBLISHED);
$query->condition('field_type', $searchtype);
$query->sort('created','DESC');

However I'd like to check if field_type is either $searchtype or 'both'
I attempted to do so using an orConditionGroup like so

$orCondition = $query->orConditionGroup();
$query->condition('status', NODE_PUBLISHED);
$orCondition->condition('status', NODE_PUBLISHED);

$query->condition('field_type', $searchtype);
$orCondition->condition('field_type','both');
$query->condition($orCondition);
$query->sort('created','DESC');
$nids = $query->execute();

However it acts like the orCondition isn't being considered at all. Using $orCondition it still does not produce nodes that have 'field_type' = 'both'. How would you go about checking whether a field contains one string or another in an entity query?

UPDATE: I added the field name to the or condition because I figured I would need to add it to both if I want it checked in both conditions. If there's a way around that, that'd be even better.

UPDATE 2:  I made a second attempt using this code but I receive a 504 Timeout error when loading the page

$searchtype = 'test';
$query        = \Drupal::entityQuery('node');
$conditionOne = $query->orConditionGroup();
$conditionTwo = $query->orConditionGroup();

$conditionOne->condition('status', NODE_PUBLISHED);
$conditionTwo->condition('status', NODE_PUBLISHED);

$conditionOne->condition('field_type', $searchtype);
$conditionTwo->condition('field_type','both');

$query->condition($conditionOne);
$query->condition($conditionTwo);
$query->sort('created', 'DESC');
$nids = $query->execute();

What I'm ultimately trying to accomplish is this logic

(status = true) AND (field_type = 'foo' or 'both')

So, the simplest way to rewrite this, would be:

$searchname = 'test';
$searchtype = 'type_1';

$field_types_array = [$searchtype, 'both'];
$query->condition('status', NODE_PUBLISHED);
$query->condition('field_type', $field_types_array, 'IN');
$query->sort('created','DESC');

The use of an array for the condition method forces the SQL query to be written as an IN query.

Reference documentation: QueryInterface::condition


Why with new bootstrap 3x-3.13 it doesn't work? After update bootstrap module my theme doesn't work correctly. I use this code in my template.php (sub theme based on bootstrap).

function mytheme_preprocess_block(&$variables) {
  $block = $variables['block'];

  // Create css id attribute based on the block's administrative name
  if ($block->module == 'block') {
    $custom = block_custom_block_get($block->delta);
    $id = strtolower($custom['info']);
    $variables['block_html_id'] = $id;
  }
}

It was before I updated module

It's after

First of all, bootstrap is a theme not module.
You were using following code to above the main container(outside the image area as soon in your attachment):

function mytheme_preprocess_block(&$variables) {
  $block = $variables['block'];

  // Create css id attribute based on the block's administrative name
  if ($block->module == 'block') {
    $custom = block_custom_block_get($block->delta);
    $id = strtolower($custom['info']);
    $variables['block_html_id'] = $id;
  }
}

If you were using this code in bootstrap theme's template.php, instead of a child theme, than after updating the theme the custom code will be no more there as the old files are replaced by new updated files.

So you need to add your code in new template file updated.


Where to put reusable code? I have used Drupal 7 for a while, but am only starting to learn to use the tpl and template.php files. As you would expect, I have become good friends with the documentation, but am still having trouble putting all the pieces together at times.

One thing that I have not figured out how to do, but seems pretty basic, is to create a function in template.php or a custom tpl file (not sure what I need as well as how to do it) that outputs HTML. Let me explain what I mean...

I have created a custom node--content-type.tpl.php. In there, I have put the following code in to replace the normal submitted by information:

<?php if ($display_submitted): ?>

      Created by <?php print $node->name; ?> on <?php print format_date($node->created, $type = 'medium'); ?>.

      Last revised by <?php print (user_load($node->revision_uid)->name); ?> on <?php print format_date($node->changed, $type = 'medium'); ?>.

<?php endif; ?>

I am trying to figure out how to reuse this code in some of my other custom node tpl files without simply cutting and pasting it in. I am obviously missing something basic. How can I go about doing this?

Re-usable template code should ideally be in its own template, backed by its own theme function:

function THEME_theme() {
  return [
    'foo_partial' => [
      'variables' => ['node' => NULL],
    ],
  ];
}

foo-partial.tpl.php:

      Created by <?php print $node->name; ?> on <?php print format_date($node->created, $type = 'medium'); ?>.

      Last revised by <?php print (user_load($node->revision_uid)->name); ?> on <?php print format_date($node->changed, $type = 'medium'); ?>.

There are a number of different permutations you could use to actually get that HTML into the node template, here's one of them:

function THEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'page' && $vars['display_submitted']) {
    $vars['submitted_html'] = [
      '#theme' => 'foo_partial',
      '#node' => $vars['node'],
    ];
  }
}

node.tpl.php

...
<?php
if ($display_submitted && $submitted_html):
  echo render($submitted_html);
endif;
?>
...


Import/export configuration and translations I downloaded the .po file for loading the Italian language and installed it on my local version of Drupal.

Then, I launched the config:export command with drush and I committed the created configuration files

When I imported the configuration on the target machine (via jenkins) I did not find all the translations loaded

In particular, compared to about 7,000 exported translations, I find only 600 imported ones

Why did this happen?

The translations are not part of the configuration.

You can configure and export the source of translation files. One option is to have the local filesystem as the source. The translation files are stored locally in the sites/default/files/translations directory, but can change this directory on the File system configuration page.

What you could also configure and export how frequently you want to check for new interface translations for your currently installed modules and themes. At
/admin/config/regional/translate/settings

Check for updates

Never (manually, this is the default)
Weekly
Monthly

You can manually download the translations at:
/admin/reports/translations/check?destination=/admin/reports/translations


Referenced entities show old value when changing properties I have three custom entities, all generated with Drupal Console. I only added some basicFieldDefinitions to them before testing some CRUD operations on them.

I have these entities:

ConfigEntity (config entity - lowest level)
ChildEntity (content entity - has an entity_reference field to ConfigEntity)
ParentEntity (content entity - has an entity_reference field to ChildEntity)

When I display the name of the ConfigEntity through the entire chain, it displays properly

// "Original Value"
$parentEntity->get('child_entity')->entity->get('config_entity')->entity->label()

When I update the name, it still displays the original value through the chain, although printing it from the entity itself, it is the new value.

// "Original Value"
$parentEntity->get('child_entity')->entity->get('config_entity')->entity->label();

$configEntity = ConfigEntity::load(1);
$configEntity->set('label', "New Value")->save();

$configEntity = ConfigEntity::load(1);

// "New Value"
$configEntity->label();

$parentEntity = ParentEntity::load(1);

// "Original Value" instead of "New Value"
$parentEntity->get('child_entity')->entity->get('config_entity')->entity->label();

Any idea if there's a cache tag mechanism I have to implement manually, or something I have to invalidate myself in code?

You can clear the static entity cache with EntityStorageBase::resetCache:

\Drupal::entityTypeManager()->getStorage('parent_entity')->resetCache([$parentEntity->id()]);


How to display a view on user's profile page? I would like to select fields associated with users and display the outputs on users' profile page. In other words, when someone navigates on a user's profile page, the outputs of the selected fields get displayed.

I tried to do that with a user views and I tried setting up different types of contextual filters (such as 'user ID', Provide Default Value, User ID from URL). But nothing seems to be work, the view does not display. When I remove the contextual filter, the view does display on the page so the problem seems to originate from the filter I selected or how I set it up.

The problem is probably really simple but I'm missing something here. Any hint?

Thanks a lot!

Looks like you may be looking for Viewfield module:

  Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Install it, and add viewfield to user profile just like you would add any other field.

Alternatively you can create a block display and choose to display only in /user/* paths, using contextual filters. This is the way I like less, as it is more prone to fail if someone will redesign URL system on page, or choose to display users in a way other than default.

Exact steps

As described by OP in comment below:

  I created a view and added a contextual filter (Profile: User UID => Display all results for the specified field => Specify validation criteria/Basic validation);
  created a view field in the Main Profile page; and
  selected the token [profile2:user:uid] from the placeholder tokens' list and checked the box "Always use default value".


display view mode on node based on field setting or taxonomy term of user profile I'm using Display Suite which is awesome and an easier solution if you're not a coder. Now that I have created several view modes I'd like to set a particular view mode that is based on a field setting (a taxonomy term in my case) in the viewing user's account setting (I guess that's also called the user's profile, right?). It seems that DS is mostly used in conjunction with Views but I simply want users to get a different view mode when viewing the node without Views. I think I'll have to create a separate module for that or add a preprocess function to my template file but I have no idea where to start. Can anyone share their suggestions with me on how to do this? I'm not a coder but I think I can implement some code, though. Cheers!

Not entirely sure if i understood your question, but I believe the Entity view modes module might help you to define custom view modes for entities, which in your case could be a taxonomy term field in your node type or user profile.

  The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities. Custom entities are added to the entity registry via hook_entity_info_alter() so they are available to any code that uses entity_get_info() to provide a list of view modes for an entity. This includes node and user reference fields, Views, etc.


pass parameters drush_make or drush_make_process I would like to call the following drush make command within drush script:

drush make someFile.make --no-core --contrib-destination=sites/all --yes

However, the Drush API for drush_make and drush_make_process only takes the directory name of the make file(thats how i uderstand, but may be wrong). So, i tried something like:

  drush_set_option('no-core',true);
  drush_set_option('contrib-destination','sites/all');
  $status = drush_make_process('.');
  //$status = drush_make_process('someFile.make');

This doesn't work. It appears that the make file is not even processed.  Any help i would much appreciate

The most stable way to call Drush from a php script is to use drush_invoke_process.

For example:

$values = drush_invoke_process('@none', 'make', array('someFile.make'), array('no-core' => TRUE, 'contrib-destination' => 'sites/all', 'yes' => TRUE));


error 500 when D8 site placed in maintenance Unless connected to admin , putting site in maintenance generate a 500 error.

I have followed Drupal 8 maintenance page theming instructions, modifying the settings.php and adding the template to the theme but it is still not working .

How can i debug this ?

BEGINNER VERSION

Maintenance mode is working in general. Use the following direction of debugging: FROM "untouched" Drupal TO your state.

Download a same core version of Drupal as you have. Turn on maintenance mode (without changing anything else), visit the page with a non-admin user.
Apply the settings in your link about (Drupal 8 maintenance page theming ) visit again the page with a non-admin user.

Whenever the site brakes you know where the problem resides.

ADVANCED VERSION

500 errors are always logged in Drupal. Check what says the "recent log messages" with admin.
Also you can set in your settings.php

$config['system.logging']['error_level'] = 'verbose';

This won't just show 500 error, but also tell the reason.


How can I ensure that every page within my drupal 6 site loads a specific Javascript file? I want to include the sites/all/themes/fusion/mapsindeed/js/css3-mediaqueries.js
 file so that mediaqueries will work within Internet Explorer 8 and below, like it already does for other web browsers.

How can I do it?

Add the URL of the JavaScript file as scripts[] to the theme's info file.


Automatically change field when another field value is selected I have a content type called Jobs.

This include a field contact which is user reference.

I have another content type called Job application.

This includes a node reference based on Jobs and field contact which is user reference.

I want when a user selects a job in the node reference select list on the job application form to automatically change the contact field in that form which the value that exists in the contact field for the relevant job selected.

Example:
Job: Educator
contact: Michael

On Job application upon selected the job "educator" the user reference field should automatically take the value Michael.

Any ideas on how to solve this? Would Rules work and if so how? If through programming, is there a module that allows for injecting code for content types?

Preferably I am looking for a solution that does not involve programming.

This sounds like a bad case of data de-normalization. You shouldn't have a "Contact" field on your "Job application" content type if it's simply going to duplicate whatever is already in the "Job" content type.

If you're simply wanting to be able to see who the contact is for a given application, use the "Rendered entity" formatter for the job reference field on the application content type. (I'm assuming you're using the Entity Reference module?) In the formatter settings, choose a view mode that only displays the contents of the Contact field on the job node.

This way, if the contact ever changes for the job, it'll live-update across all job applications.


How can i add a block below the Main Menu? I asked for a second horizontal menu here. But i couldn't manage to success so i'm changing my question a bit.

I want to add a block below the "Main Menu". I will put a table into that new block, which will be looked like a horizontal menu.

In my default case "Main Menu block" is disabled. But i can see the Main Menu horizontally. I ccan't understand how it can be seen :) When i enable "Main Menu block" from "admin/structure/block" that block becomes visible where i set its position, but it sorts Main Menu Items vertically. Also horizontal Main Menu still appears. (That case is also occurs for "User Menu". Its block is disabled. When i enable its block it comes with a vertical menu)

What's the position of the "below of the horizontal Main Menu" in Bartik theme? I created new block and put it to highlighted, help, featured regions. Help and highlighted regions doesn't cover all horizontal part. Featured tooks three times more place than the block.

So i couldn't find a way to put my new block just below the Main Menu..
I would be happy if you can help. Thank you.

The main menu that you can see in the theme is not in a block.  It's printed at a certain spot within your page.tpl.php page in the bartik theme.  Check it out (make a copy first) and mess about to see the results.
If you want to add a new block to a region that doesn't already have a block check out this post http://drupal.org/node/1088718 as it details how to do so.
Your other question had to do with why the menu renders vertically instead of horizontally like the main menu, it's all due to the css styling.  Chances are that the menu is in an unordered list

 and that the list items (menu links) have been set to display:inline or float:left.
I hope I was of some help


Apache SOLR index or retrieve the node a file is attached to I'm building a search engine with Apache SOLR (8.7.0) where PDF files are indexed and searched through, that part is working (with search_api_attachments in case you're wondering). However, the client wants to show a link to the node where this file was referenced from. This is using plain file fields, no media library. Is there a way to either index the node ID with the file, or get this reference somehow in the view with a relationship or something? Spent a good day on it but couldn't figure it out, maybe I'm just overlooking it. Or is this something that would require me writing a custom hook to add the field to the index? (it seems like quite a general use case to me though)

I am not sure if this can be done with a generic file field. It could be possible if it was a media or entity reference field. I think the simplest approach is to use hook_search_api_solr_documents_alter to find and add the node ID to the document when it is being indexed.
You can, possibly, then use the new field to create a relationship to Node table in the view to display the link or simply handle it on the theme level.


Adding a line break or space in TWIG I'm trying to configure email confirmations that are sent out by one of our web forms. At the moment they are appearing without line breaks but I want to be able to have line breaks between certain strings.

At the moment one of our vendors hosts and designs our site, so we have have limited access to edit and configure.

Is it possible to do what I want in the body?

**we are using Drupal 7.
**below is a screenshot of what I have the ability to edit.

In the Twig documentation, there is an entry that can help you out: https://twig.symfony.com/doc/2.x/filters/nl2br.html

{{ "I like Twig.\nYou will like it too."|nl2br }}

will output:

I like Twig.<br />
You will like it too.

So inside a string, you could use \n or the function nl2br at the end of it.


In Drupal 6, how to display two grouping fields such as Country then Province? In Drupal 6, I have a view for certain objects with Location:Country and Location:Province fields, both set to Exclude From Display; sort criteria to sort first by country then by province; and Style setting Grouping Field to be Location:Province. That displays all the objects in the order I want, everything with the same country grouped together, then within each country objects are grouped by Province/State, each state's group of objects labelled with the name of the state.

However, I would like to have a group title displayed for Country, not just Province, so it would look like

Canada
  Ontario
    object 1
    object 2
  Quebec
    object 3
United States
  Arizona
    object 4
  California
    object 5
    object 6

I'm a newbie to Drupal. Is there a standard way to do this? I've tried search terms such as nested grouping and multiple groups but haven't found mention of this use case.

If you are comfortable with theme templates, you could do this by modifying the Style output, eg:

for your View.  Here I created a quick View called for-da-grouping like this:

which has the node title and then two fields, country and province which are excluded from display.  I am sorting first on Country and then within that Province, so, given the same information in your example, this produces:

But, if you add some logic to your new Views template:

<?php
/**
 * @file views-view-unformatted.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */

$country='';
$province='';

/*
  drupal_set_message('
' . print_r($view->result[0], TRUE) . '
');

    [node_title] => object 1
    [nid] => 660
    [node_language] =>
    [node_data_field_da_country_field_da_country_value] => Canada
    [node_type] => page
    [node_vid] => 660
    [node_data_field_da_country_field_da_province_value] => Ontario

*/

?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if ($view->result[$id]->node_data_field_da_country_field_da_country_value!=$country): ?>

      <?php print check_plain($view->result[$id]->node_data_field_da_country_field_da_country_value); ?>
      <?php $country=$view->result[$id]->node_data_field_da_country_field_da_country_value; ?>

  <?php endif; ?>
  <?php if ($view->result[$id]->node_data_field_da_country_field_da_province_value!=$province): ?>

      <?php print check_plain($view->result[$id]->node_data_field_da_country_field_da_province_value); ?>
      <?php $province=$view->result[$id]->node_data_field_da_country_field_da_province_value; ?>

  <?php endif; ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

You can get:

Now, things to look at in specific:

You need to sort your View first by country and then by province so the data is in the right order to begin with.
You need to know your Views results, they are stored in $view->result and you can get what you need out of looking at $view->result[0] and in my view, my two fields I want to group on are called node_data_field_da_country_field_da_country_value and node_data_field_da_country_field_da_province_value  but yours are most probably going to be different but the logic is still the same:  Only display the country and/or province if it has changed since the last time it was displayed.
Add some css to your new group headings and you should be all set.

If not, you can investigate the Views Field Module and so forth mentioned in https://stackoverflow.com/questions/9015500/how-to-group-by-more-than-one-field-in-drupal-view for alternative methods.


Set a data value for a content field with rules I am able to create a new content with rules whenever a user has been flagged as 'satisfied'. However, i need to fill in the fields as well with the flagged username, and some other fields in the flagged user profile. This i tried to do with 'set a data value' but the parameters doesn't seem to be available. Only 'site' and 'node' is available in d data selection field.
Is there a way to 'fetch' the user profile of the flagged user and use it in the fields of the newly created contents?

Solved by myself.

under the same rule (after a user has been flagged, )and after "create a new entity", I added 'set a data value' and chose 'entity-created:'. This then followed by the value "flagged-user:...".

If you understand my question, then you should understand my answer.lols


hook_preprocess_field() $variables crashing while printing I am trying to modify a file field value and add a download svg icon and then add it to a twig file by using a preprocess field.

function myfi_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'field_download') {
    print_r($variables);
  }
}

I am not sure what I am doing wrong here but the variable is not loading and it is timing out (memory exhaustion)

Use Devel with vardumper and dump only the $element instead of the whole $variables something like:

function myfi_preprocess_field(&$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == 'field_download') {
    // Dump only the element.
    dpm($element);
  }
}


How to add a class attribute to a block? How can I add a class attribute to a Drupal 8 block?

There are many examples in Drupal core such as the help modules that sets the role attributes for the block. So following that I can succesfully add a class.

/**
 * Implements hook_preprocess_HOOK() for block templates.
 */
function mymodule_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'mymodule_my_block') {
    $variables['attributes']['class'][] = 'my-nice-block';
  }
}

Is it possible to add a class without the preprocess hook?
Ideally within the block plugin file located in src/Plugin/Block/ ?

This would help keeping all the code related to one block contained in one location.

Have you tried to just set #attributes on the render array returned by our block plugin?

$build['#attributes']['class'][] = 'my-nice-block';

Looking at BlockViewBuilder::preRender(), that should work.


views replacing ul li within a large block of html text I have a odd issue.  I am using Views 3 and Drupal 6, when I create content with ul and li tags, Views strips out the list tags and replaces them with the following:

nbsp;
     .nbsp;nbsp;nbsp;nbsp;content
     .nbsp;nbsp;nbsp;nbsp;content
     .nbsp;nbsp;nbsp;nbsp;content
     .nbsp;nbsp;nbsp;nbsp;content
nbsp;

instead of:

content

content

content

content

The content appears correctly in the database, but in display and preview from Views the rewrite happens.

I have the following options:
add default classes
  rewrite output (this was the first thing I checked and is displaying this behavior regardless of this rewrite)
hide contents if empty.

thanks

I would suggest installing the Theme developer module and tracking down the template that might be rendering that output.


Which parameter do I need to pass for user registration? I have first name, lastname, email, password, confirmed password and gender
for user registration like facebook registration when I visit https://example.com/my_services/user/register.

Then I get the error "You are not allowed to change your username" when I select put method. How do I find the keys of that fields so that I send key and values?

I don't know which parameter I need to send with the URL.

$user_data["field_name_first"]["en"][0]["value"]='testranjeet8';
$user_data["field_name_last"]["und"][0]["value"]='testgholave8';
$user_data["mail"]="testranjeet12@example.com";
$user_data["pass"]["pass1"]="test123458";
$user_data["pass"]["pass2"]="test123458";
$user_data["field_gender"]["en"]="Male";

Just pass the parameter you will get the result .I had problem with android side that they are not passing value correctly
finally i got answer


counter on each images in view I have a view that display 8 images(which links to their particular node) uploaded by the all users, now i want to display a counter which counts total number of times that image or that image link have been visited/viewed.

Please help me.

I think ..Its like if you on the left of this Question answer section on this site they have mentioned three things
1.Asked Today
2.Viewed 4 times(or total no. of times viewed )
3.etc

my requirement is second.
Thanks

Sounds like Node view count module would be suitable, especially as it integrates with views.


How to display the webform submission data in the below format in Views? I want to display the webform submission data along with some other information in the below mentioned table format (like multiple rows for a particular column inside of a table).

Is it possible with Views, or can anybody suggest a module, if there is such or any other way of getting it? I tried searching but found no module that meets my requirements.

Use the Webform MySQL Views module.
Then navigate to web form, you will find separate tab MySQL views.
Generate one view form the same by navigating to that view.
When the view is generated, you will find this view under structure menu, under views section.
Then you can display it as you wanted to display, either in grid, unformatted list, tabular format, etc.

As your image seems colourful and in tabular format, you could use CSS classes for that, applying them under Advance section.


Colorbox has broken my site. Help! I had downloaded the libraries module. I then watched another tutorial which told me to CREATE  a libraries directory in the sites/all folder. WHich I did, I then downloaded the colorbox plug in and pasted it in the empty libraries directory. I am now getting the following error:

Fatal error: Call to undefined function libraries_get_path() in /Applications/XAMPP/xamppfiles/htdocs/drupal/sites/all/modules/devel/devel.module on line 407

I deleted both libraries directories to start from scratch but the error is still there. How do I fix this?

libraries_get_path is defined in libraries.module

Make sure the Libraries API module ( e.g 7.x-2.0 ) is installed and enabled.


Should I disable all UI modules once the site is in production? Just wondering if I should I disable all UI modules once the site is in production?
e.g.: Context UI

Most of them are not required for any other module.

This is probably considered best practice in terms of performance because on every call each module is loaded into memory and executed.

However you may find it annoying to have to constantly re-enable the modules, particularly with views or rules.


Drupal site does not show well when SSL is enabled We have our site hosted on our Virtual Ubuntu 12.0 LTS. I am converting it to HTTPS. We are using Secure Login so that anonymous sessions are via HTTP or HTTPS and authenticated sessions only via HTTPS.

When I enable /var/etc/apache2/sites-available/site-ssl ->

On IE, I get this message "Only secure content is displayed" Click here to show all content for every page we navigate to. When I accept to show all content, the website renders on IE 11.

The CSS is not being picked up at all on a chrome browser ( Version 34.0.1847.116)

I have attached the screen of the site. You will see the menus are not in place. The flex slider images are one below the other.

Any ideas or help to fix this is appreciated !

You get this message from MSIE because the page has a mixture of secure and insecure content.

The culprit is usually inline/embedded content (images, iframes, javascript, css, etc.) that originate from a non-secure URL. Chrome just refuses to load it, causing the error you see To fix it, you need to locate those elements of the page, and replace them with secure versions.

To locate for these elements of the markup (unless they are obvious now that you know what to look for), use FireBug (requires that you use FireFox instead of MSIE/Chrome) or just press CTRL+uin MSIE to analyze the markup.  In the markup, search for inline/embedded content hyperlinked with URLs starting with http: (instead of https:).

If all your links are internal (i.e. pointing to stuff below the webroot of the same server), you can eliminate the problem by dropping the scheme element of the URL (as suggested in a comment below by @JohnathanElmore).

In other words: if your server is example.com and you currently have the following URL reference as part of your theme:

src="http://example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

you should replace it with the following:

src="//example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

or even:

src="/sites/all/modules/spamspan/spamspan.js?somequerystring"

I can't tell you exactly how to go about making these replacements without knowing what you can and cannot do on your site. (If it was my site, I would simply edit the theme templates and clear alll caches. But I've no way of knowing whether this option is available to you.)


How to implement Taxonomy as Role? I am building an application for a university where teachers will submit questions(MCQs) into Topics(Vocabulary) containing many terms infact in hundreds.

Our business logic is so that teachers will be allowed to submit questions only of their respective academic field, so we need to limit the list of topics to teachers based on their area of field. For example computer science teachers will submit questions in computer science term and its children.

So basically what I want it, something like one role per taxonomy term, I tried the Taxonomy Access Control module and the user permission module, but to no avail.

Is there a better solution for limiting taxonomy terms per user? Not per role or should I then create a role against every taxonomy term?

The Taxonomy Term Permissions module is what you are looking for.

From the project page description:

  This module allows taxonomy administrators the ability to restrict
  setting individual terms on nodes by user or role.


I want to change default product variation machine name? I am working in Drupal Commerce kickstart. It's have default content types like hats,bags_cases,tops and all. I want to change the machine name also.Is it possible?

I am going to change structure->content types -> edit

But I can't change it...

Yes its possible.

if you want to edit the machine name of your content type name 'pages' then goto 'admin/structure/types/manage/page' --> click the "edit" button and update with the required value.

Same way you can do it for any content types.

Thanks


template associated with views style-plugin, and then customized for particular view: views does not find template I have a style plugin, 'mystyle'. And I created a view, 'myview', with style set to 'mystyle'.

Here is the declaration of 'mystyle' in hook_view_plugins:

function mymodule_views_plugins() {
  $plugins = array(
    'module' => 'mymodule',
    'style' => array(
      'mystyle' => array(
        'title' => t('My Style'),
        'handler' => 'mymodule_views_plugin_mystyle',
        'theme' => 'mymodule_views_plugin_mystyle_template',
        'uses fields' => TRUE,
        'uses row plugin' => FALSE,
        'uses options' => TRUE,
        'uses grouping' => FALSE,
        'type' => 'normal',
        'even empty' => FALSE,
      ),
    )
  );
  return $plugins;
}

I have the following files in mymodule/views:

(handler)
mymodule_views_plugin_mystyle.inc

(template associated with this style)
mymodule-views-plugin-mystyle-template.tpl.php

(template associated with this style, and customized for the view 'myview')
mymodule-views-plugin-mystyle-template--myview.tpl.php

My problem:
Views is using the first, less specific, template (mymodule-views-plugin-mystyle-template.tpl.php) to display this view.

When I edit 'myview' and click on "theme information", I see both templates listed under "style output":

mymodule-views-plugin-mystyle-template.tpl.php
mymodule-views-plugin-mystyle-template--myview.tpl.php

The first, less specific, template is in bold. If I understand correctly, this means that views found the first template but did not find the second.

I have tried rescanning, but that does not help. I have also tried deleting the cache.

Should this work? What do I need to do to get views to find the more specific template?

Drupal by default doesn't scan for more specific templates in modules directories, but views allows you to do it by adding 'template path' to hook_views_api(), see: https://api.drupal.org/api/views/views.api.php/function/hook_views_api/7.x-3.x


Custom Entity field of type long_text not storing values I created a entity.

$fields['supplemental'] = BaseFieldDefinition::create('text_long')
                ->setLabel(t('Supplemental'))
                ->setDescription(t('Answer description.'))
                ->setDisplayOptions('view', array(
                    'label' => 'hidden',
                    'type' => 'text_default',
                    'weight' => -3,
                ))
                ->setDisplayOptions('form', array(
                    'type' => 'text_textfield',
                    'weight' => -3,
                ))
                //->setRequired(TRUE)
                ->setDisplayConfigurable('form', TRUE)
                ->setDisplayConfigurable('view', TRUE);

And I'm saving data into this entity's field like

$mcq = Mcq::create(array(
           'supplemental__value' => $value->supplemental,
            'supplemental__format'=>'basic_html',
        ));
$mcq->save();

Issue is all fields gets populated except of type 'text_long'. Am I missing something or there is any other way of populating entity field values.

After realising few minutes later, the column name should be supplemental not supplemental__value.

I was mapping content by looking into database columns which was wrong.


Response comes after 6 min while creating user using services module of Drupal 7? I have a client side application developed in angularJS. As i am sending POST request to Drupal to create user, user is getting created without any delay if i check in Backend. But i get response after 6minutes!. The request just goes on and on!! Any advice what i am doing wrong?

It's unlikely that your site needs 6 minutes of CPU time to create a user but you can confirm that checking the system load during the process.

When I've faced that kind of problems the reason was one or more timeouts when trying to connect to an external service from the server.

For example, imagine that when you create the user the site querys an external database via an HTTP connection checking for the user usual nickname (Abigail → Abbie, Peter → Pete, etc). If that external service is down your site happily will launch the connection, waiting patiently the answer until the timeout is reached and connection is closed. If your site tries to connect six times and system timeut is 30 seconds then there you have your six minutes for use creation.

Check your installation for modules that may conenct to external services, check dblog for timeouts errors messages, check system log for similar messages. Disable any suspicious module and try to create a user.

If this only happens when using Services (not in the regular user creation form) narrow your search to any Services related modules or custom code.


Ajax via Jquery and attach behaviors The Ajax framework is very nice but i want more complex effects. So I am trying to do the Ajax calls via Jquery. The goal here is to load nodes by clicking some links on the menu but the nodes  contains an image which pop ups with a lightbox and also contains a from which submits via Ajax. For demo site i am using Drupal commerce. here is the demo to check out.

I am using    Drupal.attachBehaviors(document); to re-attach the needed js scripts. The problem is that some of the behaviors are attached and some others are not. For example the first menu link 'Products' is a view and it uses ajax pagination but it loses this functionality but the image lightbox in this view does work. So i am little confuse here.

This is my code.

/*
 *  Implemets hook_menu()
 */

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

$items['myajax'] = array(
    'title' => 'Ajax',
    'page callback' => 'myajax_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

$items['myajax/view'] = array(
    'title' => 'Ajax',
    'page callback' => 'myajax_view_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

return $items;
}
/*
 *  Ajax handling
 */
function myajax_callback($nid = '') {
      $node = node_load($nid);
      $vnode = node_view($node);
      return theme('node',$vnode);
}

function myajax_view_callback($view = '') {
      print views_embed_view($view, 'default');
}

and my js file

(function ($) {

Drupal.behaviors.myajax = {
    attach: function(context,settings){
        $('#main div.column').before('
Loading...
');

        $('a.ajax_link', context).once().bind('click',function(e){
            $(this).addClass('ajaxafy');
            e.preventDefault();
            var url = $(this).attr('href').split('/');
            //console.log(settings);
            $('#loading').fadeIn();
            $.ajax({
               type: "POST",
               url: Drupal.settings.basePath + 'myajax/' + url[2],
               data: {'js':1}, // you can also pass block name and act more dynamicly
               success: function (response){
                  $('#loading').fadeOut()
                  $('#main #myajax', context).html(response)
              Drupal.attachBehaviors(document);

              },
            });
        });
        $('a.ajax_link_view',context).once().bind('click',function(e){
            e.preventDefault();
            var url = $(this).attr('href').split('/');
            $('#loading').fadeIn();
            $.ajax({
               type: "POST",
               url: Drupal.settings.basePath + 'myajax/view/' + url[1],
               data: {'js':1}, // you can also pass block name and act more dynamicly
               success: function (data){
                  $('#loading').fadeOut()
                   $('#main #myajax', context).html(data);
                   Drupal.attachBehaviors(document);
              },
            });

        });

    }
};

})(jQuery)

Alse the webform submits also using Ajax but it loses that behavior.

What i am missing here? Please check the demo to see what's going on. Thanks in advance.

Must be:

Drupal.attachBehaviors($('#main'), context);


Clone SelectQuery doesn't seem to work I want to change the sorting of a view with something very specific which needs 2 subqueries.

So far, I tried to do something like this:

$sorted = false;

function mymodule_query_alter(&$query) {
  global $sorted;

  $view = $query->getMetaData('view');
  if( !$sorted && $view->name == 'my_view' ) {
    $sorted = true;

    $subquery_1 = clone $query;
    $subquery_2 = clone $query;

    // Apply sorting stuff...

    $query = $subquery_1->union($subquery_2);
}

Then I just realized that this desn't even work (while my view is working):

$subquery = clone $query;
$query = $subquery;
dpm($query->__toString());
dpm($query->arguments());

It doesn't return any result, but everything seems ok in the dpm dump.

Have I done something wrong? Or maybe should I handle this problem in another way?

EDIT:

I need to get a list of nodes sorted this way:

Sticky nodes | order by date.
Nodes in one of the taxonomy-term selected in user profile | order by date.
Other nodes | order by date.

I've already a working SQL request (actually 3 with UNION), but I need to make it work with Drupal.

So, I was working on a test for @Mołot to reproduce the clone bug, and I couldn't with a fresh view.

I tracked down the difference :

With the filter Published or admin: the cloned query didn't return anything.
No problem with the simple Published filter.

Don't ask me why.

As @autopoietic said, working with core query_alter_hook wasn't a good idea. I switched to views hook, and got the SelectQuery object :

function mymodule_views_pre_execute(&$view) {
  $query = &$view->build_info['query'];
}

Then I was able to do my sorting.


How to override Drupal.ajax.prototype.beforeSend? I need to add my own little if's and checks in 3 functions inside

misc/ajax.js (
  Drupal.ajax.prototype.beforeSend,
  Drupal.ajax.prototype.success,
  Drupal.ajax.prototype.error
)

How can I override them in my module? I can't find a manual and it's not in Examples for Developers. Sorry if it seems a dumb question, but I'm a php developer - I can work with js, but I'm not so fluent with it.

Can I simply write it in my module's js file?
If 2 or 3 modules needs to modify them, how to avoid conflicts?

This might be a better way:

(function ($) {
  // Drupal's core beforeSend function
  var beforeSend = Drupal.ajax.prototype.beforeSend;
  // Add a trigger when beforeSend fires.
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    beforeSend.call(this, xmlhttprequest, options);
    $(document).trigger('beforeSend');
  }
})(jQuery);

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


Views: Can I create views based on taxonomies that link to other, context-specific taxonomy-based views? I need to keep things in taxonomies so that I can retain the faceting behaviour in search, but I would also like to set up a more conventional way of drilling down through pages (and I'm hoping Views will let me do this).  I'm wondering if I can have a Views page that lists all the items in one taxonomy package, but when a user clicks on one of those items, they are taken to another set of taxonomies.  When they select something from that page, they are given only the list of nodes that have both taxonomies applied to them.

It will probably be too confusing to explain exactly what I'm working with, so let's say I was creating a page that collects government documents.  Every node corresponds to one document, but every document will have a taxonomy for region (i.e., California, Texas, etc.) and department (i.e., Transportation, Education, etc.).  So the first View would show all the states, and when they click on a state, they're taken to a list of departments.  When they click on a department, they're shown a View that lists all the documents for that state.

I realize this is just faceting behaviour, but I've been requested to build something like this anyway.

One solution is to create a view showing taxonomy terms.

Display 1

Create a page display with a path "documents"

Add a relationship "Taxonomy term: Content using <state vocab>." Require this relationship.

Under Other > Query Settings select Distinct

Add fields

Taxonomy term: Term ID
Taxonomy term: Name

Exclude term ID from display

Rewrite the results of Name > Rewrite the output of this field:
[name]

Add a filter Content: Type (= <your document content type>)

Display 2

Create a new page display with a path "documents/%"

Remove the Relationship for the state for "This page (override)" and add a relationship for your Department taxonomy. Require this relationship.

Add a contextual filter for Content: <state field> and display contents of "No results found" when filter value is not in the URL.

Edit the rewrite value of your name field, make sure to select "This page (override)": [name]

Display 3

Create a third page display with a path "documents/%/%"

Keep the state relationship from the view's defaults, but add a relationship using "This page (override)" for your Department taxonomy. Require this relationship.

Add a contextual filter, override for this display, for Content: State and then add one for Content: Department.

Override your fields for this display, removing the Term ID and Term Name, and add a field for Content: Title.

If I have explained this well enough, display 1 should give you a list of states that link to display 2 using the contextual filter to give a list of departments from that state, linking to display 3 showing a list of your document node titles from that state department.


How to clear cookie with cookie name on from submit? When users fill values in node form input fields I set cookies of those values with help of javascript code, example :

    var date = new Date();
    date.setTime(date.getTime() + (60 * 60 * 1000));

 $('#edit-field-topic-und').on('change', function() {
            var section =  $(this).find("option:selected").val();
            console.log(section);
            if(section){
                $.cookie("section", section, { expires: date });
            }
        })

        $('#edit-field-topic2-und').on("change", function () {
            var topic = $(this).val();
            console.log(topic);
            if(topic){
                $.cookie("topic", topic, { expires: date });
            }
        });

        $('#edit-field-language-und').on('change', function() {
            var language =  $(this).find("option:selected").val();
            console.log(language);
            if(language){
                $.cookie("language", language, { expires: date });
            }
        })

If user does not submits from and next time come to node add form page, I set default values in from with help of form alter:

case 'link_node_form':
      /*show default values from cookie*/
      if (empty($form['nid']['#value'])) {

        if(isset($_COOKIE['section'])) {
          $form['field_topic']['und']['#default_value'] = $_COOKIE['section'];
        }

        if(isset($_COOKIE['topic'])) {
          $form['field_topic2']['und']['#default_value'] = $_COOKIE['topic'] ;
        }

        if(isset($_COOKIE['language'])) {
          $form['field_language']['und']['#default_value'] = $_COOKIE['language'];
        }

      // clear cookies after from submit
        $form['#submit'][] = 'custom_overrides_link_node_form_submit';

      }

Now when user submit form and node got created successfully cookie is not clearing or the cookies got values of last submitted node.

Please suggest how to clear / unset cookies when form get submitted.

function custom_overrides_link_node_form_submit($form, &$form_state) {

  if(isset($_COOKIE['section'])) {

    unset($_COOKIE['section']);
  }

  if(isset($_COOKIE['topic'])) {

    unset($_COOKIE['topic']);
  }

  if(isset($_COOKIE['language'])) {

    unset($_COOKIE['language']);
  }

}

By setting it to one hour ago time with empty value I managed to make it working according to my requirements.

function custom_overrides_link_node_form_submit($form, &$form_state) {

  if(isset($_COOKIE['section'])) {

    unset($_COOKIE['section']);
    setcookie("section", '', time() - 3600);
  }

  if(isset($_COOKIE['topic'])) {

    unset($_COOKIE['topic']);
     setcookie("topic", '', time() - 3600);
  }

  if(isset($_COOKIE['language'])) {
     unset($_COOKIE['language']);
     setcookie("language", '', time() - 3600);
  }

}


Title field input textbox way too long in firefox browser This looks a very simple question but I seem to find it rather difficult to find a very easy solution...

Textboxes in forms are way too long when looking at it using Firefox but not in Chrome. In Chrome, container widths are respected so the textbox width does not go over containers' width. However, default size of 60 when using Firefox just breaks the container width declaration and does not get respected...

I had the same css issue.
you need to address the input field correctly with the inputtype "text":

e.g.

.mywrapper-form input[type="text"] {
   width: 100px;
}


Send form result back to twig I created a module for searching values from external databases. My controller creates a form and send it to the custom twig page of my module.

The controller method that creates the form and send the data to the twig template looks like:

 public function customSearchPage($query, $results)
    {
         $searchForm = \Drupal::formBuilder()->getForm('Drupal\movies\Form\SearchForm');

        $searchForm['searchQuery']['#value'] = $query;

        return [
            '#theme' => 'insert_movie_page',
            '#form' => $searchForm,
            '#query' => $query,
            '#results' => $results,
        ];
    }

Now I created a Form using the Drupal 8 Form API. The submitForm method will send the inserted data to a compute class and gets a resultset back (array with multiple model objects). Now I need to send the resultset back to the twig template to show the results to the users. How can I achieve this behaviour?

SubmitForm method looks like:

 public function submitForm(array &$form, FormStateInterface $form_state) {

      $search = $form_state->getValue('searchQuery');

      $SearchController = new SearchController;
      $results = $SearchController->searchMovies($search);
  }

In submit you have two choices.

Rebuild

public function submitForm(array &$form, FormStateInterface $form_state) {

  $form_state->setRebuild();
}

The form and the twig template the form is wrapped in will be rebuilt and you can display the result.

This is a great question from @AdrianCidAlmaguer to demonstrate how this works with a basic example how to display the sum of two numbers: How to show a string once you submit a form in a page reloading the page?

Redirect

public function submitForm(array &$form, FormStateInterface $form_state) {

  $form_state->setRedirect($route_name, $route_parameters, $options);
}

You redirect to a new page and can display the result there.


How can I have a field value that is the sum of other (decimal) field values? I have created a custom content type with three decimal fields. I need to tally these three fields and then wrap the output of each one with a specific data attribute,  stating their respective value as a percentage of the total.

Am new to drupal so if someone could point me in the right right direction as to how best achieve this it would be much appreciated.

This question is tagged with Views, so I'm just going to go out on a limb and leave this here just in case: Views Calc

  This module adds simple calculations to a views table. Requires the
  Views module.

  You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).


Where are the primary and secondary tab blocks? I installed drupal 8 using the minimal install profile. For the admin pages I enabled the seven admin theme, but in the blocks admin screen I cannot find the Primary tabs and Secondary tabs blocks.

They are available under other names (I think one is called "Tabs") when you used the the minimal installation profile.

But you can import the blocks by entering the code of the files

profiles/standard/config/install/block.block.seven_primary_local_tasks.yml
profiles/standard/config/install/block.block.seven_secondary_local_tasks.yml

into the Single config import located at

admin/config/development/configuration/single/import

(this requires the config management module to be enabled)


What's the differences between these 2 queries to publish/unpublish nodes? I found these 2 queries to publish or unpublish a node programmatically:

db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

I do not understand the difference, and not sure which one use.

Any suggestions?

Let me explain you with all details....

Your First Query is update statement on node table in drupal database which sets node to publish for a particular nid...

db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

Node table is a base table which stores node related information..

Your Second Query is on node_revision table which stores node revisions if you track node revisions which are nothing but updates...

db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

It's discouraged in Drupal to run queries directly on Drupal for certain actions.. For example in your case you are updating a node and setting status to published.. Drupal works using concept of hooks which are events and actions.. If any module is implementing any node related hooks they won't fire if you run queries directly.. So it's discouraged..

Right way of doing above action is using node_save api function in Drupal 7...

$node = node_load($nid);
$node->status = 1;
node_save($node);


Easiest way to export specific user-generated content? I'm using Drupal 6.x on a site that has many users. There are about 20 "Pro" users that function as authors. I need to export an individual author's posts in order to later import them into WordPress. What might be the easiest way to accomplish this?

Bonus! I also need to export the comments associated with each article, AND change all comment authors to "Anonymous." Should I do that after the export through SQL, or is there an easier way?

I am looking into the Views module, but it's pretty far over my head... I would certainly prefer a simpler solution if that is possible.

Thanks for the help in advance!

Views module is the only solution which makes your task very easy.

1.Simply create a view and add the necessary fields you want to export.

2.Add a display (data export).

3.In DATA EXPORT SETTINGS name your path with .csv extension example data.csv

Finally call the path on your browser. That's it

Another difficult way is to write queries and then create a php code to export the result to csv


Display node add form in popup I want to display node add form of a particular content type in a pop-up for anonymous users too. There are posts related to displaying a node content in pop-up but not about node add form.

I have a .tpl for a calendar display view. Now when anyone click on a particular div of the table I need to open a pop-up of node add form. So I need to add the <a> anchor tag in the tpl file.

How to achieve this? Is there a way to call the node add form as a pop-up in jquery?

First, I would say dont put this logic in a .tpl if you can put it somewhere else, for maintainability.

Second, as with many drupal solutions, there is more than one way and they differ in some aspects.  Let me try a few for you:

Solution A: https://www.drupal.org/project/colorbox  This adds a checkbox to the views field controls that says "Open link in Colorbox", and you use the Output as a Link controls to make this link point to /node/add.  Verify necessary permissions are set.

Solution B: Ctools modal link conversion.  In your calendar view add a nid field and use the 'Rewrite Field' options to replace it's value with your Create anchor tag.  Make sure this tag has the class "ctools-use-modal".  The reason for doing this so early is that links tagged with that class, when passed through the render process, get converted into a modal link.  Since this is on a calendar display, I am guessing that you are wanting people to make events for the calendar, and it would be really cool to have the event creation form pre-populate with the day they clicked?  Look at https://www.drupal.org/project/prepopulate and alter your anchor path to include the token from the date field that is already in your view.  Now the hard part, you will need to write a hook, so you will need a custom module.  I havent tried https://www.drupal.org/node/1312770 but it looks like it can make a skeleton for you.

You will need to implement this:

function hook_views_pre_build(&$view) {
  if ($view->name == [your_view_here]) {
    $current = $view->current_display;
    // Include the CTools tools that we need.
    ctools_include('ajax');
    ctools_include('modal');
    // Add CTools' javascript to the page.
    ctools_modal_add_js();
  }
}

That will make sure the view is processed by ctools looking for modal pop-ups.  I just used this the other month in a slightly more complicated use case, where path in the view is a custom registered callback and anonymous user gets a sign-up form in modal, and logged in user gets the requested resource.  Using what I have explained above, you should have a site where everybody gets the modal.  Make sure you have the appropriate Node Create permissions checked.

Solution C: There is an Overlay module that ships with Drupal 7, has been in there from the begining.  This is less popular than colorbox and ctools, and bit more limited.  Enable the module, give anon user permission to use it, and add "#overlay=" to the beginning of your link path in the view.  I dont recall at the moment if they solved some security issue involved with anonymous access to this module, so I caution against using it.  I am really only including it here as an example of how many solutions are available in drupal.

Good luck, and please do say how this worked for you.


Add a custom field to a quiz I've got a quiz. There is a content type to create a question. I've added a textfield to it (which will show a link to where the user can find the answer).

When I look at the question itself the textfield has been added and is being displayed on the screen. But when the question is part of the quiz, the textfield isn't there anymore (not on the screen, nor in the code).

Who can help me?

Maybe I need to add some kind of hook to the Quiz module but I don't know how hooks/custom modules work.

Thanks in advance.

There are probably many ways doing this. I'm still new as well, so go easy on me.

I would suggest you to create a taxonomy quiz. Each list item of quiz would be your question. Then for the content type answer, have a field named question and select term reference, choose select list as the widget type. That way, when a user create a new content answer and refer to one of the question from taxonomy quiz, you can just click on the question and it will give you a list of answer.

Other ways would be using Node Reference, but I couldn't get my mind around how to refer back to the question itself, maybe Relation would do the trick.

But try my first suggestion first.


How can I create a user list hierarchical select exposed filter? When I create a user view, I don't see the option for having hierarchical select on the exposed filters. I have the hierarchical data saved using hierarchical select already. Simple hierarchical select doesn't have the option too.

How can I create a user list hierarchical select exposed filter?

Hierarchical Select for Drupal 7 does not have Views support.  At this point, the HS has not been actively maintained in more than a year so it is unlikely to expect this to be added soon, if at all.  There is an issue on porting the D6 functionality to D7.

If using Simple Hierarchical Select, which only works on taxonomy terms, you can follow the instructions on the module's page:

  add a new filter using the field set-up as "Simple hierarchical select" or use "Content: Has taxonomy terms (with depth; Simple
  hierarchical select)" as a new filter
  use "Simple hierarchical select" as selection type
  select "Expose this filter to visitors, to allow them to change it"
  enjoy ;)


How to get the View Object from ViewsBlock? I'm loading a variable list of blocks. In some cases these blocks are a views_block type. When I load a views_block, the viewsblockbase provides the protected View object, but does not provide a method to retrieve it.

How would I go about retrieving the full view object from a views_block?

I considered a ViewsBlock::Create() approach however this would be redundant which Im trying to avoid. Likewise, I have the view_id and display_id but would rather not Views::GetView() when the object is already sitting right there in the loaded block.

snippet

<?php

public function buildDashboard() {
  // $block_instance = new DashboardBlockManager;
  $block_instance = \Drupal::service('plugin.manager.block');
  $blocks = $this->getBlocks();
  foreach ($blocks as $region => $region_blocks) {
    foreach ($region_blocks as $index => $block_id) {

      //$block_id example views_block:dashboard_tasks_by_assignee-block_1

      $load_block = $block_instance->createInstance($block_id);

      $title = $load_block->label();
      $build_block = $load_block->build();
      $build_block['#block_title'] = $title;

      //check the plugin type
      $definition = $load_block->getPluginDefinition();

      if ($definition['id'] == 'views_block') {
        //cant do this
          $view = $load_block->view;
      }
}

I think there is no way to get the the view Object directly it's protected property and there is no method to get it:
From ViewsBlockBase

  /**
     * The View executable object.
     *
     * @var \Drupal\views\ViewExecutable
     */
    protected $view;

But there is a way first get the view id from the DerivativeId and then load the view here is a code snippet below:

  use Drupal\views\ViewExecutable;

  $blockManager = \Drupal::service('plugin.manager.block');
  $contextRepository = \Drupal::service('context.repository');
  // Get blocks definition.
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());
  $views_blocks = [];
  foreach ($definitions as $id => $definition) {
    $id_type = explode(':', $id);
    if ($id_type[0] == 'views_block') {
      /** @var \Drupal\views\Plugin\Block\ViewsBlock $viewsBlock */
      $viewsBlock = $blockManager->createInstance($id);
      $derivativeId = $viewsBlock->getDerivativeId();
      $derivativeId_exploded = explode('-', $derivativeId);
      $view_id = $derivativeId_exploded[0];
      $view = Views::getView($view_id);
      $views_blocks[] = $view;
    }
  }

I hope that helps.


select nodes title start with charachter I want to have query with EntityFieldQuery that return me nodes with title start with A or B but has not obvious method to use or in property condition,
I dont want use db_select or db_query.
in this link not comes like but it work ,but  If I want use REGEX operator it return me error.

  $query=new EntityFieldQuery();
        $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'product_display')
        ->propertyCondition('status', 1);
$query->propertyCondition('title', '^(B|A)','REGEX');

There is no database agnostic support for regex in EntityFieldQuery. The documentation in EntityFieldQuery::propertyConditon lists the available operators. As mentioned by Clive, this list is not complete. Apparently you can use any operator that is supported by your database backend.

As an alternative that should be supported across different database backends, you could build multiple queries using the STARTS_WITH operator and then merge the results.

Or you write a custom query using db_query. Or use db_select with or-linked conditions.


How to have new activity count above any view? I have seen on your website, when there is a new question posted, the list shows a new activity button with a count above the list. How can I do that in Drupal with any view?

I am interested in showing such a thing with Statuses. There is an option in statuses settings to show a refresh button below the status stream when there is a new activity, but I want to show it above like on stackexchange and with a count.

Have a look at the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice.
Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".
Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.


How to display permanent arrows on the left/right of a carousel when using the Flexslider module? I'm using the Flexslider module with Views and have a nice carousel running on my Drupal site.

The problem is that the design calls for permanent arrows on the left/right and the module only shows them when you hover over the carousel.

Is there an easy way to do this?

The following CSS will get you started:

.flexslider .flex-direction-nav a.flex-prev,
.flexslider .flex-direction-nav a.flex-next {
    display: block;
    opacity: 1;
}
.flexslider .flex-direction-nav a.flex-prev {
    left: 0;
}
.flexslider .flex-direction-nav a.flex-next {
    right: 0;
}

This will also help:

.flexslider .flex-direction-nav a:before {
    font-family: serif;
    content: "";
}


How to translate the description metatag for a view I have a multilingual site based on drupal 7 with Internationalization i18n and Metatags modules.
I made a multilingual view and it works fine, I could translate all entities except the view-description (and of course the metatag description).
I would like to have for each language a different meta tag description of the view.

As I can read in this issue, it seems there is still no solution.

Is there any workaround?
Thank you for replying.

You could add something in the html.tpl.php along these lines:

  <?php
  if((function_exists('views_get_page_view') && views_get_page_view()) && ($language->language == 'fr')){ ?>
      ...Your metatag here...
  <?php
  }elseif((function_exists('views_get_page_view') && views_get_page_view()) && ($language->language == 'de')){ ?>
      ...Your metatag here...
  <?php } ?>

  views_get_page_view() finds out what, if any, page view is currently
  in use. If it returns NULL, then the current page is not a views'
  page.

Source

This line of code may come in handy as well, to figure out which view:

$view = views_get_page_view();

Source

Is this enough to help you on the way?


Show specific url path in admin theme I want to edit in admin theme some editing pages like "entityform/*/edit". How can I do that?

I find what exactly I want.

Administration theme module is great for using admin theme selected URL path.


Allowing a user to choose which image style they want for a single uploaded image I have a views list showing a set of property's displaying address, image, description and price in a horizontal manner, each line is a new listing for a property.

the user simply uploads an image and clicks save. however I have recently been asked to allow for the user to again upload a single image, only this time select an image style that contains an an overlay or watermark image on top of the uploaded image.

I have managed to create the image styles with a watermark effect for each overlay image they requested such as "Available now", "Under Offer" ect. But I have absolutely no idea how I provide a choice for the user to select one of these image styles.

so to clarify the user would like to upload an image and then select a pre made image style under that uploaded image to apply a watermark over the top. I am having trouble providing a choice for the user to select. everything else has been achieved.

I hope this makes sense I have tried to be as detailed as i can and hope there is a solution to this. Thank you for everyone's time.

You can add an additional field to your content type that stores the values of the image style presets on your site. This will allow them to select which image style they want once they've uploaded an image.

You'll need to write a small custom module to pull the existing image style presets from the database and programatically populate the allowed values of the in your new select field.

You can create a custom node or views template and use the value of the image style field to display the uploaded image with the selected image style.


OpenCalais is not autotagging content I'm using the following modules versions on Drupal 7.

OpenCalais   7.x-1.0-alpha2+22-dev
Feeds    7.x-2.0-alpha8

I have a Feed that is creating my content correctly into the Feed Item content type. When I click on the edit tab, I can see that OpenCalais is suggesting tags.

But it does not 'autotag' the content and requires me to actually click the tag before it gets added to the autocomplete textbox. This kind of defeats the purpose. According to this http://www.lullabot.com/blog/article/introduction-calais, it is supposed to do this out of the box. the only different I see is that this is for Drupal 7. I have also installed RDFx just in case it had that requirement for the D7 version.

How can I get OpenCalais to input the suggested tag into the field automatically?

I believe you did not configure the Calais module correctly.

Go to admin/settings/calais/calais-node, expand the fieldset of your content type and pick either "Apply all suggested terms on every update" or "Apply all suggested terms on creation ONLY" from "Calais Processing:" field.
This way, the tags will be applied automatically.


EntityFieldQuery - ordering by multiplication of two fields I need to order my news by their importance value (1, 2 or 3) which is in the field field_importance and the date they are published. So I would need to order my news by this calculation: created * field_importance and I haven't figured out a way to do it with EntityFieldQuery. If someone knows a way to do it without EntityFieldQuery, that's equally good. This is my code so far:

$query->entityCondition('entity_type', 'node')
      ->propertyCondition('status', 1)
      ->propertyCondition('type', array('news'))
      ->propertyOrderBy('created', 'DESC');

If you don't have to pull in a whole bunch of linked entity stuff, just run a regular db_query() joining your "importance" field table to your node table.

$query = "SELECT nid, (created * field_importance_value) AS weight
FROM node n
JOIN field_data_field_importance f ON f.entity_id = n.nid
WHERE type = 'news'
AND status = 1
ORDER BY weight DESC";
$result = db_query($query);
// Add foreach loop here...

I'm just guessing the importance table name and field name from your OP.


Save Link field in custom form I'm brand new at making custom forms and I'm having trouble getting the link field to save to the database.

The text body field saves fine but the link field object defined below it does not. I'm sure that this is an easy fix but I haven't been able to find proper documentation on adding the link field to custom forms.

Thanks in advance.

    /**
* Implements hook_block_configure().
*/

function My_Module_block_configure($delta='') {
$form = array();

switch($delta) {
case 'my_module' :
    // Text field form element
    $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
     );

     //link field
    $form['link'] = array(
        '#type' => 'link_field',
        '#size' => 20,
        '#field_name' => 'link',
    );

    break;
}
return $form;
}

/**
* Implements hook_block_save().
*/
function My_Module_block_save($delta = '', $edit = array()) {
    switch($delta) {
    case 'my_module' :
        // Saving the WYSIWYG text
        variable_set('text_variable', $edit['text_body']['value']);
        variable_set('link_variable', $edit['link']['value']);

        break;
    }
}

I get success with this. It needs to be improved though, especially the '#language' bit. What I found to be important was to wrap the link field in a container and set '#tree' to true to group it under its key. And the link field is a multi-value field with a link title and url, so you have to take care of that.

function MYMODULE_block_configure($delta='') {
  $form = array();

  switch($delta) {
    case 'my_module' :
      // Text field form element
      $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
      );

      //link field
      $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
      );
      $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und', // how to fix this??
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
          'title' => variable_get('link_title', ''),
          'url' => variable_get('link_url', ''),
        ),
      );
      break;
  }
  return $form;
}

/**
 * Implements hook_block_save().
 */
function MYMODULE_block_save($delta = '', $edit = array()) {
  switch($delta) {
    case 'my_module' :
      // Saving the WYSIWYG text
      variable_set('text_variable', $edit['text_body']['value']);
      variable_set('link_title', $edit['link_container']['link']['title']);
      variable_set('link_url', $edit['link_container']['link']['url']);
      break;
  }
}


How can I update existing config from a custom module's config/install yamls? I added some config yml files to my module's config/install directory so that it is installed directly when installing my module, it works well only if there isn't a config file with the same name installed already and only if it's the first install.
  So my question is there a way to update the config files already installed with my module's config file, and delete them when uninstalling the module ?

A module install should not update config. If you want to update existing config, your module should implement hook_update_N() (see docs) instead.

However, you could add a dependencies: enforced section to your YML config files. This will remove your existing config on module uninstall, and install the newest config on module reinstall. This way you can "emulate" a simple update mechanism for your own, private custom module. See doc for enforced config dependencies


Can't delete Relation module I'm trying to disable or delete the Relation module (and about to pull what's left of my hair out).

Relation and Relation Endpoints Field are checked, but greyed out so I can't uncheck them. I don't see anything that's dependant on these, and I don't see anything in the Field List related to this module.

All of the other Relation modules (Relation Dummy Fields, etc) have been uninstalled and I've run cron 40 or 50 times as well as

DELETE FROM field_config WHERE field_config.deleted = 1;

which someone suggested on another post on the topic, but no success.

The reason I'm trying to delete Relation is that I'm trying to update Drupal core from 7.28 to 7.36 (long story) and getting an unresolved dependency as Relation isn't compatible with 7.28.  Someone suggested I disable the module before doing the update, and I'm trying to do that.  However, I'm wondering if per-chance this problem has to do with the incompatibility.

I don't seem to be able to move forward or back and I'm not sure what to try next.

Currently:
Drupal 7.28
Relation 7.x-1.0-rc7

One thing to check is if there are still fields using this field? Take a look at admin/reports/fields to see if there is anything using the relation fields.

Once you are certain...

If you are certain that there are no dependencies relying on this module, then you can open phpmyadmin, and look at the system table.

Look for /sites/all/modules/relation.info and change the status from "1" to "0". Do the same for relation endpoints as well.

This will disable the module manually.

I would recommend doing a good backup, or even better, recreate your environment away from your production site and test there.


How do I redirect anonymous users? I let anonymous users publish content on my site, but the content must be reviewed before to be  published. The following is my ways to do that:

Using CCK, I created a content type and unchecked the publish option.
I gave the permission to create/edit/delete the content type to anonymous users.

This allows anonymous users to publish the content, but when they save the node they get an "Access denied" error.

What's the difference between what I do and using Workflow module?
Is there a way to redirect the page, and make the anonymous users see the node they created?

There is also the view unpublished module which will allow anon users to view the unpublished node they just completed.


Enable modules across platforms using Features/Drush I am wondering, could this be automated.

I download and enable contrib modules on @dev
I push files on @live (including new modules)
via Features/Drush I tell @live to enable new modules, so servers are in sync.

I do some needed disabling/enabling of dev modules when doing sql-sync to @dev, but this is case when I install new modules on @dev and want them on @live automagically when I commit.

I could, of course, do drush @live en [modulename] for each module I installed on dev.

Yes, this could be automated. I'd suggest the missing component is git or possibly another source control tool, so you can create commits that represent complete sets of configuration changes.

(I see you mention commit in your question so presumably you already use git).


Where is the class "placeholder" defined? According to the function:

function drupal_placeholder($text) {
  return '' . check_plain($text) . '';
}

It would return the HTML code with class "placecholder".
I had searched the word "placeholder" in the drupal 7 project about 4,800 files. I expected to find the default CSS definition of class placeholder e.g. em.placeholder{} or .placehoder{}. But I can't.

I can only find some files with html ID attribute #placeholder{} was defined.

Some of the files:
 drupal/modules/color/color-rtl.css
 drupal/modules/color/color.css
 drupal/sites/all/module/ctools.css.stylizer.css

Because I want to modify class with my style globally. Please advise if any default definition of class placeholder in drupal 7.

The only uses of the placeholder class in core are (filename, followed by line number, follby the line):

modules/dashboard/dashboard.js:35:        if ($('.placeholder', this).length == 0) {
modules/dashboard/dashboard.js:38:        $('.placeholder', this).html(empty_text);
modules/dashboard/dashboard.js:41:        $('.placeholder', this).remove();
modules/system/system.admin.css:264:.exposed-filters .current-filters .placeholder {

and also a few in jquery.ui that you can ignore:

misc/ui/jquery.ui.draggable.min.js:40
misc/ui/jquery.ui.sortable.min.js:26
misc/ui/jquery.ui.sortable.min.js:27
misc/ui/jquery.ui.sortable.min.js:29
misc/ui/jquery.ui.sortable.min.js:39
misc/ui/jquery.ui.sortable.min.js:40
misc/ui/jquery.ui.sortable.min.js:43
misc/ui/jquery.ui.sortable.min.js:55
misc/ui/jquery.ui.sortable.min.js:56
misc/ui/jquery.ui.sortable.min.js:59
misc/ui/jquery.ui.sortable.min.js:60

You can safely ignore all this and just implement your own css for the .placeholder class in your theme.


how to get list of all route in routeProvider? I have:

class MyRouteProvider extends DefaultHtmlRouteProvider {
    public function getRoutes(EntityTypeInterface $entity_type) {
        $test = parent::getRoutes($entity_type); // TODO: Change the autogenerated stub
        // how do i get list of route that i have in this method?
    }
}

how do i get list of route that i have in getRoutes method?

what i'm trying to do here is: I like to search a particular route (based on $entity type) that created by my_entitiy and modify it.

Not really sure what you are aiming for, but you have it already as the getRoutes() method works with a Symfony RouteCollection collection

class MyRouteProvider extends DefaultHtmlRouteProvider {
  public function getRoutes(EntityTypeInterface $entity_type) {
    /** @var \Symfony\Component\Routing\RouteCollection */
    $collection = parent::getRoutes($entity_type);
    /** @var \Symfony\Component\Routing\Route[] */
    $routes = $collection->all();

    return $collection;
  }
}

If sounds like, though, you want to implement a RouteSubscriber to alter the route.  There are a bunch of these in core to use as examples.  And you don't need to get all of the routes, and then search through them.  You can just use the route collection and get the route that you need.  The route subscriber defined by the Node module is probably the simplest example:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // As nodes are the primary type of content, the node listing should be
    // easily available. In order to do that, override admin/content to show
    // a node listing instead of the path's child links.
    $route = $collection->get('system.admin_content');
    if ($route) {
      $route->setDefaults([
        '_title' => 'Content',
        '_entity_list' => 'node',
      ]);
      $route->setRequirements([
        '_permission' => 'access content overview',
      ]);
    }
  }

}

Note that is just does a $collection->get() to find a particular route, and then modifies it.


How do I programmatically save "2019-11-04 07:30:00+01"? I have "2019-11-04 07:30:00+01" as datetime value. I am not getting how to handle  the "+1" part in a Drupal 8 date field.

I am using this code, but it's not giving me any value.

use Drupal\Core\Datetime;

$userTimezone = new DateTimeZone(drupal_get_user_timezone());
$gmtTimezone = new DateTimeZone('GMT');
$myDateTime = new DateTime($item['start_date'], $gmtTimezone);
print_r($myDateTime);
die;

There is no DateTime class in Drupal\Core\Datetime you should use DrupalDateTime class instead try with.

    use Drupal\Core\Datetime\DrupalDateTime;
   //$userTimezone = new DateTimeZone(drupal_get_user_timezone());
    $gmtTimezone = new DateTimeZone('GMT');
    $myDateTime = new DrupalDateTime($item['start_date'], $gmtTimezone);
    $dateTime = $myDateTime->getPhpDateTime();


Strip caption from image using css I am adding a caption to images by using the following module: https://www.drupal.org/project/image_field_caption

For the front page I am using views. There, I also show the images but I do NOT want to show the captions. I guess the captions can be stripped away by using CSS...

How is that done? I do not know CSS and the "interaction" of Drupal and CSS very well.

My questions:
1. Where do I have to add the CSS code?
2. What do I have to write there?
3. How is this CSS snipped included in views to get the effect of stripping caption away?

Thanks!

if this is strictly a css question, I believe it's off-topic here, but...

I've never worked with that module, so this may or may not be an option:

If you output your View as a table, you can modify how fields are represented. Unless the module overwrites the default image formatter, you should be able to choose the Image formatter instead for that field and bypass the module.


Alter field values via module How can I update field values of all nodes via module?

I have a hook_cron function inside MYMODULE.module that updates field_popularity_score field of all nodes, of a particular type, so that I can use Views to sort the nodes by field_popularity_score.

In Drupal 7, you should use a queue for such type of operations. In short, what happens is the following:

An item is added to the queue
An item in the queue is processed, and removed

In the case of cron tasks, there is a hook (hook_cron_queue_info()) that tells Drupal which queues need to be handled when drupal_cron_run() is executed, and which function handles the items contained in the queue.

function mymodule_cron_queue_info() {
  $queues['mymodule_update_node_popularity'] = array(
    'worker callback' => 'mymodule_update_node_popularity',
    'time' => 20,
  );

  return $queues;
}

For how to populate that queue, I see two possible cases:

The field is updated for every node that is updated
The field is updated for every node, once
The field is updated for every node that is created, or updated

In all the cases, the following function should be used, together the hook I previously shown.

function mymodule_update_node_popularity($nid) {
  $node = node_load($nid);

  // Calculate the new score for the node.

  $node->field_popularity_score[LANGUAGE_NONE][0]['value'] = $new_value;
  // Replace the previous line with the following one, if the value should be different for each language.
  // $node->field_popularity_score[field_language('node', $node, 'field_popularity_score')][0]['value'] = $new_value;

  node_save($node);
}

The parameter received from the worker callback (in this case, mymodule_update_node_popularity()) is the one that is passed to $queue->createItem().

In the first case, I would implement the following code.

function mymodule_node_update($node) {
  if ($node->type == 'content type to handle') {
    $queue = DrupalQueue::get('mymodule_update_node_popularity');
    $queue->createItem($node->nid);
  }
}

In the second case, I would implement the following code.

function mymodule_cron() {
  $args = array(
    ':type' => 'content type to check',
    ':created' => variable_get('mymodule_last_checked', 0),
  );
  $queue = DrupalQueue::get('mymodule_update_node_popularity');

  $nodes_result = db_query('SELECT nid, created FROM {node} WHERE type = :type AND created >= :created ORDER BY created ASC', $args);
  foreach ($nodes_result as $node) {
    $queue->createItem($node->nid);
    variable_set('mymodule_last_checked', $node->created);
  }
}

The reason I am not using "SELECT nid FROM {node} WHERE type = :type" as query is that such query would cause mymodule_cron() to always add the same nodes to the queue (except for those nodes that have been deleted). mymodule_cron() needs a way to filter out the nodes that have been already handled, and the query I wrote is a way to achieve that.
The value passed to $queue->createItem() can also be an array, or an object, and that value would be passed to the worker callback.

In the third case, I would use the following code.

function mymodule_cron() {
  $args = array(
    ':type' => 'content type to check',
    ':changed' => variable_get('mymodule_last_checked', 0),
  );
  $queue = DrupalQueue::get('mymodule_update_node_popularity');

  $nodes_result = db_query('SELECT nid, changed FROM {node} WHERE type = :type AND changed >= :changed ORDER BY changed ASC', $args);
  foreach ($nodes_result as $node) {
    $queue->createItem($node->nid);
    variable_set('mymodule_last_checked', $node->changed);
  }
}

This code works because, when a node is first created, both $node->created, and $node->changed are set to the same value.

In the first case, when you need to update the field value when the node is updated, you could implement hook_field_presave(), instead of using a Drupal queue.


Exposed Filters View is not functional with Anonymous Users I created a Filtering Search with Multiple Exposed Filters. It all has been working fine except one thing; when I logout as an admin and use the site as an anonymous user, exposed filters don't work.

The screenshot of my exposed filters form is below:-

In a functional scenario, When I click on any value, let's say EMEA, the form auto-sumbits and show hierarchical values in all the below filters and show the data on the right side.

As an example, When I click EMEA, the form auto-submits, and all the offices from EMEA appear in the lower filter of Filter by Office and results are shown.

The problem is that all the filters, data and values are shown for anonymous users but not auto-submitting takes place. It seems it just refreshes the page when I click on any filter.

Any idea?

Best.

P.S

I used two modules within it:-

Better Exposed Filters (for making filters more readable)
Views Hacks (to use Views Selective Exposed Filters for showing hierarchy within Filters)

I got it.

I had LDAP module enabled and that was de-authorizing the access. Had to deactivate it.

Thanks a lot guys.


Add value to every user in data field I'd like to do simple thing, but because of drupal serialized data field don't know how to. I'd like to set for every user a variable in "data" field, I do it manually when user edits its profile, like this:

$edit['data']['profile_bg_active'] = 1;

I want to do it now for all users, so the "profile_bg_active" exists in every user data field.

The code I am using is the following one.

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->execute();

foreach ($updateAllDudes as $dude) {
  $existingUser = user_load($dude->uid);
  $edit = array();
  $edit['data']['profile_bg_active'] = 1;
  user_save($existingUser, $edit);
}

I get the following error in the log:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, name, pass, mail, theme, signature, signature_format, created, access, login, status, timezone, language, picture, init, data)`

It seems it is creating new users instead of updating the existing ones.

This is because you're not filtering the users when you grab them using db_select. This will also grab the "Anonymous" user (uid 0). When you try to save that user, this error happens most likely. Putting a simple if(!empty($dude->uid)) within your foreach loop should fix this issue. Or excluding uid 0 from your db_select query using the NOT EQUALS condition like so:

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', 0, '<>')

Or by using the NOT IN condition:

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', array(0), 'NOT IN')

See here

  if you need to edit all users (I am setting a default value for a custom field), you need to strip uid=0 from the list and deal with it as a special case.