Spam registrations even after adding domain to Mollom blacklist I have a problem with spambots from itregi.com and drupaler.org that registers accounts on my clients Drupal site. I have Spamicide and Mollom installed and I have also added the domains to Molloms blacklist in the following format:
Author e-mail   contains    itregi.com

But they still get accounts with these domains as email.
I don't know what to do more or if I am using the blacklist wrong? Any suggestions?

Try using Honeypot, it's a module specially designed for spambot filtering...


Where and when in the User login workflow is the last Access time timestamp set? I am trying to understand when exactly the last access time is set in the Drupal user login workflow.  I did notice that the following method is probably what is used to set the timestamp

  public function setLastLoginTime($timestamp) {
    $this->get('login')->value = $timestamp;
    return $this;
  }

However, I could only find the declaration but not the method call in the codebase and it has proven difficult to track it. It seems quite surprising it is not called anywhere. I am thinking that there should be a direct write to the field 'access'.

P.S The reason I am trying to get the value is to determine what all nodes are created after the user had last accessed the site.

Simply scan the codebase for setLastLoginTime and you'll see that there's actually only one single place where this function gets called. And that is user_login_finalize.

/**
 * Finalizes the login process and logs in a user.
 *
 * The function logs in the user, records a watchdog message about the new
 * session, saves the login timestamp, calls hook_user_login(), and generates a
 * new session.
 *
 * The current user is replaced with the passed in account.
 *
 * @param \Drupal\user\UserInterface $account
 *   The account to log in.
 *
 * @see hook_user_login()
 */
function user_login_finalize(UserInterface $account) {

And when does user_login_finalize get called? Scan the codebase again. And you'll see that there are some few places only. For example in the submit handler of the user login form, in the submit handler of the user register form, or for example also in the install_finished handler when you after a successful interactive site installation (in the browser) get logged in as user 1.

Following the input from @4k4 there must be differentiated between the last login time and the last access time. Both are base fields of the user entity. The login time gets stored on every login finalize (see above) and the access time (the one you can see in the users View in the LAST ACCESS column at /admin/people) gets renewed every 180 seconds. This happens in an event subscriber which gets triggered on every request/response cycle – the UserRequestSubscriber.

The last access time then can be retrieved from User::getLastAccessedTime. I maintain a small module to calculate online, absent and offline states of a user with exactly that method: https://git.drupalcode.org/project/user_online_status/-/blob/8.x-1.0/src/StatusService.php#L83.


How do I pass the language through ajax request I have an ajax function in the javascript file that calls for the data in a custom module. But the problem is it always get the data for the default language. In my case it is 'en'. How do I get the data for another language.

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

This method always returns the default language for ajax requests. How do I get the data for the language that is mentioned in the url.

ajax:

$.ajax({
    url: "/gallery/view",
    method :'POST',
    data: {
        category : category,
        propertyId : propertyId,
        isCorporate : isCorporate,
        brandId : brandId,
    },
    success: function(result){}
});

routing :

eme_gallery.view:
  path: '/gallery/view'
  defaults:
      _controller: 'Drupal\eme_gallery\Controller\ViewGalleryImage::view'
      _title: 'Image Gallery'
  requirements:
      _permission: 'access content'

You will need to change the URL of your AJAX call to include the language prefix. So this:

url: "/gallery/view",

Will be this:

url: "/ja/gallery/view",


how to extend FormBuilder::processForm from multiple API endpoints in one class I'm trying to consolidate my form processing by entity_type, without rebuilding the forms (just using the default forms provided by Drupal.

I have dynamic routes pointing to a _controller::method. I've tried:

A. \Drupal::service('entity.form_builder')->getForm($group_content, 'edit', $data) but this just returns a render array, no instance.
B. \Drupal::formBuilder()->getForm('\Drupal\group\Entity\Form\GroupContentForm') but this is the wrong class path and i can't figure out how I could reference any entity:bundle:id by any pattern (i've tried many)
C. Changed the route to use _form or _entity_form extending FormBase (instead of a controller), but it seems these require the buildForm method to defined the form's full field list (which defeats the purpose of my question).

What is the best approach to expose edit/add/delete process handlers for multiple bundles / entity_type in a single class?

A. EntityFormBulder::getForm is just a shortcut for instantiating the form object, injecting the entity and building the render array. You can split this up:

  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state_additions = []) {
    $form_object = $this->entityTypeManager->getFormObject($entity->getEntityTypeId(), $operation);
    $form_object->setEntity($entity);

    $form_state = (new FormState())->setFormState($form_state_additions);
    return $this->formBuilder->buildForm($form_object, $form_state);
  }

B. You have to inject the entity before you can build an entity form, see the steps above.

C. _entity_form is for integrating an entity form in a route, then the route parameter is upcasted and injected into the form automatically, see How to Inject entity object in EntityForm

The best approach is C. (standard pattern) and refactor the OOP code.

BTW if you don't find a OOP solution or if it is too complicated then you could simply add a custom process callback to $form['#process'] in a form alter hook to all or specific entity forms.


Creating a Dropdown menu in Drupal 7 My question is how do we get the menu in drop down structure.
i.e

I used following:

<?php print theme('links', array('links' => $main_menu)); ?>

but this only produces top level menu even if we have sub menus in menu management.

horizontal or vertical nested menus: Nice Menus or Superfish

simple vertical nested menus: Menu Block


How can I strip out default markup for a text field? I have created text fields for first name and last name (which i need as separate fields so i can sort by last name when needed) but the default markup is so cumbersome! they each are nested in 3 divs, and all I want to do is display as a typical manner, ie. Firstname Lastname

How can I strip out the default markup for these 2 fields only? creating a field override template doesn't seem like a good idea, or is it?

Several ways to skin this cat. You can use a custom tpl.php as suggested, or, you can also explore some contrib modules such as display suite or fences.


How to add the search form in Bootstrap theme? I am trying to set the search form with submit button in the Navbar as shown in the following image(Following image I have taken from the Bootstrap tutorial page).

Now, When we install the default Bootstrap theme from drupal.org it will be ended up like as shown in following image.

Now, if I simply move that block to the Navigation bar, it will end
up as shown in following image, which is not a solution for this.

So, I dig out on the bootstrap tutorial
page and found the
following code.

So, I can paste that code in the page.tpl.php and can achieve as
shown in following image, BUT it will not search anything, as it is
just a plain HTML code.

How can I achieve that? If CSS is the answer, for now I do not want to go with that. As IMHO, since this display of search form is described as a default on the bootstrap tutorial and in every theme demo display pages, So, there should be some way to enable that, or some way to place that.

Any suggestion or direction? Thanks.

After some search I figure out the following solution, it is working, But the issue is it is applying to search_block_form also, might be function lsubtheme_bootstrap_search_form_wrapper($variables) is the reason, which is getting applied everywhere. Might be giving False positive result.

PLEASE anybody have any suggestion, how to imptove this, I am trying will update.

Codes in template.php

function lsubtheme_preprocess_page(&$variables){
  $search_form = drupal_get_form('search_form');
  $search_box = drupal_render($search_form);
  $variables['search_box'] = $search_box;
}

/*
 *  Form alter to add missing bootstrap classes and role to search form.
 */

function lsubtheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#attributes']['class'][] = 'navbar-form navbar-left';
    $form['#attributes']['role'][] = 'search';
  }
}

function lsubtheme_bootstrap_search_form_wrapper($variables) {

  $output = '
';
  $output .= $variables['element']['#children'];
  $output .= '
';
  $output .= '<button type="submit" class="btn btn-default">Search</button>';
  $output .= '
';
  $output .= '
';
  return $output;
}

Code in page.tpl.php

 <?php print $search_box; ?>


Hide formatting options from a CCK field in Drupal 6 I have a custom module in which I am using hook_form_alter to remove the formatting options/help text for the body and comment fields:-

function mymodule_form_alter(&$form, &$form_state, $form_id) {
// We don't want the format options displaying
if (isset($form['body_field']['format'])) {
    $form['body_field']['format']['#access'] = false;
}
if (isset($form['comment_filter']['format'])) {
    $form['comment_filter']['format']['#access'] = false;
}
}

This works fine. However, I also need to remove the same formatting options/help from a CCK field. I've tried to use the same technique but can't isolate where in $form the formatting options are being included. Is it not possible to removed them using the same method as above?

We want to remove this information as it is not relevant to the user as the WYSIWYG editor provides them with all the tools they need and nothing more. We don't want to hide these with CSS, they need removing from the output.

Found that this can be handled in the theme's template.php file:-

function phptemplate_filter_tips_more_info() {
return '';
}
function phptemplate_filter_tips($tips, $long = FALSE, $extra = '') {
return '';
}

Which then overrides all filter tips from forms.


Image upload in a node gives required error we have a node to which we upload many pictures. This time, after ~ 337 pictures all of the following pictures are marked as failure with an error but as message is just given "Field Bilder is required". Bilder (translates to images) is the field we already uploaded 300+ images.

In the recent Drupal log is no message concerning upload errors. Any clues what could cause this problem?

Most probably the upload is limited due to php settings. There is not only a setting for max upload per file, but also a max for a post.

On this page you can find how to solve in this link

If this doesn't work, there might be a setting for max_execution_time in php.ini, which cuts off the upload script if it takes too long.


Filter RelationQuery by relation_type I have some 2-point-relations called 'is_member_of' where the source endpoint is a person and the target endpoint is a group.

I like to list all of the members (without using a view).

In the code I build a relation query with the nid 1234 as target (last option = 1)

$query = relation_query('node',1234,1);
$results = $query->execute();
dpm($results);

This lists ALL relations to the nid 1234. I only want to have relations of the

relation_type='is_member_of'

Is there a fieldCondition which can do that?

Thanks.

A RelationQuery is just an EntityFieldQuery under the hood, and since relation_type is the bundle key of the relation entity type, both

$query = relation_query('node',1234,1);
$results = $query->entityCondition('bundle', 'is_member_of')->execute();

and

$query = relation_query('node',1234,1);
$results = $query->propertyCondition('relation_type', 'is_member_of')->execute();

should work.


add to cart in Commerce + Panels Where in the Panels "add content" list can I find the "add to cart" button?

So far I can only add it via node / node content =

but this prints node title + body text + add to cart as opposed to just add to cart - here is the node content panel with a cyan border:

How can I add just the "add to cart" button without the other stuff?

Thanks...

The "Add to Cart Form" is not available directly from Panels.  You need to create a view to load the Add to Cart Form and then display that view in the panel. When creating the view you have total control over what you want to display or not display.

Panels is a way to put other Drupal content constructs together, first you have to build the constructs to hold the content though...


How to use flags to pass variables to users? Backstory:
Ok, I have a site where users can post events, rate them, attend them (everyone can see who will attent) and such. Now I want to make it so you can add variables to users, which resembled what they did. for instance: User: Anon had a red jacket and was drunk.

Then I would like a list that is unique PER event with these variables which the users can add to their own profiles. (so everyone can see what they did/had at that specific event)

for instance:
List of events:
Color run, Jumping, Racing
"User goes to event "color run"
and there is a list with:
"what resembles you at this event:
-Drunk
-In a group
-Red jacket"

Then they select "drunk and red jacket" and submit/bookmark.

Now I want this to be saved to their profile so when they go to their own profile it will look like this:

profile>events>color run>

red jacket
drunk

and for a different event it could be that they chose something else and that would show up.
Any ideas how to make this reality?

I was thinking about using blocks but I have no clue how to make the multiple select part.

Consider using the Profile 2 module. Excerpt from its project page:

  Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields.

That project page contains a lot more interesting info, such as these Features which might help for addressing this question:

  Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those.
  Optionally, profile forms are shown during user account registration.
  Similar to the deprecated core profile module, fields may be configured to be private - thus visible only to the profile owner and administrators.
  By default the UI behaves similar to the deprecated core profile module, thus showing each profile type in each own tab below user//edit. Via the included "Profile pages" module profiles can be viewed and edited at their own page and get their own menu link, e.g. "My profile".
  Thanks to the foundational entity API the module integrates well with Rules as well as Features - thus profile types and the associated fields can be exported into feature modules. Once the Entity tokens module (part of the Entity API) is turned on, there are also token replacements available.
  You may use Views and/or the Search API to provide listings or searches for profiles.

Refer to its community documentation also for more details about this module.


How are user.tokens.inc and other similar files included? I notice that many core modules in Drupal 7 implement hook_token_info and hook_tokens in a hook.tokens.inc file, but I can't figure out how this file is included. Should I be doing the same with my own module? How can I be sure it will be loaded?

They do it by way of hook_hook_info():

Defines one or more hooks that are exposed by a module.
Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.

As luck would have it, the example from the docs shows exactly how the Token module does it:
function hook_hook_info() {
  $hooks['token_info'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens'] = array(
    'group' => 'tokens',
  );
  return $hooks;
}

Should I be doing the same with my own module?

Totally up to you - it certainly can't hurt, other modules that need to implement your hook will just have an extra option for storing the hooks. But if you don't, they can still implement your hooks in the .module file anyway.


Override tpl for custom menu page I have created a custom menu with hook menu booking/%/reschedule and where % is nid of bookings ( content type ), I want to override tpl file for this page in my theme. I tried with page--booking--%--reschedule.tpl.php but its not working.

Write this function in your template.php file, which is located in your theme (untested):

function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'booking' && $alias_parts[2] == 'reschedule') {
    $vars['theme_hook_suggestions'][] = 'page__bookingtemplate';
  }
}

Then you can create a new template file which is called page--bookingtemplate.tpl.php and after clearing the cache, it should work.

Credits to Clive for this post.


Views group different number of divs of a view by wrapping them I have a views block that is displayed in the content section of a node. What I need is wrapping the rows of the views block by divs. I have a list of 10 divs like so:

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Now I want to wrap the first 3 divs, div 4 to 8 and div 9 and 10 in a separate wrapper div like so.

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

Some Text here

How would I edit my views.tpl.php? Thanks!

Here is what worked for me. Mind that I only got it to work in an unformatted list format in views.

<?php
  $currIx = 1; // This will be our incremental index variable. Let's make it 1-based to maintin consistency with your example.
  $currWrapperIx = 1; // Wrapper counter
  $wasOpen = FALSE; // This variable will be used later as a flag to watch for properly closing wrapper divs.
?>

<?php if (!empty($title)): ?>
  <p class="<?php print $title ?>"><?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php switch ($currIx){
    // List the row indices that are supposed to begin a new wrapper.
    case 1:
    case 27:
      if($wasOpen == TRUE){ // Close current wrapper div before opening a new one.
        print "
\n";
        $wasOpen = FALSE;
        $currWrapperIx ++; // Increment the index for next wrapper's class.
      }
      // Open a new wrapper div
      print "
\n";
      $wasOpen = TRUE;
      break;

    default:
      // For other row indices do nothing.
    }
  ?>

  <div class="<?php print $id ?>"><?php print $row; ?>

  <?php $currIx ++; ?>
<?php endforeach; ?>

<?php
    // Close the last wrapper.
    if($wasOpen == TRUE){
      print "
\n";
      $wasOpen = FALSE;
    }
?>

Kudos go out to @Artur. Great support. Many thanks.


dropdown menu doesn't always show up in corporateclean I customized a theme from corporateclean and now, adding a drop down menu, the drop down doesn't show up on the rest of the page. The link is http://athleticedgefitness.com/contact where it shows the Links drop down; if you go to any other page, you see that the drop down doesn't show up. Why not? How can I fix this?

I am using Drupal 7.

Clearing the cache didn't do it!

I see, where the problem is. In the parent menu you also have to select "show as expanded" option to display the child menu in drop down or whatever configuration you have.

Steps (if you may need):

Goto Structure->Menus
Select the Menu and click list links
Find the parent menu and edit it
Inside that you will have option to choose "show as expanded", Check that
Clear the cache and you are good to go.


How to display a field twice in a view mode? I'd like to display a field_address in a view mode twice, once as the displayed address and once as a google maps directions link.  I suppose I could create one custom field formatter that outputs both components, but it seems excessive to create a formatter to display basically what should be two formatters.

Is there a way, say in hook_entity_view to display a field twice with two formatters?  Basically say $build['field_address_direction'] = $build['field_address'] and then change the formatter?

If you want to display a field twice in hook_ENTITY_TYPE_view(), you can get the field object from the first field and clone the field with a different field formatter and custom display settings.

For example to add the body a second time with the field formatter text_summary_or_trimmed and a custom trim length of 80:

function mymodule_node_view(&$build, $entity, $display, $view_mode) {
  if (isset($build['body']['#items'])) {
    $build['body_teaser'] = $build['body']['#items']->view([
      'type' => 'text_summary_or_trimmed',
      'settings' => [
        'trim_length' => 80,
      ],
    ]);
  }
}

You can clone the current settings this way:

$build['body']['#items']->getSettings();


How can I theme Media fields? I use Media + File Entity projects.
I have content type with field_media_picture (widget: Media file selector) which then connected with Media image file.
The Media Image file type has field_picname (text).
I've Managed display for the Media Image file type to display: image file and field_picname.
I've created field--field_media_picture.tpl.php:

<?php print render($items);?>

This code show image + field_picname. It's OK.

But how can I get these fields (image and field_picname) separately in PHP?
I want to theme these fields individually.

I've themed these fields through code:

<?php
hide($items[0]['field_picname']);
print render($items);
print render($items[0]['field_picname']);
?>

But I'm not sure the code is the best.


Getting field labels from the $node variable How can I get the labels of specific fields within a node, in Drupal 7?

The field for which I am interested has the following structure:

    [field_text_question1] => Array(
      [und] => Array(
        [0] => Array(
          [value] => Sales Intern
          [format] =>
          [safe_value] => Sales Intern
        )
      )
    )

The best way is to use field_info_instance($entity_type, $field_name, $bundle_name) to get information about specific instace of a field. The label of the field is contained in the array returned from that function.

 $info = field_info_instance('node','field_name','content_type_name');
 print $info['label'];


How Do I Replicate Computed Field Functionality In Drupal 8? I have a question regarding Computed Values in Drupal 8. I currently use Computed Fields in Drupal 7 to perform mathematical operations on certain fields and save that calculation in another field. I am attempting to recreate this functionality in a Drupal 8 install.

I recently saw an article that said Computed Fields would be depreciated by the functionality of Drupal 8 core. However, it is not clear to me how to recreate this in Drupal 8. Could someone explain how I take one integer field and multiply it by a percentage to get a decimal number?

I would appreciate any help provided.

Thanks,

Chris

There you are:

https://drupal.org/node/2112677

Basically you have to write a plugin and store your calculations in the getValue() function.


Default theme css wrongly included in another theme I have 2 themes enabled on a Drupal 7 installation. The have one css file each included in their .info files:

sites/all/themes/themeA/css/screen.css
sites/all/themes/themeB/css/screen.css

The default themeA is the default theme. Using hook_custom_theme, I'm setting the theme to themeB for a certain section of the website based on path. The theme changes successfully and the page renders using themeB when it should.

There is something strange that happens though and the css file from themeA loads as well, breaking parts of the page.

I am checking in hook_css_alter in themeB and there is no mention of themeA/css/screen.css. I am checking in hook_css_alter in themeA and it is never executed.

I have solved this by removing the file from themeA.info and adding it in themeA_css_alter(). I would prefer though and it would be interesting as well to find out why this happens, so that I can put back the the file inclusion where it should normally be.

Any insights?

The issue was happening on form pages that had CKEditor-enabled fields. The CKEditor module has a configuration option to specify additional CSS to load. By default, it loads the default theme's CSS. After changing this option, everything works as expected.


How do I set the page title from view result (same as the view result) I have set up a View that shows a random page from the site filtered according to node types and uses the Global : Random (asc) sort criteria. It displays only one result per page and a fresh page is shown every time the page is refreshed.

I want to set the view's page title to be same as the node displayed. I am doing this using javascript right now, but would prefer a PHP alternative that I could either use in the template or the views setting directly.

Setting the page title using javascript isn't SEO friendly.

I am using the latest version of Drupal 6 with the latest stable release of Views 3.

The results of print_r($view->result, true) (as requested) are :

Array
(
    [0] => stdClass Object
        (
            [_random] => 0.00171253550957193
            [radioactivity_node_1_s_energy] => 3
            [node_title] => <Title of the node being displayed>
            [nid] => 393
        )

)

Inside a views template, you could call drupal_set_title() with whatever you want out of the $view->result array.  You can put a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent in there to see what you have to work with.

In Style Settings, just click on Theme Information, and choose one, I'd suggest modifying the Style Output one because you could also change $title in there as well.

ADDITIONS DUE TO COMMENTS:

No, views will not set this for you, I thought that's what you were asking.

In your views template for the view in question, you need to dig into your row result to get the value you want and then call drupal_set_title() with that.  Calling it with a null value only returns the existing title, if any.

For example, if you put the print_r() of your result in there, you will see what values you have to work with, and then you use them with this to set the title.

Let's say you have something like this:

[0] => stdClass Object
    (
        [node_title] => Sirens
        [nid] => 240
        [_random] => 0.000554758124570137
    )

which is the view result from a view I just put together that randomly returns node titles, you would do something like this in your template:

$title=check_plain($view->result[0]->node_title);
drupal_set_title($title);

You could also put this in a pre_render() hook like so:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name==NAMEOFYOURVIEW) { // && $view->current_display == 'page' if needed
    $title=check_plain($view->result[0]->node_title);
    drupal_set_title($title);
  }

}

But either way, since I don't know exactly what your view row looks like, I can't tell you precisely what $view->result[0]......  you need.

Also, all of this is assuming your theme behaves nicely with the $head_title variable as well.


Uploading from within fieldset using drupal 6 forms API not working I've got a drupal form with a fieldset (actually, two). Inside the fieldset, there are a number of dynamically generated file fields. Unfortunately, I can't seem to access these fields' contents from file_save_upload. Currently, I'm attempting to use the approach described here to set the #name property of my file fields so that the files array gets built correctly. However, file_save_upload always returns 0. What am I doing wrong?

Form (this is an example, since the actual form is dynamically generated by a bunch of code that isn't relevant here):

$form['release_data_graphics'] = array(              //This has a few other random things in it
    '#type' => 'fieldset',
    '#title' => 'Brand Release Graphics',
    '#collapsed' => FALSE,
    '#collapsible' => TRUE,
    '#weight' => 11,
);
$form['release_data_graphics']['graphics'] = array(  //This has a few other random things in it
    'folders' => array(                              //This is here because I iterate through it
        'folder1' => array(
            '#type' => 'fieldset',
            '#name' => 'Folder 1',
            '#description' => 'some description',
            'graphics' => array(                     //This is here because I iterate through it
                'graphic1' => array(
                    '#type' => 'file',
                    '#title' => 'Upload graphic 1',
                    '#name' => 'files[1]',
                ),
                'graphic2' => array(
                    '#type' => 'file',
                    '#title' => 'Upload graphic 2',
                    '#name' => 'files[2]',
                ),
            ),
        ),
    ),
);

Then, in my submit handler, I iterate through the folders and child graphics arrays (which I won't show here) with file_save_upload. My code ends up running file_save_upload like this:

graphic1 = file_save_upload('1', file_directory_path(), FILE_EXISTS_REPLACE);
graphic2 = file_save_upload('2', file_directory_path(), FILE_EXISTS_REPLACE);

When I select a few items for upload and then print the files table in the submit callback, the files table looks good:

[files] => Array(
    [1] => test1.png
    [2] => test2.png
);

So I'm really having trouble figuring out what's going on...

Add this to beginning of your form

You need this:

$form['#attributes'] = array('enctype' => 'multipart/form-data');

Also:

file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME)

you have

graphic1 = file_save_upload('graphic1', file_directory_path(), FILE_EXISTS_REPLACE);

you should have

$graphic1 = file_save_upload('graphic1',,file_directory_path(), FILE_EXISTS_REPLACE);

One thing I've noticed in D6 with file uploads is that using only file_save_upload() will result in your file being purged on a subsequent drupal cron run. This happens because all files are uploaded in Drupal with a status of 0.

Therefore, you should be calling your hook_submit more like this...

// Save new file uploads.
if ($file = file_save_upload('file_upload', $validators, file_directory_path())) {

// Do something with $file here.

//Make file permanent
file_set_status($file, FILE_STATUS_PERMANENT);
}


Applying a patch doesn't work I'm having trouble with applying a patch for a Drupal module.
I thought it was as simple as using "git apply thepatch.patch," but when I do this in the main directory that holds the .git directory, I get the following error message:

  Checking patch entity_translation.admin.inc…
  error: entity_translation.admin.inc: No such file or directory

When I do this in the directory where the files are located, nothing happens; no error is shown, but no file is changed.

It's not a problem I have with this particular patch, but I never seem to be able to apply a patch, and I just end up manually editing the files.

I would like to know the solution once and for all.

It is possible that the patch was rolled before the days of Git on drupal.org.

For old patches:

patch -p0 < thepatch.patch

For new patches that mysteriously fail with git apply:

patch -p1 < thepatch.patch


How do I reset the clean URLs? Another developer has sent me a completed Drupal 7 website. When I installed it, the home page uses clean URLs, which don't work; example.com/index.php?q=/node/123 does work.

When I go to example.com/index.php?q=admin/config/search/clean-urls, there is not a check box to turn clean URLs on. Is there a way to disable the clean URLs, and start the process again?

When clean URL are enabled, the page at admin/config/search/clean-urls is like the following one:

When clean URLs are not enabled, you should see a description such as the following one, and a button to test the clean URLs ("Run the clean URL test"):

  Use URLs like example.com/user instead of example.com/?q=user. If you are directed to a Page not found (404) error after testing for clean URLs, see the online handbook.

Once you click on the submission button ("Run the clean URL test"), Drupal would check if the clean URL are possible to enable, and show you the checkbox to enable them, which should be not selected.
If that doesn't happen, the online handbook reported in the description has a link to How do I unset the clean URLs? where three methods are listed:

Run the following Drush commands:

    drush vset clean_url 0 --yes

Run the following MySQL commands:

    UPDATE variable SET value = 's:1:"0";' WHERE name = 'clean_url';
    TRUNCATE cache;

If previous update statement didn't solve it, some drupal version may need a different key :

    UPDATE variable SET value = 'i:0;' WHERE name = 'clean_url';
    TRUNCATE cache;

Alternatively, you can modify the appropriate settings.php file to include the following line at the bottom (or similar code in the site settings array you'll see there).

$conf['clean_url'] = 0;


Node access based on condition I'm adding an event list to a website and I want to limit what anonymous users see based on a field value, a checkbox "Private event". If the checkbox is marked then only a subset of the fields for the given event are shown. Furthermore, after a year of the event I want all fields to become visible to anonymous users. I took a look at the Access Control module but couldn't find a way to have this conditional type of access to fields. Is there another module that I could use?

I would do like this:

Define a new 'Restricted' View mode. Either manually with hook_entity_info_alter or with Display Suite.
Create a new Page in Page manager, using the by default available Node view.
Create two separate variants in the page.

The first one will use a selection rule on ´Role: Anonymous´ and ´Field Private event: True´. In this Variant, display the node with the 'Restricted' view mode.
The second variant will not need a selection rule, as it will be the fall through option. Here you show the node with the normal 'Full' view mode.

For making everything visible after a year , it sounds like either a hook_cron with some code in it, or perhaps a combination of some Rules with a VBO, which would flip the private field off after a year. Sounds like that might be a separate question though.


Does field_revision_field_xxx table store the same values as field_data_field_xxx does? I use drupal7.

According to the answer here,

{field_data_[field_name]} Standard data storage for a field.
{field_revision_[field_name]} Standard revision storage for a field.

I understand it, but, finally, they store the same values, right? This is because, I found that field_revision_field_xxx actually stores the updated values after I update a field-xxx.

[The reason why I ask this]
I try to transfer field values from one profile type to another which have the same uid. For it, I create field_data_field_xxx_transfered and field_revision_field_xxx_transfered and rewrite the pid in them.

I succeeded to transfer values from field_data_field_xxx to  field_data_field_xxx_transfered. And, if field_revision_field_xxx stores the same values as field_data_field_xxx does, all I need to do is to copy field_data_field_xxx_transfered to field_revision_field_xxx_transfered. And, this is much easier than to do from field_revision_field_xxx to field_revision_field_xxx_transfered.

Thank you.

Yes, field_revision_[FIELD_NAME] contains the same value as field_data_[FIELD_NAME]. The only difference in both these table is, if you've enabled revision for entity having this field ([FIELD_NAME]), the field_data_[FIELD_NAME] will contain the latest revision value of the field and field_revision_[FIELD_NAME] will contain all revision value.

For example, Suppose I've a content type article with revision enabled, and has a field field_tags. I've then created a content of type article, so now field_data_field_tags and field_revision_field_tags contain data for the content I've just created. After this when ever I'll be updating this content, the field_data_field_tags will hold the latest revision data for field_tags field and field_revision_field_tags will hold all revision data for field_tags field i.e. revision id 1, 2, 3 and so on.


Is there a variable that keeps track of which pages are enabled or disabled in Page Manager? I'm using the Features module and I'm tired of manually enabling/disabling pages (user_edit, user_view, etc.)  Is there a variable that I can add to Strongarm to control this in code?

Yes, there's a variable per page of the form "page_manager_MACHINE_NAME_disabled", eg. "page_manager_node_view_disabled". You need to set it to FALSE using Strongarm to enable the corresponding page.


Custom User Fields Not Displaying I've created a couple custom fields for Users in Drupal 7 via Config > Account Settings > Manage Fields. Mainly a user's real name, company and a welcome message.

I'd like this info to be displayed when the user views their account page (site.com/user/username) but the fields will not display except to my admin account. The fields are set to visible in the display settings and the users are assigned the appropriate permissions to view profiles and other content.

I've tried enabling Profile2 and using it as well but the problem still persists. Any ideas what's going on here? It's driving my crazy!

There is a check box on field edit page of user account which enable "Display on user registration form.". This one might work for you.


Node image instead of pointer icon in openlayers map Does anyone know a way to change the pointer icons to node images?

Like the image below

I really like to have a little preview image from the node instead of hundreds of same looking pointers.

Any ideas?

output the image's URL in your view which supplies data to your map.
create a new openlayer style, and for the marker graphic, give it your field name enclosed in ${}.

eg. add field_image to your view, set it to output 'url to file'
then add a new style and tell it the marker graphic url is ${field_image} and select an image style (eg. thumbnail)

use this new marker style on your overlay and you'll see the image show up as a marker icon.


How to show a map within a node using gmap and location modules I'm trying to save a location together with the node of a certain content type and when the node is shown I want the location to show up on a map within the node content. I use the Gmap and Location Modules, and I manage to save locations to the database, but the map doesn't show up. Any suggestions?

In the display settings of your content type, you should be able to change the value to "Map only" or "Adress with Map".

Then it should display it as a GMap.

I use:

GMAP
GMAP Location
Node Locations
Location CCK

I think you're missing Location CCK, in order to get the Map stored as a field in the content type.

Otherwise, if you use the content Location, I think the map is available as a block (not sure about this one).


Custom Table or CCK? I'm currently working on a project with a new requirement that, in a nutshell, queues submissions from users and submits them them to a remote API:

collects submissions from users (with a form)
each submission points to a record on a remote system (uuid provided by remote API)
each submission has a status (ie: new, accepted, declined)
each submission stores a number of other fields of data
each submission references a node id that already exists in drupal
submissions with a status of "new" are presented to an administrator, who can accept or decline them (the queue)
changes to submissions are audited
submissions are never published as content, as they may contain personal info

Much of the data being stored for each submission is simply for interaction with the remote API. Only a small amount of the data for each submission is for human/administrator eyeballs.

I began architecting the storage for these submissions - basically just a really wide database table with one column that references a node id. The database table will also need to be exposed in Views, so that I can easily build pagable, filterable & sortable html tables. Will also perform some custom bulk operations (View Bulk Operations).

I'm now debating if it would be wiser to use a custom node type with a pile of CCK fields to store these submissions as unpublished nodes, rather than building it all custom. On the downside, I'd have to do a lot of form_altering to get the submissions form to where I want it, and I really don't need a lot of node functionality (workflow, comments, titles, etc, etc). On the plus side, if using nodes+cck the Views integration comes for free, and it's likely quicker to build.

I'm working in Drupal 6, and an upgrade to Drupal 7 is at least a year out - but it's also something I need to consider when making this decision.

Any thoughts?

Go with CCK.

I've done this in Drupal 5, and I'm doing it again for Drupal 6.  It's really not that hard to get this going.  You gets all kinds of things for free both with CCK and Views.  You already mentioned the benefits for Views, but it's the same for CCK.  You simply create everything you need from the UI, and then export it to a file that gets read during your install hook.

Also, why write your own CRUD?

I'm doing something very similar.  Take a look at my code over at Syndeploy.

I haven't exported the Views code yet, but I'll get there.


How to remove the Day field from the Date drop down? on this page http://dev.amnesty.io1developer.com/donate-now
under the section of the Credit card,I want to remove from the date the Day field.
It is a webform.How to achieve this?
Thanks

if there is no validation on the form you could hide it with CSS.
Otherwise you can use a hook_form_alter


Migrating D5 users to D6 using MigrateDestinationUser I'm using the migrate module to migrate users from a Drupal 5 site to a Drupal 6 site.

MigrateDestinationUser assumes that the source passwords will be plaintext which isn't the case in Drupal 5. Is there any way around this assumption?

As per http://drupal.org/node/1349758, you need to add a complete function:

$this->addFieldMapping('pass', 'source_password');
...
public function complete($account, $row) {
  db_update('users')
    ->fields(array('pass' => $row->source_password))
    ->condition('uid', $account->uid)
    ->execute();
}


Custom views handler without table This seemed easy at first but I'm losing my hair on this.

I simply want to add a custom view handler that uses no table.

I tried to do as views php proposed, $data['views']['mycustomfield'] in hook_views_data, but still, "mycustomfield colum not found".

Any help ? Thanks !

Actually its easy. Just look at the implementation Views Global handlers which is available in views.views.inc.

Below is the example how you can add field handler without having a table,

Specify your custom handlers in hook_views_data like below,

/**
 * Implements hook_views_data().
 */
 function my_module_views_data() {
   $data['custom']['table']['group'] = t('Custom');
   $data['custom']['table']['join'] = array(
     // #global is a special flag which let's a table appear all the time.
     '#global' => array(),
   );

   $data['custom']['custom_handler'] = array(
     'title' => t('Custom Handler'),
     'help' => t('Custom Handler.'),
     'field' => array(
       'handler' => 'views_handler_custom_handler',
     ),
   );

   return $data;
}

Create a inc file for your handler an put your logic there. something like below
Here the file name would be views_handler_custom_handler.inc

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
 class views_handler_custom_handler extends views_handler_field {
   function query() {
     // do nothing -- to override the parent query.
   }

   function option_definition() {
     $options = parent::option_definition();

     // Override the alter text option to always alter the text.
     $options['alter']['contains']['alter_text'] = array('default' => TRUE);
     return $options;
   }

   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);

     // Remove the checkbox
     unset($form['alter']['alter_text']);
     unset($form['alter']['text']['#dependency']);
     unset($form['alter']['text']['#process']);
   }

   function render($values) {
     // Render your content.
     return 'Sample';
   }
}

Specify this new handler file in your module's info file
Clear the caches

Now the new field handler will be there in the field list.


Identifying drupal installation on windows I don't want a google custom search to be shown on my development system which is on windows but it should be visible when on production system which is on Linux.

How do I check it?

This isn't working out. I've placed this code in the block "Pages on which this PHP code returns TRUE (experts only) " but it does not work in my Windows installation:

<?php
if(  file_exists("C:"))
{
return false;
}
return true
?>

You can achieve this by implementing the php_uname() function:

$os_name = php_uname("s");
if($os_name == 'Linux') {
  return TRUE;
}
//can apply additional checks for other OS
else {
  return FALSE;
}


Facebook OpenID Selector I work with the OpenID Selector; everything is OK, but nothing happens when I click on "Facebook."

I work with the Drupal for Facebook module; this works fine, but with the OpenID Selector just it's just select the facebook icon.
Another issue is when a user log in to my website and needs to log out; the user is still logged in with the service he used.

From the libraries/openid-selector/README.txt:

  how to plug-in facebook provider
  put the following code in providers_large or providers_small:

facebook = {
     name: 'Facebook',
     url: "javascript:facebook_click();"
}

  where facebook_click is something like:

function facebook_click() {
      $('#<id of html fbconnect element>').click();
}

  the same mechanism also applies if you want to plug-in any oauth or xauth provider

So that is what the README says. I specifically had to do the following I'm using Drupal7.8 with openid-selector module 7.x-3.x (2011 May 07):

In modules/openid_selector/openid_selector_fb.js:
Replace the chunks that look like similar with the ones Ive posted.

providers_large.facebook = {
  name: 'Facebook',
  url: "javascript: $('.fb_button').click();"
};

and again for this chunk

Drupal.behaviors.openid_selector_fb = { attach: function (context) {
  $('.fb_user-login-button-wrapper').hide();
}}


Page Categorisation and Multi-level Paths I want to categorise my pages and see the category names in path.

For example: instead of http://localhost/a-funny-story, http://localhost/stories/funny/a-funny-story.

What is the best practice? I tried to do it with Pathauto module. I created a content type with a term reference of a category taxonomy.

I use this pattern [node:field_my_page_category]/[node:title] in "CONTENT PATHS". But this doesn't work for multi-level categories. I tried to use "join" [node:field_my_page_categories:parents:join:/]/[node:title]  as mentioned here.

But I get this error: The Pattern for all Sayfa paths is using the following invalid tokens: [node:field_my_page_category:parents:join:/].

If it is a node, you need to use Pathauto and also Replacement Patterns, in the Replacement Patterns select the taxonomy term and put it in the url.

But if you need to list set of contents based on the url you need to use Views and add the terms as contextual filters.


Migrations dependencies: run one by one? I have a few migrations in the same group for singe multi-language entity type set up. One migration handles one language. I need to make sure that default English language migration runs first and then it triggers all the others when I execute migration for the English language via admin UI of migrate tools module.

Can not find how make it through dependencies in yml for the default language, because dependencies list gets processed first. Is there proper way to do it?

First of all, you only need two yaml files, one for the default language and one for the translations.

If you are migrating for example a content type of bundle pages and your default language migration is eg. my_website_migrate_node_page, then in the my_website_migrate_node_page_translation define your dependencies as follows

migration_dependencies:
  required:
    - my_website_migrate_node_page
  optional: { }


Creating multiple temporary sites I have to evaluate multiple different third-party modules. I figured the easiest way to evaluate each one would be to create a site featuring one module at a time so nothing could possibly conflict.

Is this efficient? If so, what would be the fastest way I could do this without going through the Drupal 8 installation process tons of times?

I'm running Fedora 25 with Apache, and Drupal 8.3.5.

I think too that the easier way is using simplytest.me, which allows to install more than one module and apply patches. (Click on Advanced options, which at first sight could not seem clickable.)

Consider that:

As of July, 2017, simplytest.me runs on Ubuntu and PHP 5.5.12-2ubuntu4.4
Some PHP extensions aren't installed, so some Drupal modules cannot be installed (e.g. the LDAP module)
As of March, 2017, it uses the Composer Manager module, so it can install any Composer requirements a module has
Some distributions, like OpenChurch, fail to install

If you don't need to have a fine control over the environment, simplytest.me is perfect for testing modules and combination of modules. It is surely faster to test modules on simplytest.me than using a virtual machine on your computer. The second option has the pro of allowing you to better control what you install at server level, and it helps if you need to reproduce more accurately the production server you are using.

The site is being ported to Drupal 8. You can see the progress on https://new.simplytest.me/. I am not sure it can be used for extended test of modules.

Reference

The project issue queue


How do I add unique page titles and meta titles to paginated views pages? I have overridden the taxonomy term pages with a view, and I want to be able to set the page title, both visible and meta, with unique titles for each page within the pager for SEO purposes. I am hoping the solution resides in a module, or in a view setting (and not on a template basis).

Do you have any suggestion?

There are actually two modules:

the Meta tags module that is used to add meta tags to any pages

  The Meta tags module allows you to automatically provide structured metadata about your website. In the context of search engine optimization, when people refer to meta tags, they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of your site in search engine results.

the Page Title module that is used to set the title visible with the <title> tag

  This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.

the Title Overrides module

  Title Overrides is a module to provide title overrides for any page in as simple as an interface as possible. This module differs from the Page Title module in that this overrides both the <title> meta tag as well as the <h1> tag. You also have the option of entirely removing the page title from any page, which will remove the <h1> tags as well as remove the piping from the meta title. This improves search engine optimization for pages that have been overridden.

As far as I recall, there were some problems using the Meta tags module to set meta tags for views, but it can be they have been resolved, now.

The Title Overrides module seems the one you are looking for, as it overrides the content's title for any page.


CKEditor doesn't load when using Bootstrap theme I'm building a fresh site on Drupal 7.26 and the main Bootstrap 3 (7.x-3.0) theme from https://drupal.org/project/bootstrap.

My site also uses Organic Groups and Display Suite, along with many other modules. CKEditor 7.x-1.13 is installed. I have not edited the code of any file in the site, including the theme files.

Problem: When creating new content, CKEditor does not appear in the text area with 'filtered HTML' settings.

Details:

My basic test user with only
"authenticated user" role cannot use CKEditor to create or edit
content. A Bootstrap-themed textarea is all that shows for all 'filtered HTML' text fields.
My admin user, using the Seven theme in overlay for admin and
editing, can access CKEditor everywhere I expect to see it. CKEditor
buttons and layout are correct.
I switched the site
default theme over to Seven, and my basic test user could use
CKEditor. Once the theme was switched back to Bootstrap, CKEditor
went away.
The really
odd part: CKEditor loads properly for the basic test user in
Bootstrap theme for all comment entry forms.

The only permissions I see for CKEditor are "Administer CKEditor access" and "Customize CKEditor appearance", which are both set only to administrator.

Resources I have read that are similar:

Having my own theme for creating and editing Nodes: No WYSIWYG Editor
https://drupal.stackexchange.com/questions/77731/ckeditor-doesnt-show-up
CKEditor is missing when editing a page, but works fine when creating a new page
http://docs.cksource.com/CKEditor_for_Drupal/Open_Source/Drupal_7/Troubleshooting#CKEditor_does_not_work_in_my_theme

In the source code for a create node page in my basic test user's account, I see
finally, at line 273 it has the scripts:

<script src="http://my.site.com/sites/all/modules/ckeditor/includes/ckeditor.utils.js?n1lvkb"></script>
<script src="http://my.site.com/sites/all/libraries/ckeditor/ckeditor.js?n1lvkb"></script>
<script src="http://my.site.com/sites/all/themes/bootstrap/js/bootstrap.js?n1lvkb"></script>

I'm wondering if loading the CKEditor js at the end is related to this problem. Since I haven't yet dug into coding in Drupal though, I'm not sure how to correct it.  I'll be creating a Bootstrap sub-theme, and maybe I can address this problem there? Any advice on this would be greatly appreciated.

As I debug this, I'll add some edits at the bottom showing what I find.

Screen captures:

Updates:

I created a Bootstrap sub-theme and activated it. For a quick test I pasted the script sources for ckeditor into the head tag. In Firebug, when viewing a Page created by Panels, the console shows this error:

TypeError: Drupal.settings.ckeditor is undefined
window.CKEDITOR_BASEPATH = Drupal.settings.ckeditor.editor_path;
on line 5 of ckeditor.utils.js

I guess that means settings haven't loaded yet.

I removed the pasted-in script sources.  After removing them, the above settings error no longer appears.  Based on the tips in the CKEditor troubleshooting, I verified that php commands to print the vars scripts and page_bottom are in place. Now, on a node creation page, Firebug reports these errors:

TypeError: a(...).on is not a function
...a(this),f=e.data("bs.modal"),g=a.extend({},b.DEFAULTS,e.data(),"object"==typeof ...
bootstrap.min.js (line 9)

Solved.  The I am using the development version of jQuery_update which provides a fallback version of jQuery to use on administrative pages.  -- https://drupal.org/node/1524944
It determines whether or not to use the admin version based on if the current_path() is found in the return value of path_get_admin_paths().  Unfortunately for me,  node/add is an administrative path. So, jquery_update kicks in and loads jQuery 1.5.2 to be compatible with the administrative task. It seems CKEditor can't operate with 1.5.2. I noted above that CKEditor loaded without issue for a comment field on a node. Since viewing a node isn't an administrative path, the page was allowed to load jQuery 1.10 which works fine with CKEditor.
For now, I added an array of paths to exempt from admin status (node/add, node/add/post, etc) and added that to the evaluation in jQuery_update. Content creation pages now load jQuery 1.10 and CKEditor appears normally.
UPDATE: in place of the array of exempt paths, I have put in place the patch posted by muschpusch at https://drupal.org/node/2141205 . It has solved this issue.


Node edit form shows cached or previous title while editing node, after updating node? When I update a node the revision show changes in values when we see diff but after updating node when I edit node again in node edit from it shows old value ie: cached value.

When I flush all cache then the updated value start appearing in node edit form.

In site no page cache is enabled, no block cache is enabled. But we are using memcache

This does not happens always but starts happening when cache not cleared for few hours but after clearing cache it starts working.

Please suggest what kind of cache is effecting values while editing node titles.

I am using modules as well Title and entity_translation

In my views there is no cache and I am using template file for views nid in which I fetch titles like below which also shows cached version :

$link = node_load($nid);
$link->title_field['en'][0]['value']  // English value title
$link->title_field['fr'][0]['value']  // French value of title

Should I try like this to get rid of cache:

$link = node_load($nid,null,true); // setting true

Please suggest, I have been trying and searching from long time but not able to find solution. It seems like problems with memcache.

Minimum cache lifetime = none

EDIT: seems kind of some similar problem Need to flush cache after node translation

TRIED SOLUTION and this is of no help :

function custom_module_node_update($node) {
  $nodeurl = url('node/'. $node->nid);
  cache_clear_all($nodeurl, 'cache_page');
  cache_clear_all("field:node:$node->nid", 'cache_field');
}

I am not sure this will help in this case or not or while updating translation of node. Please suggest!
Thanks!

I have switched to below for cache and removed memcached completely. All problems solved with this.

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

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

Thanks!


How to avoid admin account to be blocked for all ip's by failed attemps to login? In my drupal site, often i see this message for the admin account

Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked.

I know i can solve it clearing the 'flood' database table, and i'm almost sure it is caused by people or bot trying to login as admin. 'Almost' for in the table flood the failed attemps have identifier '1-127.0.0.1' that is the local ip and it sound strange to me...
There is a way to avoid the problem for good? (and to be sure it is about people/bot trying to login and not something else?)

(I mean obviously a convenient way. Allowing all the login attemps without blocking them is not a solution.)

The answer can be found in this article

https://www.karelbemelmans.be/2015/04/reverse-proxy-configuration-for-drupal-7-sites/

Adding these lines to settings.php solves the issue:

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';

Added these lines, in the flood table of the drupal site database, every failed login request is logged with the real ip the request came from.

The real problem, indeed, was not lying in the failed login attemps, but in linking all the attemps to the loopback address. Looking at the flood table in drupal database, I could see every request under the ip 127.0.0.1, which is wrong and causes any request from any user (and any ip) to be blocked if anyone from any ip tried to login with wrong passwords. Linking attemps to their right ip makes the drupal flood protection working as expected, that is blocking attemps only from the ip which tried to login with wrong password.


Refreshing entity definition I've got a D8 media type that holds information obtained from an external source. The information comes in name value pairs that I wish to save as individual fields, mostly so I can index them easily with solr.  On some files I get new property names that have to be persisted as fields, so I have a presave hook that creates and saves a FieldStorageConfig, and a StorageConfig for my each new field in my  media bundle.  It all works swimmingly.

THe problem is when i try to save a value to that new field in the presave function an error is thrown indicating that the field doesn't exist.  (It does exist, but Drupal doesn't know about it yet).  When I resave the media with the same input file everything goes as planned.

Is there a way to force Drupal to refresh the media's field list?

This is as simple as reloading the entity.  The entity is loaded with the current fields, if new fields are added to the content type, the entity won't update on its own.

In my presave hook I check to see if new fields have been added at that time.  If so I wait til the media update hook is fired to reload.


"user:one-time-login-url" token not getting replaced by token_replace I'm trying to send e-mails to users manually by using the hook_mail_alter hook. The following is my function in its entirety:

function custom_module_mail_alter(&$message) {
    $email = '[user:name],

A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at [site:login-url] in the future using:

username: [user:name]
password: Your password

--  [site:name] team';

    $account = $message['params']['account'];
    $uid = $account->uid;

    $_user = user_load($uid);

    dpm(token_replace($email, array('user'=>$_user)));
}

The output looks like this:

Peter,

A site administrator at Website has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at http://localhost/website/user in the future using:

username: Peter
password: Your password

--  Website team

As you can see, things like [user:name], [site:name], and [site:login-url] are properly processed. The only token that isn't processed is [user:one-time-login-url]. Any ideas why this is happening?

EDIT: Just for reference, the token does get processed in the Welcome e-mails that's sent out by the system automatically, so the token module is active and working... It just doesn't seem to get processed when I manually call token_replace().

To replace that token, you need to call token_replace() as token_replace($email, array('user' => $_user), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE)).

The function user_mail_tokens() is described in the documentation as:

  Token callback to add unsafe tokens for user mails.

  This function is used by the token_replace() call at the end of _user_mail_text() to set up some additional tokens that can be used in email messages generated by user_mail().

The code used by _user_mail_text() to call that callback is the following one.

// We do not sanitize the token replacement, since the output of this
// replacement is intended for an e-mail message, not a web browser.
return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE));

The Token module is not necessary to replace tokens, in Drupal 7. The code to replace tokens is part of the Drupal 7 core code; the Token module in Drupal 7 defines extra tokens that Drupal core modules don't define.


Using pathauto to create multiple aliases, one for each term? If I have a taxonomy tags so that I can tag a node with foo and bar and baz, is there any way to make the pathauto module create three aliases?

If it would normally create content/my-new-node, is it possible to make pathauto create foo/my-new-node and bar/my-new-node and baz/my-new-node?

Under Configuration, if you go to Modules and click on Configure for Pathauto, you should see the option for the URL patterns. There is a section for taxonomy as well. However, I realize you want to change a node's URL based on the taxonomy term you've associated with it. At this point, it's just a matter of figuring out what token is going to do that for you.I have not used it, but I would imagine the Field Tokens module may help you do what you want to do. If you search for "pathauto" on that page, some people discuss using it with Pathauto down in the comments.


String replace with rules Is there a way to string replace with rules?

I'm trying to find some way to transform values without changing a value entirely.

Is there something I'm missing, or should I just make a custom rule that does string replace?

I used this for my incoming feeds, changing http:// to https://

{ "rules_http_to_https" : {
    "LABEL" : "http to https",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "feeds" ],
    "ON" : { "feeds_import_canada_com" : [] },
    "DO" : [
      { "data_set" : {
          "data" : [ "node:body:value" ],
          "value" : "\u003C?php\r\necho str_replace(\u0022http:\/\/\u0022 , \u0022https:\/\/\u0022, \u0022[node:body]\u0022 );\r\n?\u003E"
        }
      },
      { "data_set" : {
          "data" : [ "node:field-contestpageurl" ],
          "value" : "\u003C?php\r\necho str_replace(\u0022http:\/\/\u0022 , \u0022https:\/\/\u0022, \u0022[node:field-contestpageurl]\u0022 );\r\n?\u003E"
        }
      }
    ]
  }
}


How can I add content in between views in bootstrap grid format? How can I add content in between views in grid format?

Header and footer is fine, but how about interrupting the flow of grids, is there a module for that?

Or do I need to hard code a template file?

Or maybe use css to make the element full width at X item number in the grid?

Image to explain here:

I am stepping in with the response of Neograph734. Google is your friend and you can easily find the answers there.

But I am going to help you. It is easy to be done:
Create a view (page or block) and setup the filter and order criteria to what you want to display. In the pager section, set items to display to 3.

Make an attachment display with the same filter and order criteria. attach the attachment to the first view. Take "attach after" . Then in the pager section, determine how many items you want to show and set the offset to 3.

This way you can either put in the footer section of the first view or the header section of the attachment the text you want to place there.


main menu link as language switcher I have 2 language and these situation:

main menu -> lang1 -> link to www.foo.com/
main menu -> lang2 -> link to www.foo.com/en

All sites when switch manually on browser the language, But my main menu link not work.

I have no space to place an other block with menu switcher on main menu bar.

I hope someone can send me in right direction because I spent 8 hour around these without solutions?

after long investigation and test I think there is no way to make the "language module" work correctly if all the language codes have not been declared in the configuration, so that every language has the code after the base_path. Using base_path for the primary language and code for the secondary (base_path / language_code /) creates confusion to the "language module" that results in unexpected results. Alias url and url edirect can not make up for the lack. It would be necessary to create a special module to solve the situation and while having seen some code in the working web, I do not think it's a good idea to use it with the core 8 and beyond. The "language switcher" module, on the other hand, works well, but to make it integrated into the main menu, you still need to write custom code. In short, all languages, the primary and the others must be dicated in the configuration in the classic way: base_path / language_code /. There is no way out.


Understanding Drupal's session management and user authentication I have a requirement where, I have to replace the default user authentication with the authentication of a central server i.e. SSO server.
By debugging Drupal I came to know that all the session management happens in includes/session.inc file. I want to do authentication as shown in the image:

SCENARIO: Login
The details of the steps would be:

Replace the login form to submit the username and password to SSO server (not on Drupal, but on .NET).
Authenticate the user on SSO server using database of that site; and send a response back to some custom PHP page of my website (or a form by a module?).
Using the response, identify the user in the users table, and create a session for that user without checking for the password (as it would mean double authentication).  By default, Drupal sets a cookie with name of $insecure_session_name variable, and with value $sid. I want Drupal not to set the cookie here, instead send the values of variables to SSO server.
The SSO server will take the values, create a cookie, and drop it in main domain domain.com (to remind both my website and sso server are on sub domain of main domain, which too in not in Drupal). Then, the drupal site can log in by using that cookie.

I know it is a tough ask, I am just looking for pointers as to how should I start? as they say "you should not hack the core". So, my questions are:

Where should I look for to understand how Drupal authentication and session management works in depth?
Is there a way where I could call the functions in includes/session.inc using hooks (as the comments with functions says "for internal use only/not to be modified")?

NOTE: I'll be using the same method to register the user, so that the record remains in central database of the SSO server. And during that will put in some junk password for the same user in Drupal site's database (as the password will not be checked while login).

Drupal supports external authentication. There are many alternatives authentication modules for Drupal, such as OpenID (included in core), OAuth Connector, or LDAP. Learn more about how Drupal authentication works; the best would be to look at the OpenID and OAuth modules, and to the core login form submit callback. But, AFAIK, they always start the normal Drupal session after a successful authentication.

For session management, Drupal plugs into PHP session handling and register it own handlers. The Drupal session backend is itself pluggable, you can set the session_inc variable to the path of a file providing alternative implementations of the functions found in includes/session.inc. The memcache module use this to store session in memcached.

For references, the OpenID module handle successful authentication in openid_authentication() which itself ceats and call the user login form submit handler (ie. user_login_submit()). This submit handler itself is simple, it loads the successfully authenticated user with user_load() into the global $user variable, it then call user_login_finalize() which handle session, login timestamp in the user table and invoke hook_user_login() implementations.

Another option is the use the user_external_login_register() function. The function will log an external user in. It also creates a local user if needed. If you need more control on local user creation, you can always use user_save(), user_set_authmaps(),  user_login_submit() and user_external_load() from you custom call, using user_external_login_register() as template of what needs to be done.


Only run javascript on certain block I have a views block that I want to modify with javascript. I can get it to load with the following in my template.php:

function THEME_preprocess_block(&$variables) {
      drupal_add_js(drupal_get_path('theme', 'THEME') .
      '/js/script.js' ,  array('type' => 'file', 'scope' => 'footer'));
}

However, I only want it to load when a certain block is displayed. I want to use something like:

function THEME_preprocess_block(&$variables) {
    if ($block->block_id == 'matching_id') {
      drupal_add_js(drupal_get_path('theme', 'THEME') .
      '/js/script.js' ,  array('type' => 'file', 'scope' => 'footer'));
    }
}

If this is possible how would I go about making sure it only runs on that block?

You can just get the element like this:

$variables['elements']['#id']

And then if you would of some reason need to load the block you can do like this:

$block = entity_load('block', $variables['elements']['#id']);
$block_id = $block->id;


How to login into Drupal using Google Apps username and password? We are looking for a way using which users can login into Drupal site using their Google Apps account user name and password. We use 'Google Apps for Education' and we do not want maintain separate username and password for our Drupal site.

We would also like to limit access to certain users having Google Apps accounts. Something like filtering or pre-approved account list. And, users' account should be created automatically when they login for the first time, and they should not need to fill any additional account information in Drupal, it should be directly pulled from Google Apps account.

Is there any module for Drupal 7 that provides this functionality? I have already tried OAuth, Loginza.ru, OpenID etc. like approaches and these are not what we are looking for.

If there is no such module, how shall I proceed with writing a custom module for the same?

To integrate your Drupal 7 site with Google Apps, you need to:

Enable the OpenID module on your drupal site
Enable the Federated Login Service using your Google Apps control panel at http://www.google.com/a/cpanel/yourdomain.com/SetupIdp
Add an X-XRDS-Location header at yourdomain.com/openid  For example, if yourdomain.com is a PHP site, upload this as /openid/index.php

<?php
header('X-XRDS-Location: https://www.google.com/accounts/o8/site-xrds?ns=2&hd=yourdomain.com');
?>

Go to your drupal site's login page. You'll see a new 'login with open id' link. Click it. Enter: https://google.com/accounts/o8/site-xrds?hd=yourdomain.com and click submit
The first time you do this, you'll be asked if you want to allow your site to authenticate. Click yes.
Subsequently, if you try to login using the above URL and you are logged in to Google Apps, you'll be logged in directly.


Enable dialog for non-admin user I'm building some modal pages using the use-ajax class plus the data-dialog-type="modal" attribute on link tags. It worked great as an admin user, but logging in as a different role(call it parent) and the links go directly to the pages.

It's pretty obvious from the sources panel in web inspector that the parent role isn't being served the necessary javascript (dialog.jquery-ui.js, dialog.js, dialog.position.js, etc).

There's nothing in the permissions that looks like it would limit the javascript added to the page.

I've tried this in my custom theme and in bartik, same result.

The answer is simple enough, though a little counter-intuitive coming from a Drupal 7 install where everything but the kitchen sink is included.

All I had to do was to inlcude the library in my theme's .libraries.yml file;

dependencies:
  - core/drupal
  - core/jquery
  - core/jquery.once
  - core/drupal.dialog.ajax

This will be more performent than including the entire core javascript system on every page. It was a little confusing since that is the behavior for the admin user.


Force a single value base field to be in a separate table? I have a custom entity type (eg: myentitytype), and I would like to add a new base field to it via hook_entity_base_field_info(). As I understand it, single value fields (with a cardinality of 1) will create new columns in the myentitytype_field_data table, but multi-value fields will create a new table.
My question: is it possible to force a single-value field to be stored in its own database table, rather than adding columns to the myentity_field_data table?

Seems the following class is responsible for determining a separate field storage table:
\Drupal\Core\Entity\Sql\DefaultTableMapping::allowsSharedTableStorage

It returns a boolean based on the following 4 conditions:
public function allowsSharedTableStorage(FieldStorageDefinitionInterface $storage_definition) {
  return !$storage_definition->hasCustomStorage() && $storage_definition->isBaseField() && !$storage_definition->isMultiple() && !$storage_definition->isDeleted();
}

The only feasible solution would be to implement your own Storage handler and flag the basefield with "custom_storage" => TRUE


How to render fields in form? I passed the $uid as a hook_menu()-wildcard to a form and loaded the user of that uid with $account = user_load($uid). Admin then is able to fill some textfields and save. I want some other non editable fields from $account simply to be displayed as markup or anything like that in the form. Tried to pass these fields to #markup like so:
'#markup' => $account->field.

But this doesn't work. Should this normally work? What am I doing wrong?

Or would it be better to display an aditional block which fetches the $uid from the URL and prints me my fields?

I don't see anything wrong with your approach. '#markup' => $account->field should work. Do you have it nested under a key?

$form['static_field'] = array(
    '#markup' => $account->field
);


What configures Drupal to send emails on the create or update of an unpublished content? My Drupal installation attempts to send emails to a number of users whenever I create or update content but do not publish it. But because sending email is not configured errors are generated.

I don't know what configuration item I could have deliberately or accidentally set to cause that. Is there any setting or module that could cause that?

I don't think I have configured any Rules or Workflow settings to send emails, and it only occurs when the item is unpublished

The culprit turned to be the Antispam module, which is the client for the Akismet anti-spam system.

Its default setting causes an email to be sent to some administrators whenever a module is updated.

What baffled me was why that setting applied only when an unpublished item was created or updated.


Compare a single value entity reference field to a multi-value entity reference field The article entity has an unlimited multi-value Taxonomy reference field field_article_countries referencing the Taxonomy vocabulary Countriesand the User entity has a single value Taxonomy reference field field_user_countries which referencing the same taxonomy vocabulary Countries.

Programmatically, and comparing to one specific Article, I want to load all users that has have their field_user_countries value = to one of the values available inside the multi-value Taxonomy reference field field_article_countries.

Example:
Say Article "ABC" has the field_article_countries with values:

Paris
Spain
London
Italy

User "A" has field_user_countries set to:

Spain

User "B" has field_user_countries set to:

Italy

and User "C" has field_user_countries set to:

Turkey

I want programmatically, and based on Article "ABC", to load only User A & User B.

Below is my code:

// Get in array, a list of all "Article Countries" available for the loaded article.
$Article_Countries = $article->field_article_countries->getString();

    // Get Entity Manager to build your query
    $storage = \Drupal::entityTypeManager()
      ->getStorage('user');

    // Get all Users satisfing your conditions
    // For Condition Parameters @See: https://www.drupal.org/docs/8/api/database-api/dynamic-queries/conditions
    $uids = $storage->getQuery()
      ->accessCheck(FALSE)
      //->condition1
      //->condition2
      ->condition('field_user_countries', $Article_Countries, 'IN')
      ->execute();

    // Load all User entities according to their IDs
    $users = \Drupal\user\Entity\User::loadMultiple($uids);

    // Loop through loaded users.
    foreach ($users as $user) {

    // Do something here.

}

The problem is that only one user is being loaded and not all users !

Any idea what is wrong with my code ?

$Article_Countries = $article->field_article_countries->getString();

This returns a string

->condition('field_user_countries', $Article_Countries, 'IN')

From the docs, condition with IN accepts an array.

So, you need $Article_Countries to be an array of entity IDs. My first thought was $article->field_article_countries->referencedEntities() to get an array of objects, and then foreach them to build an array of IDs, but that's a bit round-the-houses. So I searched for a neater way and found this: http://drupal.stackexchange.com/a/207715/89581 which suggests:

$ids = array_column($entity->field->getValue(), 'target_id');


Views Sort by Taxonomy with headers I have a bunch of nodes that are of the type expert. Expert nodes have a flexible sized list of expertise categories. So an expert would be a person, (Patrick McDougle, Patricia O'Connor …) and a expertise category would be (Autism, Aging, Bulimia …) Using Views 3 and Drupal 7 I would like to end up with something like this:

Aging
Patricia O'Connor

Autism
Patrick McDougle
Patricia O'Connor

Bulimia
Patrick McDougle
...

Is there a way to do this, without having to create my own views template?

The trick is to add a view of taxonomy terms, and then add a relationship to the content. You'll also have to hide some fields and add a grouping field in the unformatted list settings. Details are below.

Create a new view that shows "Taxonomy terms" of type "expert [vocabulary]" sorted by Unsorted
Continue and edit
Add a relationship under Advanced > Relationships
Choose "Taxonomy term: Content with term" (Relate all content tagged with a term) & apply to all displays
You'll now be able to add a field and the content will show up. Click add next to Fields and select the Content Title or whichever field the name is stored at.
Uncheck "Create a Label" and apply.
Click on Format > Settings, and select "Taxonomy term: Name" in the "Grouping field Nr.1" dropdown, and click Apply. This will create a heading of the taxonomy term.
Hide the taxonomy terms from showing up extra times by clicking on the "Taxonomy term: Name" field, and click "Exclude from display."
Uncheck "Link this field to its taxonomy term page" so that the taxonomy term is not linked to it's page.
Save the view, and view the page.


How to create websites in shared folder using quickstart? I am using quickstart and I am able to create websites, run all drush commands, etc.

I am running Virtual Box on a Windows7 machine. i have setup a folder to be shared.

My problem: I am not able to create drupal sites (using drush qc --domain=mysite.dev") in that shared folder.

I want to create in that shared folder since I need access to the files from my windows environment also - for backup purposes, etc.

My terminal Output:

12:51:05 ~$ cd Desktop/
12:51:12 ~/Desktop$ cd shared
12:51:14 ~/Desktop/shared$ ls
DrupalPro_test.ova
12:51:15 ~/Desktop/shared$ drush qc --domain=neil.dev
                                                                     [ok]
Creating dns config (add neil.dev to /etc/hosts) ...                 [ok]
Command failed: neil.dev already exists...doing nothing              [error]
12:51:30 ~/Desktop/shared$ ls
DrupalPro_test.ova
12:51:36 ~/Desktop/shared$ ls
DrupalPro_test.ova
12:51:37 ~/Desktop/shared$

I found my answer on how to control where to store code. Trick was to use "--codepath=..." parameter.
Controlling where files are to be stored
drush qc --domain=d7tries.dev --codepath=/home/drupalpro/websites/REPOSITORIES/my-drupal-experiments/d7tries.dev --makefile=/home/drupalpro/.drush/d7.make
Help at: https://drupal.org/node/819398


Drupal 7 drop down menu not showing on other pages I have the main menu with 4 links (home, services, portfolio, contact)

under "services" I created a sub-menu, (service1, service2, service3)

The problem is that the little arrow that drops down the sub-menu shows ONLY on the "services" page and NOT the other pages.

How to fix that? thanks.

To clarify:

Go to Structure/Menus;
Select the menu with the non-expanding menu item (ie. Main menu);
Select the List Links tab if not already;
Click the "edit" link for the non-expanding menu item - the "Show as expanded" button is there.


Why would piece of content of each content type be migrated but their text formats wrong? I'm trying to migrate content D6 -> D7. I've written the importers (actually just edited existing ones) and run the process. However, as far as I can see, body of content are imported but with the wrong format i.e. one of them correctly shows as Full HTML while another shows just Select.

Below is my importer:

class StoryMigration extends NodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('body', 'body');
    $this->addFieldMapping('taxonomy_tags_1', 'field_tags')
      ->defaultValue('tid');
    $this->addFieldMapping('field_headerimage', 'field_headerimage')
      ->sourceMigration('Files');
    $this->addFieldMapping('field_headerimage:file_class')
      ->defaultValue('MigrateFileFid');
  }
}

UPDATE: I also did a format mapping, like below:

$common_arguments = array(
    'source_connection' => 'default',
    'source_version' => 6,
    'format_mappings' => array(
      '1' => 'filtered_html',
      '2' => 'full_html',
      '3' => 'php_code'
    ),
   ...
   ...
   ...
  );

You need to map the body format.

This is from 6 years ago, but reposting in case mikeryan does not see this question.

  if the format is part of the source data (i.e., it varies from node
  to node), you can make use of the source_field feature:

$this->addFieldMapping('body', 'body')
     ->arguments(array('format' => array('source_field' => 'body_format'));

Where body_format is the value from the source db I believe.

It has been a loooong time since I have done a 6 to 7 migration.

This post might also be of use if you are using migrate_d2d.


Choose Nodes within another Node This is something I've struggled with for a long time in Drupal. I'm guessing it's a relatively easy answer but I haven't been able to find an elegant solution. Here's the problem:

Let's say I have an e-comm site with Categories, Coupons and Products(all are CCK content types). Each Category can have any number of Products and Coupons. I'd like the ability to have a menu within my Category node that will allow me to select any of the existing Product and Coupon nodes. Also, not necessary but ideally I'd like the ability to change the order of Products/Coupons within the Category.

Is this possible? Or, is there a better way to do this?

Thanks in advance.

May be you're better of creating a vocabulary for your categories. This way you can filter for vocabulary terms in views.


how to apply 'noindex' to all nodes and leave Alias indexable to prevent perceived duplicates for SEO We're working with an SEO specialist who is finding that our underlying /node/### page URLs are competing with our aliases and bringing our page ranking, etcetera down - because they're perceived as duplicate content. (Drupal 8)
I'm looking at anything that is out there, but not sure if any of these cover what I need. Is there a simple way to set all urls containing /node/* to noindex, nofollow? Maybe a way in robots.txt?
Would simply adding this to robots.txt work?
Disallow: /node/*

As a side question, what are the ramifications of making such a change? Any issues I need to be aware of, protect against?
Or maybe there's another way people have solved this problem?

For Drupal8 and 9 what you need is simply this module: https://www.drupal.org/project/redirect. It will redirect all /node/* to its alias. For Drupal7: https://www.drupal.org/project/globalredirect


Drupal Migrate - Assign Roles I'm creating a Migration from our old website (non-Drupal) to our new Drupal website. On our old website, roles and role assignments were kept in 2 seperate tables. So far, I've written a simple UserMigration and a RoleMigration class. However, I'm in doubt how I should proceed for the RoleMembershipMigration.

In short: Should I manually load roles in a prepare function for the UserMigration, or should this be done in a seperate Migration class altogether? I'm inclined towards the first, since it is not actually a migration to a seperate entity.

I suggest to join roles and role assignements tables togother in your query of RoleMigration class,
in that case you will have these fields as source fields : role_id, user_id, role_name

now in UserMigration you just need to apply the dependency of the role migration on "roles" field :

$this->addFieldMapping('roles', 'role_name')
            ->sourceMigration('Role')
            ->defaultValue(drupal_map_assoc(array(2))); // authenticated user default value

Don't forget also that the key field of migration mapping should be the user_id field :

$this->map = new MigrateSQLMap($this->machineName,
        array('user_id' => array(
                'type' => 'int',
                'not null' => TRUE,
                'description' => 'User ID.'
                )
            ),
        MigrateDestinationUser::getKeySchema()
    );

Didn't test it but should work like that!


How to hide a block based on content type? I have a custom content type where when loaded, I want to HIDE (no show) a regions block. Been looking around trying to find the answer and have come up short. Ideally, I'd want to do it in a preprocess or something, not within a template. Tried accomplishing it with Context, but appears that only allows you to add blocks to regions, not remove them. Fairly new to Drupal, so bare with me.

Sadly, it is not yet part of Context to negate the context (that I am aware of).

You have 2 options (slightly different than the link mentioned by @Mołot):

Write your own context.  It's actually not that hard, and you can follow the general flow suggested in (this post)[http://dtek.net/blog/extending-drupals-context-module-custom-condition-based-field-value].
Use the built-in visibility settings on the block configuration page to enable the block on all content types but the one you want, and all pages desireable (e.g, user/*, views pages, etc.).


Vanishing Blocks/Menues I have a legacy site running Drupal 6.19, and today, I found out that the entire side bar had disappeared. I haven't run any updates, and no administrators have been on the site for a while, so I'm not sure what could have triggered this. Does anyone have any suggestions for how to reverse this?

I have gone into the /build/blocks menu, and the proper menu items are listed as being there (right sidebar region), and if I add a test item to any block region, it won't show up. The site is using a custom theme; however, the issue persists if I change themes the the default Drupal theme. I didn't see anything in the theme or global theme configs that would indicate a problem.

Thank you for you help.

The problem was fixed by my collegue when he MySQL. Unfortunately, I didn't find any errors displayed on screen or in the logs, so I'm not sure what happened.


How to hide node title for specific content type using template file I am trying to remove a node title on a specific content type (Core Article) using its template file.

I don't want to use preprocess_node() hook that it's pretty straight forward but not of my liking due to I want to organize all my edited templates in my custom template folder.

What I did is this:
I copied the node.tpl.php to my template folder under the folder "templates". I renamed that file to node--article.tpl.php. I edited the template file removing all the header section (which includes the title render function). Cleared the caches but the title is still there.

What am I doing wrong?

EDIT: Here is the code in my node--article.tpl.php

<article id="node-<?php print $node->nid; ?>" class="<?php  print $classes; ?> clearfix"<?php  print $attributes; ?>>
   <?php
      // Hide comments, tags, and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      hide($content['field_tags']);
      print render($content);
      ?>
      <?php
     if (!empty($content['field_tags']) || !empty($content['links'])):
      ?>
   <footer>
      <?php
         print render($content['field_tags']);
         ?>
      <?php
         print render($content['links']);
         ?>
   </footer>
   <?php
      endif;
    ?>
    <?php
      print render($content['comments']);
    ?>

PS: Sorry for the code styling but I guess html5 tags are breaking the lines in stack exchange editor.

Maybe you render article as full page then  $title rendered in page.tpl.php

you just need override your content type page template, I mean duplicate page.tpl.php ( if you use bootsrap sub theme go to  boostrap theme boostrap\template\system\page.tpl.php`  file to your subtheme template forlder and rename it to page--article.tpl.php and remove title form it.

I mean remove these lines from it

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

<?php print $title; ?>

  <?php endif; ?>

dont forget clear the cache


Adding custom data to the node object I have created a content type called providers and when editting said content types users can fill in extra information related to the content.
I have included said form fields using hook_form_alter, and the appropriate hook for _submit applied with it all working fine (saving to db etc)
Where I am stuck is I can access the data, by loading it via hook_ENTITY_TYPE_load call which allows me to access it in _form_alter but for some reason when viewing the node, I do not see the data.
Is there a specific way of loading external data on top of node object in d8?
below is how i load the data.
    /**
     * Implements hook_ENTITY_TYPE_load($entities)
     */
    function remittance_providers_node_load(array &$entities) {
      //loop thorough the loaded entities
      foreach ($entities as $key => $entity) {
        // if provider node type is being loaded add our data on top of it.
        if ($entity->bundle() == 'providers') {
          $nid = $entity->id();
          $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
          if(count($commission_data)>0){
            foreach ($commission_data as $ckey => $comm) {
              $entities[$key]->commission[$ckey]['amount_from'] = $comm->amount_from;
              $entities[$key]->commission[$ckey]['amount_to'] = $comm->amount_to;
              $entities[$key]->commission[$ckey]['commission'] = $comm->commission;
            }
          }
        }
      }
    }

I have installed devel and checked all its phases and I dont see it in there.

I have found preceding value array with [x-default] shows the values.
I presume this has to do with the translation module

function remittance_providers_node_load(array &$entities) {
  //loop thorough the loaded entities
  foreach ($entities as $key => $entity) {
    // if provider node type is being loaded add our data on top of it.
    if ($entity->bundle() == 'providers') {
      $nid = $entity->id();
      $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
      if(count($commission_data)>0){
        foreach ($commission_data as $ckey => $comm) {
          $entities[$key]->commission['x-default'][$ckey]['amount_from'] = $comm->amount_from;
          $entities[$key]->commission['x-default'][$ckey]['amount_to'] = $comm->amount_to;
          $entities[$key]->commission['x-default'][$ckey]['commission'] = $comm->commission;
        }
      }
    }
  }
}


Exporting custom configurations from Drupal After installing a Drupal7 site, I have made several configurations/customizations over time. Now I would like to export them somehow, in order to load them to another site. But the problem is that I don't remember exactly what I have done. The Features module does not help because you have to tell it exactly what to export, but I don't remember all the changes.

I know that this is a difficult problem on Drupal7, which is expected to be solved on Drupal8. But I am asking just in case that somebody knows any tricks that can help to solve it on Drupal7.

You can features module. So you can create a feature of several configuration and can use in other installation.

Sorry I missed the features part in question, which you already know.

I think features is the best solution for exporting configurations. other than features nothing is there for exporting all configurations without telling what to export.