How can I set per file access controls by role to files on a node I'm migrating a publications database from an old CMS to drupal 7 using the migrate module.  One of the requirements is that some publications (nodes of content type document) will be available to the public (anonymous users and everyone else) and some will be staff only (administrators, staff, and probably some higher level roles created for content editing).  Each publication can have an arbitrary number of associated files, each of which can also be publicly available or internal only (Same set of role based control).

How could I set this up?  So far my two possible solutions have been:

creating a different content type called files and using inline entity form to to associate thre file nodes with the publications.  This will allow me to ad a field for whether the file node is publicly available or not
Using the media module.  Unfortunately it appears that the Migrate Extras module that has media support doesn't support Media 7.2.x (As far as I can tell it is designed for 7.1.x).  I have tried installing Media 1.x but I have so far been unsuccessful at getting migrate to recognize the extra field as a destination field for migrate to write to.

The first thing to understand when you want to shield files from unauthorized access in Drupal is the difference between the Public and Private stream wrapper. By default files are uploaded in Drupal in a public directory and no matter what you do with access control on entities the files will be publicly available directly via the url to the file. So first make sure you setup Drupal to be able to serve files through Drupal via the Private file system (stream wrapper), instead of directly through the web server (public).
Take a look at "/admin/config/media/file-system". You can read more about this on Drupal.org.

In any case you will need an extra access control module (and/or custom code). If you don't use Media and only use the Private files stream wrapper you will be able to shield files per role using the Content Access module.

If you want Media not only for access but also for the other nice features it brings think about this: it will not solve your file access issue out of the box. And the Content Access can't help you anymore because it really only works for nodes and not for File entities. Because Media depends on File Entity (separate module since version 2.x) you are no longer required to create node types for documents that need to be fieldable, this is nice. But currently there are no good contributed modules I know of that add granular access control to file entities. So you will need custom code to manage access. I could help you out in this case, but I guess it should be a separate question.

Edit:

I extracted a custom sample module from a project of mine which adds role based permissions to File Entities (untested), see:
https://github.com/dmsmidt/drupal_file_entity_access


How do you join a custom table to a node from a field with hook_views_data() I have a custom table that contains (for simplicity) two fields:

id
client_id

On my node content type, I have an integer type field called: field_dashboard_id.  All my nodes have the field_dashboard_id set to ids from the custom table.  I have a content view that I would like to also display the client id from the custom table. (FYI I am able to create a view if I use Dashboard Entries instead of Content but I want to use Content and join to Dashboard Entries)

I tried the following code but when I try to add a relationship, I am not seeing my custom table in Views.

/**
 * Implements hook_views_data().
 */
function mydashboard_views_data() {
  $data = [];

  $data['mydashboard_site']['table']['group'] = t('Dashboard');

  $data['mydashboard_site']['table']['base'] = [
    'field' => 'id',
    'title' => t('Dashboard entries'),
    'help' => t('Contains a list of dashboard entries.'),
  ];

  $data['mydashboard_site']['table']['join'] = array(
    'node' => array(
      'left_table' => 'node__field_dashboard_id',
      'left_field' => 'entity_id',
      'field' => 'id',
    ),
  );

  $data['mydashboard_site']['id'] = [
    'title' => t('ID'),
    'help' => t('Unique Site ID.'),
    'field' => [
      'id' => 'numeric',
    ],
    'filter' => [
      'id' => 'numeric',
    ],
    'argument' => [
      'id' => 'numeric',
    ],
    'sort' => [
      'id' => 'standard',
    ],
    'relationship' => [
      'base' => 'node', // The name of the table to join with.
      'base field' => 'field_dashboard_id', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
      'extra' => [
        [
          'field'    => 'field_dashboard_id',
          'value'    => 'value',
          'operator' => '=',
          'numeric'  => true,
        ],
      ],
    ],
  ];

  $data['mydashboard_site']['client_id'] = [
    'title' => t('Client ID'),
    'help' => t('The client id'),
    'field' => [
      'id' => 'standard',
    ],
    'filter' => [
      'id' => 'string',
    ],
    'argument' => [
      'id' => 'string',
    ],
  ];

  return $data;
}

Update

Also tried the following:

$data['mydashboard_site']['table']['join'] = [
  'node__field_dashboard_id' => [
    'left_field' => 'field_dashboard_id_value',
    'field' => 'id',
  ],
];

'relationship' => [
  'base' => 'node__field_dashboard_id', // The name of the table to join with.
  'base field' => 'entity_id', // The name of the field on the joined table.
   // ID of relationship handler plugin to use.
  'id' => 'standard',
   // Default label for relationship in the UI.
  'label' => t('Example node'),
],

When you have a field you have a table for it with stored values, so you just add the fields table to your query
Like

/**
 * Implements hook_views_query_alter().
 */
function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   $query->addTable('my_fields_table');
   $query->addWhere(<condition group id>, '<table_column>', <value>, '<operator>');
   // These you can use to alter the behaviour for your condition group.
   //$query->setWhereGroup('OR/AND', <condition group id>);
   // This one is for the global group behavior.
   //$query->setGroupOperator('<OR/AND>');
  }
}


Show different fields when adding a content depends on the language i have a question about a multilanguage feature which i don't find. I have contenttype with many fields (about 20 fields). Now i want to translate this page in a few languages. My problem is that some fields (the content of the fields) are only visible for a specific language like italian for example.

So the first idea could be to add additional fields to the contenttype for the specific languages. In aspect to the code i would render the specific field depending of what language is selected on the page.

But in relating of adding a content this could be very confusing with many languages.

So my question is: Is it possible to show fields when adding a content depending on what language is selected for the new content. For example when i have a field which should only visible for the italian translation.

Is this a known problem?

If you have some specific fields which only should be viewed based on language , the best way to do that is by using page manager and panels .

Download and enable this modules
go to Structure -> pages
enable node_view
add a variant and select Selection Rules
now add a rule based on user->language and node->type
and now you can make a custom view based on language


Combining the Same Terms in different Vocabulary as one I have two vocabulary used by two different content type.

Category
Tags

However, the second content type does not use the Vocabulary Category. But there are nodes in second content type that has been tagged with same name in Category. So now I want to have the nodes of these same name be displayed as one.

That is
Category has term - TermA
Tags has term - Term A

Node of Type1 has been associated with TermA of Category and Node of Type2 has been tagged with TermA of Tags, but both these nodes should appear in one single taxonomy page as TermA. I am using Taxonomy Term Views.

How can this be done any ideas?

You should try putting both Category and Tags under a single master vocabulary. Then assign both Category and Tags as parents of the shared term. So you have:

Level 1: MasterVocabulary
Level 2: Category [parent:MasterVocabulary], Tags [parent:MasterVocabulary]
Level 3: SharedTermA [parents:Category, Tags], TermB [parent:Category], ...


drupal as mobile app backend Im currently using drupal 7 + commerce for online sales and I have a phonegap app that creates orders. I want to use drupal 7 via a the services module to sync the app sales data with the online store. My concern is speed as drupal requires a full bootstrap for each service call. Is there another recomended way to access the drupal 7 commerce database directly that would perform the crud operations faster?

Not sure if "faster" but I'd recommend the integration of Drupal Commerce and Phonegap (I'm guessing you're using DrupalGap already) if you're already using both: https://www.drupal.org/project/commerce_drupalgap

You've got plenty of resources there to get started such as the Commerce Services module.

It's up to you to decide where you need or not a full bootstrap of your backend, I'm thinking you need it to get advantage of user access, permissions and consistency check in your order status, but it depends a lot on your app and where  you're implementing the business logic. If you access the database directly, without any bootstrap is going to be faster, but the same way you build a drupal site, if you bypass Drupal to access directly to the database that'd be faster as well.


How to efficently use Drupal as a laboratory notebook and information management system? I am a chemo-informatics researcher looking to find user experiences and feedback on methods to keep laboratory notebooks on a computer and/or online using Drupal ( e.g. plugins to use, taxonomies).

How do you want to organize your information?  I would use a content type such as 'notebook_entry' with a taxonomy 'subjects' and/or 'projects' that allows free tagging of terms.

notebook_entry should use the body field for the bulk of your content.  You can add additional text/image/file fields for storing related information that can be displayed with the content.

I recommend using views to display your notebook entries.  You can create an argument in your page view with the taxonomy term or terms you've defined for the notebook_entry content type.  This will make the page only display entries related to that term.  You'll have to create a menu block filtered by the taxonomy to access your content.  It will list each of the taxonomy terms as links to your page view that displays your notebook_entries.  Create a list of terms and use the global text field to make a link to the path of your page view including the arguments.


Commerce price attributes doesn't work when I use commerce discount for products I used commerce pricing attributes in order to add extra fee based on a select box field. For example if user select black from color attributes, price increases 10$ and if user select white, price increases 5$ today, I have installed commerce discount module and defined a discount for all products.

But it seems price attributes doesn't work when discount is defined for product. Because by changing color in no change happened for price.

what is your suggestion to solve this problem?

I found the solution of this problem. In order to avoid this error, you must set order for your discount.

for the field order (with description : Discounts will be sorted by this value to be evaluated in that order.)
set the discount on 1 (or the lowest amount in the select box)

this will fix the problem.


View list of teasers wrapped in  instead of How can I view my teasers in <li> instead of in the default <div>? I find that changing the <div> to <li> in node.tpl.php doesn't work since <li> needs to be wrapped in a <ul> tag.

You could use the Views module to output an unordered list of teasers. You can use the HTML List display type, along with a Node: Teaser field.


Display field collection items together with nodes in view sorted by date I would like to create a view, which would list all the events of an organization (please look at the mockup). The problem is, that some of the are part of longer series, so I had to group them somehow. So now I have 2 content types (Event and Series of Events), the latter contains Field Collection field with multiple instances, which is used for sub-events. (Please see the scheme)

I use common date field for "Event" nodes and "Sub-event" field collection items, but I can't sort by it, because for "Sub-event" I would need to use relationship, which disables sorting of events.

So my question is: How would you create something like this?

I am using Drupal 7, Wiews 7.3 and latest version of Field Collection.

For better understanding of my problem, please look at following images (sorry, I can't post images because I'm new here):

Scheme

Mockup of view

I would strongly suggest to move away from field collection implementation. Because, Sub - Events are actually events and should be nodes. Right now they are becoming values of a Single Event by using field collection.

Try considering Entity Reference. Add a reference field called Parent Event to the event content type and make it reference to same content type. Make the field optional so that you can create root Events.

In future, above architecture will provide you lot of advantages. Hope you like it!


Biblio module: importing ris files, titles not importing even though mapped correctly I have ris files of citations to upload, and despite having titles mapped correctly at admin/config/content/biblio/iomap/edit/ris -- T1 goes to Title, I get nothing but "untitled" nodes. I am using version 7.x-1.0-rc7. Some other data seems to populate appropriately, but looking at logs, many things aren't, so it's more than just titles. I have a large number of errors for a number of fields along the lines of:

Notice: Undefined property: stdClass::$title in _biblio_ris_parse_line() (line 357 of C:\wamp\www\mysite\sites\all\modules\biblio\modules\RIS\biblio_ris.module).

Thinking there might be something wrong with the data, I created my own simple ris file and tried an example file that I found online. I had the same problems with all of them.

I tried the dev version and have the same problem.

Any help would be appreciated.

after finding this comment, I changed two lines in biblio_ris.module:

339 from

$node->biblio_pages .= ($tag == "SP") ? $data : " - " . $data;

to

$node->biblio_pages = ($tag == "SP") ? $data : " - " . $data;

and 357, from:

$node->$field .= $data;

to

$node->$field = $data;

It works.


How to change to another image when mouseover using Views? I need to change the big image "A" to "D" when mouseover thumbnail "D" in a view (using Views).

How can I do this? Preproces page or jquery in a custom text in view?

You can try Views Slideshow module with its ThumbnailHover slide feature. You can find its full documentation page in here.

Basically create a view with fields and a pager, set it as slider (Content: slide) and check Activate slide and pause on pager hover option.

For more details, see: What you'll need to crete a jQuery slideshow in Drupal.


How do I provide a page manager page override for my custom entities using ctools plugins I have a custom entity type implemented, this is essentially identical to what the Model module provides, with extra integrations.

I'm wanting to use panels and page manager to template my entity pages, much like how page manager provides the node_view which overrides the node/%node path, I want to override my custom entity paths.

What ctools plugins and hooks do I need to implement to gain this functionality?

We can achieve this quite easily by using node_view as a guide. First though you must implement hook_ctools_plugin_directory() in your module file to register the ctools plugins:

/**
 * Implements hook_ctools_plugin_directory().
 */
function my_entity_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'page_manager' || $owner == 'ctools' || $owner == 'panels') {
    switch ($plugin_type) {
      case 'tasks':
      case 'content_types':
          return 'plugins/' . $plugin_type;
      break;
    }
  }
}

This tells ctools that we are implementing plugins under the plugins directory inside our module folder and the plugins will be in their own directories. Since I am only implementing "tasks" I want to only return for that plugin type. The "task" plugin type is what we will use to implement our custom entity view.

After implementing this we just have to create the .inc file to implement our task. The file must be named name_of_plugin.inc, so for this we will use "my_entity_view.inc"

And here's the code for that, note that function names are made up of the following keys: module_name_plugin_name_hook(). I found it quite easy to follow this code, the hook_my_entity_task_tasks() is what all the other callbacks hang off. After implementing this, clear cache and your override should appear in /admin/structure/pages

<?php

/**
 * @file
 * Handle the 'my_entity view' override task.
 *
 * This plugin overrides my_entity/%my_entity and reroutes it to the page manager, where
 * a list of tasks can be used to service this request based upon criteria
 * supplied by access plugins.
 */

/**
 * Specialized implementation of hook_my_entity_task_tasks(). See api-task.html for
 * more information.
 */
function my_entity_my_entity_view_page_manager_tasks() {
  return array(
    // This is a 'page' task and will fall under the page admin UI
    'task type' => 'page',

    'title' => t('my_entity template'),

    'admin title' => t('my_entity template'),
    'admin description' => t('When enabled, this overrides the default Drupal behavior for displaying my_entitys at my_entity/%my_entity. If you add variants, you may use selection criteria such as my_entity type or language or user access to provide different views of my_entitys. If no variant is selected, the default Drupal my_entity view will be used. This page only affects my_entitys viewed as pages, it will not affect my_entitys viewed in lists or at other locations. Also please note that if you are using pathauto, aliases may make a my_entity to be somewhere else, but as far as Drupal is concerned, they are still at my_entity/%my_entity.'),
    'admin path' => 'my_entity/%my_entity',

    // Menu hooks so that we can alter the my_entity/%my_entity menu entry to point to us.
    'hook menu' => 'my_entity_my_entity_view_menu',
    'hook menu alter' => 'my_entity_my_entity_view_menu_alter',

    // This is task uses 'context' handlers and must implement these to give the
    // handler data it needs.
    'handler type' => 'context',
    'get arguments' => 'my_entity_my_entity_view_get_arguments',
    'get context placeholders' => 'my_entity_my_entity_view_get_contexts',

    // Allow this to be enabled or disabled:
    'disabled' => variable_get('my_entity_my_entity_view_disabled', TRUE),
    'enable callback' => 'my_entity_my_entity_view_enable',
    'access callback' => 'my_entity_my_entity_view_access_check',
  );
}

/**
 * Callback defined by my_entity_my_entity_view_my_entity_tasks().
 *
 * Alter the my_entity view input so that my_entity view comes to us rather than the
 * normal my_entity view process.
 */
function my_entity_my_entity_view_menu_alter(&$items, $task) {
  if (variable_get('my_entity_my_entity_view_disabled', TRUE)) {
    return;
  }

  // Override the my_entity view handler for our purpose.
  $callback = $items['my_entity/%my_entity']['page callback'];
  if ($callback == 'my_entity_page_view' || variable_get('my_entity_override_anyway', FALSE)) {
    $items['my_entity/%my_entity']['page callback'] = 'my_entity_my_entity_view_page';
    $items['my_entity/%my_entity']['file path'] = $task['path'];
    $items['my_entity/%my_entity']['file'] = $task['file'];
  }
  else {
    // automatically disable this task if it cannot be enabled.
    variable_set('my_entity_my_entity_view_disabled', TRUE);
    if (!empty($GLOBALS['my_entity_enabling_my_entity_view'])) {
      drupal_set_message(t('Page manager module is unable to enable my_entity/%my_entity because some other module already has overridden with %callback.', array('%callback' => $callback)), 'error');
    }
  }

  // @todo override my_entity revision handler as well?
}

/**
 * Entry point for our overridden my_entity view.
 *
 * This function asks its assigned handlers who, if anyone, would like
 * to run with it. If no one does, it passes through to Drupal core's
 * my_entity view, which is my_entity_page_view().
 */
function my_entity_my_entity_view_page($my_entity) {
  // Load my task plugin
  $task = page_manager_get_task('my_entity_view');

  // Load the my_entity into a context.
  ctools_include('context');
  ctools_include('context-task-handler');

  // We need to mimic Drupal's behavior of setting the my_entity title here.
  drupal_set_title($my_entity->label);
  $uri = entity_uri('my_entity', $my_entity);
  // Set the my_entity path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  $contexts = ctools_context_handler_get_task_contexts($task, '', array($my_entity));

  $output = ctools_context_handler_render($task, '', $contexts, array($my_entity->id));
  if ($output != FALSE) {
    //my_entity_tag_new($my_entity);
    return $output;
  }

  $function = 'my_entity_page_view';
  foreach (module_implements('my_entity_override') as $module) {
    $call = $module . '_my_entity_override';
    if (($rc = $call('my_entity_view')) && function_exists($rc)) {
      $function = $rc;
      break;
    }
  }

  // Otherwise, fall back.
  return $function($my_entity);
}

/**
 * Callback to get arguments provided by this task handler.
 *
 * Since this is the my_entity view and there is no UI on the arguments, we
 * create dummy arguments that contain the needed data.
 */
function my_entity_my_entity_view_get_arguments($task, $subtask_id) {
  return array(
    array(
      'keyword' => 'my_entity',
      'identifier' => t('my_entity being viewed'),
      'id' => 1,
      'name' => 'entity_id:my_entity',
      'settings' => array(),
    ),
  );
}

/**
 * Callback to get context placeholders provided by this handler.
 */
function my_entity_my_entity_view_get_contexts($task, $subtask_id) {
  return ctools_context_get_placeholders_from_argument(my_entity_my_entity_view_get_arguments($task, $subtask_id));
}

/**
 * Callback to enable/disable the page from the UI.
 */
function my_entity_my_entity_view_enable($cache, $status) {
  variable_set('my_entity_my_entity_view_disabled', $status);

  // Set a global flag so that the menu routine knows it needs
  // to set a message if enabling cannot be done.
  if (!$status) {
    $GLOBALS['my_entity_enabling_my_entity_view'] = TRUE;
  }
}

/**
 * Callback to determine if a page is accessible.
 *
 * @param $task
 *   The task plugin.
 * @param $subtask_id
 *   The subtask id
 * @param $contexts
 *   The contexts loaded for the task.
 * @return
 *   TRUE if the current user can access the page.
 */
function my_entity_my_entity_view_access_check($task, $subtask_id, $contexts) {
  $context = reset($contexts);
  return my_entity_access('view', $context->data);
}


How to assign a user to administer one content type only? I have created a content type "TestContent". I created view using the content type. I can add content using the TestContent and I can see the content just fine in view. And I am the admin. Now, I have created a role "David" and I have created a user "xpress". I also have assigned the user to the role.

Then in Admin > People > Permission: I have selected check box for 'David' for the below items:

David: TestContent: Create new content
David: TestContent: Edit own content
David: TestContent: Edit any content
David: TestContent: Delete own content
David: TestContent: Delete any content

I logged out as admin and logged back in as xpress but I did not see the add content, find content for the content type that he has permission. Note that this user only have the permission to add content, edit content, update content, delete content for the content type.

Can you please help?

Thanks.

The xpress is not an admin, right? So the xpress won't be able to see the admin toolbar. Have you tried accessing the link of node/add/testcontent, node/node-id/edit? was xpress able to access it? if yes then you need to provide a link/button for the xpress to see when he/she logs in. Then I think you need to use views to show the lists of TestContent where xpress can search/filter.


How to alter commerce checkout form in a custom module? I'm using commerce and want to alter the checkout form in a custom module to prepopulate certain fields and hide them.

However, I'm not able to do this using hook_form_alter() as well as hook_commerce_checkout_pane_alter().

Here's my sample code:

function MYMODULE_form_alter($form, &$form_state, $form_id) {
  global $user;

  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
      // Rename the button for example.
      $form['buttons']['continue']['#value'] = t('Overridden value');
      break;
  }
}

How can I edit fields that are displayed on checkout?
Is there some other hook I should use?

Thanks!

I think you're looking for commerce_checkout_form() (commerce_checkout_form_checkout doesn't exist as far as I can tell from greping Commerce's code):

function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

or

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}


hook_views_pre_render -> how to access variables I have a view of teasers, and would like to check the status of each node.
Using hook_views_pre_render (in the template.php file of the theme), I can access:

$view->style_plugin->row_plugin

Which gives me the output below (only first few lines printed, using debug):

entity_views_plugin_row_entity_view::__set_state(array(
 'entity_type' => 'node',
 'entities' =>
 array (
  0 =>
  stdClass::__set_state(array(
     'vid' => '19',
     'uid' => '1',
     'title' => 'My Node Title',
     'log' => '',
     'status' => '0',
     'comment' => '1',
     'promote' => '0',

However, I can't figure out how to access the status variable.

debug($view->style_plugin->row_plugin->entities());

produces a white screen, any variation that I tried either returned NULL or a white screen.

Any help greatly appreciated.

Install the Devel module if you haven't already and use dpm($view); to see the structure of the view, then you can drill down to the part of the variable that you wish to inspect.

The devel module will print the result of your dpm() in the message area as long as there are no syntax errors in your module crashing the site.

I have found drush cc all (Linux command line tool) to be useful in finding syntax errors though I suspect there is a better way.


How to replace value of text box? I have 2 input fields in my drupal form. When end user inserts some value in first input, I want to auto insert the second input field. How can I achieve this.

Here is my code.

input form element 1

// total fee of the payment schedule
    $form['fee'] = array(
        '#type' => 'textfield',
        '#title' => 'Fee Amount:',
        '#default_value' => (isset($fee_details->fee)) ? $fee_details->fee : '',
        '#maxlength' => 5,
        '#required' => TRUE,
        '#description' => t('Fee amount'),
        '#id' => "fee",
        '#element_validate' => array('element_validate_integer'),
'#ajax' => array(
            'callback' => 'replace_fee_instalment',
  'wrapper' => 'replace_textfield_div',
),
    );

Input field 2nd is

 $form['amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Instalment'),
    '#title_display' => 'invisible',
    '#default_value' => ($amount) ? $amount : '',
        '#maxlength' => 5,
        '#element_validate' => array('element_validate_integer'),
  );

I think u need to use javascript for this.
on the keypress event handler for the first textbox, u can get the text of the first textbox and update the second textbox using javascript itself


how do display 404 while the url didn't exits I add a view contains three display page,and the page urls are:

questions
questions/my
questions/unanswered

but when I visit the url questions/s12dsdd ,It display the questions page list all questions,how to display a 404 page ? I found none settings in views.

of course we can handle it in code,but not a good one....

other desciptions:

  What he asks (I believe) is how to have 3 displays in one view and with [placeholder], [placeholder/versionone], [placeholder/versiontwo] URLs respectively and get a 404 on [placeholder/somethingrandom]. The second part of the URL does not seem to be an actual argument such as %nid. It's just a literal representation within the URL of what the display is meant to provide. :) @magtak

You can create two views. In one, using questions as URL, you add "Content: Nid" as contextual filter, and use the following settings for that contextual filter.

In When the filter value is NOT in the URL

Select Display all results for the specified field

In When the filter value IS in the URL or a default is provided

Select Specify validation criteria
As Validator, select Content
As Action to take if filter value does not validate select Show "Page not found"

The other view, using questions/mine as URL, would use "Content: Author uid" as criteria, and use a default value taken from the user currently logged-in.


composer install error I can't install anything because of this error:

  [RuntimeException]
    Could not scan for classes inside "/app/vendor/symfony/serializer/src/" which does not appear to be a file nor a folder

and subsequently:

  Could not scan for classes inside "/app/vendor/symfony/yaml/src/" which does not appear to be a file nor a folder

I navigated to that directory and the src folder is indeed missing...

I'm using Lando and switch the PHP to 7.1. I tried deleting the vendor directory and rerunning lando composer update and lando composer install but get the same errors.

Could be and over lap of composer requests. This example is for Pantheon resipe but it may help https://github.com/lando/lando/issues/340


Apply a promition only on a product variation I have a Drupal Commerce product with two variations.

Variation A - 18 euro - SKU 123
Variation B - 30 euro - SKU 234

Is it possible to apply a promotion only on Variation B?

I am using Drupal Commerce 8.x-2.4.

You need to implement you own promotion condition plugin. Theres a condition plugin defined in commerce_product module in Commerce module since 2.0 release but I recommend you to use latest stable release. Check this class Drupal\commerce_product\Plugin\Commerce\Condition\OrderItemVariationType thus it only checks for variation type (aka bundle), you can easily write your own checking specific product variation instance. Also worth checking OrderItemProduct condition plugin I think you need a mix from both. This plugin is located in the same namespace than the first one.

Update

There's a feature request for that see this link. Thanks to @bojanz!


Personal Contact Forms What is the best way to get a 'Contact User' form on nodes like an ebay-ish 'Contact Seller' simple form?

I tried Contact / Contact Forms module, but I do not want a Sitewide Contact form to be accessible (don't want to use it) and I want Mollom/Captcha integration and sending limits for anonymous users.

I thought maybe I could do Webform, but I can't see a way to make the recipient dynamic (node author, for example).


Use Subdomains as variable with Domain Access I'm new to Domain Access module. It seems it is built to allow you to run different sites off the same database. I'm looking for something more simple than that.

I want to the subdomain title to be included in the site name. I want a content type to be assigned to different subdomains and for that content to be the only content of it's type visible on the same subdomain.

Aside from that, everything else on the site should remain the same. Theme, users, layout, etc.

How can I best do this with DA module? Is it possible to use the domain as a variable (for use in views, panel's context and a token for the site name)?

I did this by installing Domain Access module. When skimming Domain Access module's documentation before, it seemed extremely complicated. However, the documentation is geared towards you learning all about how it works. The actual steps to install are more than a regular module, but not too complicated.

It allows me to restrict content to a specific domain and to have different site names for each domain.


Events showing on a calendar is radically different formats With event nodes imported using the Feeds Importer. How might I get the Jan 1 event to appear only on January 1st?

These events shown below on Jan 1 and 4 are all day events. Their individual date formats are listed below. The dates entered in both seem to be the same, but the difference in the rendering is baffling.

Additional information: Based on a helpful comment below. Here is what the Inspector shows in Firefox.

Jan 1 event, should not span two days

(full size image)

Jan 4 event with proper rendering

(full size image)

Well I half-way solved my the issue by changing a Multi-day event to a single column. I have some more reading and research to do on importing calendar events but for now, the rendering is correct.

This setting is found in the Views Format box by clicking Settings next to Format: Calendar.


Will the site load slower when using a sub-theme of a sub-theme? In Drupal, you have a base-theme, and maybe a sub-theme. That sub-theme can also have another sub-theme.

Will Drupal be slower when using 3 themes, where each of them is a sub-theme of the previous one, or doesn't this affect the performance?

TL;DR Have as many sub-themes as you want, it's not a problem.

Longer answer All types of inheritance, theming or otherwise, will have a performance penalty, and really all logic that you perform will have that effect; However

With proper caching enabled, only the very first request that uses the sub-sub-theme, is actually going to notice a difference. After that you will have aggregated css/js files from all three (or more) involved themes, and all of this becomes a non-issue until you clear the cache, after which you will again need to aggregate the files once.
With a pretty big generalization, the performance cost is roughly going to be linearly proportional to the number of changes you make. So if you don't make a lot of changes, you won't see a big effect.

Generally speaking, I suggest you approach the problem the other way around. Organize your theme/solve your problem in a way that is efficient for you as a human. Then worry about how to make it efficient for a machine only when necessary.

Since your site isn't written in assembly, your entire site is a huge performance problem, but in the vast majority of cases, a cpu performing literally trillions of calculations in a second makes that a non-issue.


How do I reset URL for Product Display when replacing the main product? (instead of having an increment added to the URL) I am having trouble with URLs after replacing items by a delete/re-import. The site uses Pathauto module.

I am adding content to a Drupal Commerce site using Feeds. I had uploaded the Product Variations and then Product Display for one product type. I realized that there were several mistakes with the CSV file and decided to start from scratch.

I deleted the original products by going to Products > Manage Products. From the "List" tab, I selected all of the products and chose "Bulk Action" >> "Delete". The products were deleted from the website, but the URL was incremented by a "-0" and the original now returned a "404" error.

Desired: www.XYZ.com/product/widget

vs.

Less than desired: www.XYZ.com/product/widget-0

How do I return the Product Display to the "widget" URL without the "-0"?

If I try to override it by manually making the update on the Product Display, I get an error message that indicates that URL is already taken.

I would like to clean this up for SEO. Please advise.

Thanks,
keb

I am not sure why this happens in Commerce Kickstart, while it does not happen with regular Drupal. Almost as if the product's path are cached or something, but clearing all caches after deleting a product did not change the outcome. But I did find an easy solution.

You can fix that by deleting your Aliases, go to /admin/config/search/path/delete_bulk

And then regenerating them


"Content Type Edit/Add" gives Whitescreen, no errors loged, what to do? I am running a Drupal Commerce Kickstart 1 on top of it (D7)site on localhost/xampp (1.7.7).

Now:
When I go to Content Type (/admin/structure/type), and click Edit on a given   type or New Content Type, i get the white screen or a server 500 error.
I can access manage fields and manage display on the same page.
When I go to drupal error logs, there is no trace of the error.
Neither can I find a trace of the problem in /opt/lampp/log/error_log.
Tried to increase allowef script time / php memory limit in php.ini - no result.

The site works without problems on a remote testing server, and has been  working without problems for a long time locally. So most probably it's local configuration, but I am not sure what to do.

Maybe some of you have an idea about what can I do?

OK, resolved. Thanks for your help,  Triskelion - thanks to you, I understand  xampp better.
There were two things
1) xampp giving no error messages. After looking in vain for error messages, I upgraded to xampp 1.8.0, and when I tried to get to the page that caused problems, I got a full error message.

 Additional uncaught exception thrown while handling exception.Original ODOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {system} WHERE type = &#039;theme&#039; OR (type = &#039;module&#039; AND status = 1) ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 165 of /opt/lampp/htdocs/twotrees/includes/module.inc). Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT ff.* FROM {filter_format} ff WHERE (status = :db_condition_placeholder_0) ORDER BY weight ASC; Array ( [:db_condition_placeholder_0] =&gt; 1 ) in filter_formats() (line 409 of /opt/lampp/htdocs/twotrees/modules/filter/filter.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 209 of /opt/lampp/htdocs/twotrees/includes/session.inc).

Still, no messages in error_log. Where should I look for them?

2) I searched through the web, and found similar problems for example [http://drupal.org/node/1542432]. It turned out this is a XAMPP mysql memomry limit problem. I changed the value 'max_allowed_packet' to 100M in 'my.cnf'.

My site works now. I was really scared!


Change $_rendered output? In a node I get the values of CCK fields as $ array or $_rendered as the rendered view of the field. How can I change the $<field_name>_rendered from its default way of rendering?

The Custom Formatters module will help you quickly and elegantly. Here is a quote about it (from the module's project page):

  ... allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.


"Access Denied" to the Admin on Old and New Install There was an access denied issue that I could not get past with my current test drupal install. I installed another drupal instance with a new db and still get this access denied error trying to get into the Admin area. This is not a cpanel, it is a server that is being setup for me.

Does anyone have ideas I can work through to get this resolved?

Does the admin have any special permissions that it needs to "chmod" etc... areas of the drupal site?

Thanks

Are you login as an admin. I mean UID = 1 ?
Try to reset the super user password and loggin again.

DRUPAL 6 and below: UPDATE users SET pass = MD5('givememypasswordback') WHERE uid=1;
DRUPAL 7 - https://drupal.org/node/1023428

Also check error logs if you think its an internal permission issue.


Commerce Fee not being added to order total sent to payment processor I have followed the Commerce Fees module's instructions found at https://www.drupal.org/project/commerce_fees:

DOCUMENTATION

    Go to admin/commerce/config/fees and add a new fee type
    Add a rule at admin/config/workflow/rules
        Event: "Apply a fee to a given order".
        Set the conditions.
        Action: "Apply a fee to an order".
            Entity data selector: "commerce-order".
            Fee: Your fee type.
            Set amounts, currency and taxes as necessary.

Notice: if using fees based on payment type, be sure to move the payment type pane to a screen before the review pane on admin/commerce/config/checkout so that customers can see the fee before accepting.

The Fee shows up in the cart contents on checkout but that fee is not added to the order total that is sent to the payment processor not show in the orders view. It's like the fee is not actually added to the total, except for in the cart content view on the checkout page.

Any idea of what I am missing?

Take a look for the issue https://www.drupal.org/project/commerce_fees/issues/2191191, maybe a patch can help you.


Customizing menu link output (add badge) I am new to drupal. I want to customize menu link

Top

All Posts

Discussed

to

Top

All Posts42

Discussed

Just add 42 next to "All Post" menu link.

This is the function you'll need:
https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

That allows you to overwrite the standard theme function. You could do an if statement to check for that specific menu link ID and do a custom output.

You'll need to put that in template.php within your custom theme and replace "theme_" in the function name with the name of your theme


Choose theme depending on the USER_AGENT How do I use the mobile theme if the $_SERVER['HTTP_USER_AGENT'] is mobile, and use the desktop theme if it is desktop?

I would suggest you to use browsecap module to detect what browser users use and switchtheme module to switch to correct theme depending on the browser they use.


naming convention for .tpl.php in drupal 7 for custom content type I have created content type named basepage and have created content test
My page url is

  ?q=basepage/test

what should my .tpl.php page name
like (node--1.tpl.php)

Overriding node.tpl.php for a specific content type is very simple.  The naming convention is node--machinename.tpl.php. For machinename, use the machine name of the content type with underscores replaced by hyphens. You can inspect the machine name if you navigate to Administration → Structure → Content types.  If you just want the override to apply to a single node (as opposed to all nodes of this content type), add the path replacing all slashes in the path with a double hyphen.

Provided you want to override the node template for path test, your template should be named:

node--basepage--test.tpl.php

No extra actions are required. Just create it (usually by copying it from the theme's node.tpl.php to node--basepage.tpl.php), modify it and place it inside the themes templates/folder.

Provided you want to override page template page.tpl.php based on the content type being displayed, the naming convention is the same, but you need to do some extra legwork:

Open the template.php file in your theme for editing.
Look for a function called THEME_preprocess_page (replace THEME with the theme's name).
If this function already exists, you will need to add your code to it inside an if-statement that goes at the end of this function, just before the closing bracket  Otherwise, if it doesn't exist, you'll need to create a new function.

This is how the function should look like:

function THEME_preprocess_page(&$vars) {
  // If the function already exists, just leave the code here intact, and add
  // the three lines below to the end.
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

Now, copy the theme's page.tpl.php to a file named page--machinename.tpl.php and place it inside the themes templates/folder.

Provided you want to override the page template  for path test, your template should be named:

page--basepage--test.tpl.php

for Drupal 7.


Multilingual Valid Path (Domain Access) I have a path controlled by page manager & domain access selection rules.

Let's say I'm on the Main (US) version of the page, and I need to know of the spanish version of the page is valid.

/contact-us

/es/contact-us

I've tried things like drupal_valid_path, drupal_lookup_path, etc.

The only option I've found is to do something like
menu_get_item()
Then hack the global language, call the callback from menu_get_item with

//hack global language here
$router_item = menu_get_item($path);
$page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
if (MENU_NOT_FOUND != $page_callback_result) {
   //url is not valid
}
//set global language back to original

Is there a simpler more generic way to programmatically do this? If there were some function like drupal_valid_path that would just say if the path results in 404 or not, that would be great, though I haven't found something like that yet.

We use the Link Checker modules on our sites. This would scan all links and give a report back as to which are broken, if any. I don't see any reason why this would not work on any site, including multi lingual.

Whether or not you use the module, you should be able to look at the code to get an idea of what functions and logic it's using to create similar functionality, if you're looking to do it programmatically.


How to override formatting for a CCK field? I have a CCK field called "stock". I dont want visitors of the website to see the value of "stock". I want them to see either "In Stock" if the value is more than 0, or out of stock if the value is less than zero.

Any idea how I can do that without actually editing the node display template?

Depending on the type of the field you are using, there are template files for those as well e.g. a number field (field--number-decimal.tpl.php). that way you would only have to override the field template, rather than the node template.


Panel with a view that is filtered dynamically by taxonomy term I'm using D7 with the panels3 and views 3.

I've got a view of medical procedures which are categorized by medical specialty. I have doctors becoming members of the site and, using profile2, I'm having them choose a specialty from that some tax vocab. I have a view of these procedures and I want it to be filtered by the specialty(ies) that the logged in user has in their profile. i.e. I want only doctors who selected the 'surgeon' specialty to see procedures also tagged with the 'surgeon' term.

I've got a view content pane set up and I have a page created with page manager which holds this in a panel but I just can't figure out how to configure Contexts to get the filtering to work.

In the view's configurations under pane settings -> argument input I have selected "From Context". As the Contextual Filters I have chosen: Has taxonomy term ID.

Please help!!

:)

To allow panels to provide the context, Under the pane settings, set the 'Required context' to 'Term ID' and besure that the 'Context is optional' setting is unchecked.


How to print alt or title field image in twig node template? I want to print alt or title field image file in node twig template Drupal 8. I tried use {{ node.field_images.entity }} to debug get value title or alt but in class \Drupal\file\Entity\File not function get those ! I saw {{node.field_images.entity.fileuri}} in link

So how to used {{node.field_images.entity}} to get value alt or title file images ?

Thanks !

The alt and title properties are stored in the image field, not in the file entity. You can access them by replacing the entity property with alt or title:

{{ node.field_image.title }}
{{ node.field_image.alt }}


Print the location or filename of an uploaded file from a custom content type I'm trying to figure out how to print out the file path and the name of the file uploaded from a custom content type. I have my template all setup and everything printing how I need to, the last thing is I just need to be able to print out the path or at least the name of the file from the upload attached to the content.

I tried using:

{{ node.field_name.value }}
{{ node.field_name.url }}
{{ node.field_name.content }}

The file field is an entity reference field, you can get the first file entity with .entity:

{{ node.field_downloads.entity.filename.value }}
{{ node.field_downloads.entity.uri.value }}

And access the fields of the file entity as usually.

If you have more than one file in the field:

second file:
{{ node.field_downloads.1.entity.filename.value }}
third file:
{{ node.field_downloads.2.entity.filename.value }}


Get custom block type image field in Display Suite twig field I have a custom block type.
I have a link field and image field.
I want to combine those fields so the image is wrapped in the link.
I created a Display Suite twig field.
What do I use to show the image? Ideally the image as rendered in Manage Display, but as long as I can show the image with a certain image style, I'd be very happy.

Here is what I have already tried:
{{ file_url(node.field_career_highlight_image.entity.uri.value) }}
{{ file_url(content.field_career_highlight_image['#items'].entity.uri.value) }}
{{ file_url(block_content.field_career_highlight_image.0['#item'].entity.uri.value) }}
{{ file_url(node.field_career_highlight_image['#items'].entity.uri.value) }}
{{ block_content.field_career_highlight_image.alt }} - shows alt, just experimenting, so wondering why this didn't work for the image
{{ content.field_career_highlight_image }}
{{ block_content.field_career_highlight_image }} - white screen
{{ block_content.field_career_highlight_image.0 }}
{{ block_content.field_career_highlight_image.0.value }}
{{ block_content.field_career_highlight_image[0] }}
{{ block_content['#block_content'].field_career_highlight_image.value }}
{{ content['#block_content'].field_career_highlight_image.value }}
{{ content['#block_content'].field_career_highlight_image }}

Thank you

{% set image_uri = block_content.field_feature_row_image['#items'].entity.uri.value %}

OR with a .0
{% set image_uri = block_content.field_feature_row_image.0['#items'].entity.uri.value %}

If not, try
{{ file_url(block_content.field_career_highlight_image.entity.fileuri) }}

If still no dice, then give this a shot. In /sites/default/settings.php add:
// Override default twig method whitelist.
$settings['twig_sandbox_whitelisted_methods'] = [
  // Defaults:
  'id',
  'label',
  'bundle',
  'get',
  '__toString',
  'toString',
  // Additions:
  'url',
];

and then in your field twig put
{{ block_content.field_career_highlight_image.url }}


Create 2 separated taxonomy pages with views I have 2 nodes type "Article" and "Page", I also have 2 taxonomy for each node type are "Taxo 1" for Article and taxo 2 for "Page", is there any way to create 2 seperated views so,

with "taxonomy/term/%" for Article I have grid views

and

"taxonomy/term/%" for "Page" I have "Unformated List",

beside 2 node types have alot of different fields.
Is there any way to handle that?

Your template file name should be like this -> taxonomy-term--tid.tpl.php
Source


Drupal rendered page for directory root, followed by static pages? I have a directory that I want to load through the Drupal system, which of course is fine with clean URLS:

  /my-dynamic-page/

However at this directory I then want to serve static pages

  /my-dynamic-page/static1

When I add a folder for /my-dynamic-page/ to the server, this now bypasses the Drupal system. While the static pages now work, when you try and load /my-dynamic-page you get a Forbidden error. This is because the Drupal system has been bypassed (there is a physical folder now) so the system looks for an index file.

How do I overcome this?

Add your own .htaccess file under the my-dynamic-page and my-dynamic-page/static1 with only this in it:

DirectoryIndex index.html index.htm


How to set value to login form's submit via themename_form_alter I have theme_form_alter function, I want to set input submit value with it too

function ivanco_form_alter( &$form, &$form_state, $form_id )
{
    if (in_array( $form_id, array( 'user_login', 'user_login_block')))
    {
        $form['name']['#attributes']['placeholder'] = t( 'Email' );
        $form['pass']['#attributes']['placeholder'] = t( 'Password' );
        $form['name']['#attributes']['title'] = t( 'Введите email, указанный при регистрации' );
        $form['pass']['#attributes']['title'] = t( 'Введите пароль' );
        $form['submit']['#default_value'] = t( 'Принять' ); // this line doesnt work((
    }
}

Buttons and Submits (yes, they are different things in Form API) does not have default value. All you can set for submit is: #access, #after_build, #ajax, #attributes, #button_type (default: 'submit'), #disabled, #element_validate, #executes_submit_callback (default: TRUE), #limit_validation_errors, #name (default: 'op'), #parents, #post_render, #prefix, #pre_render, #process, #submit, #states, #suffix, #theme, #theme_wrappers, #tree, #type, #validate, #value, #weight

As you can see, no #default_value. As user is not supposed to be able to change that value, it's simply #value - no need for defaults.

Read more on Form API Reference.


Want to add tabs from /user/* pages to other pages When I go to any "user" pages on my site in /users/* I have menu tabs for the various pages in that section, like below.

I want to add the top level of tabs to another set of pages. Specifically, I am trying to setup the Private Msg module, which has everything in /messages/* When someone is reading their messages, I want to have the same top level of tabs they see in /users/*

You can use Tab Tamer module to arrange tabs at your user/% location or some where else too. You can change orders or enable/disable as per your requirement.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.

  Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully
  when javascript is disabled.


Hierarchical Select Question I don't know if its possible at all but I need something like what is seen in this demo for one of the menus with Hierarchical Select module. This works fine when I use it for a vocabulary with hierarchical terms but don't know how to use it for generic Drupal menus.

You have a separate submodule for using Hierarchical Select with menus, the same as for taxonomy terms.

So, for taxonomy terms you have Hierarchical Select Content Taxonomy submodule (hs_taxonomy), and for menus you have Hierarchical Select Menu (hs_menu) submodule, which you should use in your case.

Click on 'Show config' links on the demo page you have mentioned to see the details.


How to avoid max execution timeout when importing a lot of nodes programmatically? I am creating a content synchronisation module. I have a UI that allows a user to import nodes from a remote site.  They enter the site url and web service endpoint, along with some other configuration options, and the program will go and fetch the nodes and import them into the database using node_save.

I received a max timeout error while importing 357 nodes:

Fatal error: Maximum execution time of 30 seconds exceeded in D:\xampp\htdocs\drupal-7.15\modules\pull_content\pull_content.module on line 1188

So, I increased the max execution time to 360 but after 360s it timed out and I got the same error.  I know that the processing hasn't frozen because I can see the nodes going into the node table at a rate of about 3 or 4 every 10s.

I don't want to keep endlessly increasing the timeout as there is the possibility that I may have to import 1000 nodes or more at one time.

Is there any way to avoid this error message other than increasing the max execution time? Maybe by running things in a batch?  Or should I just make the max execution time really large?

Yes, there is a way! It's built into Drupal core, and it's there for this exact reason and purpose. You need to use the Batch API. Batch lets you, well, perform operations in batches across page loads. It automates the carrying of information between these page loads and helps you to show a nice progress bar to the user.

See:

Batch operations reference
The Examples module (which contains a batch_example module)
Countless online tutorials


Image_style_url with [default_image] I am trying to print a commentator's avatar picture in the comments.tpl.php

<img src="
        <?php
            if ($picture) {
                print image_style_url('comment_picture', $comment->picture->uri);
                ?>"

which works as desired. However it doesn't post the default_picture if the user does not have a profile picture uploaded.

I've tried using [default_image] but then nothing happens

<img src="
        <?php
            if ($picture) {
                print image_style_url('comment_picture', $comment->picture->uri);
             } else {
                print image_style_url('comment_picture', [default_image]);
            }
                ?>"

Use below code in else condition...

$user = user_load($comment->uid);
print theme('user_picture', array('account' => $user));

OR

$filepath = variable_get('user_picture_default', '');
$default_image = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => '', 'title' => ''));
print $default_image;


How can I prevent user pages being created for users with a specific role? I have various users on a Drupal site.

Internally, I differentiate between users by user role (e.g. 'member', 'non-member').

Is it possible that if a user has a certain user role, that I prevent them from having a user page that is visible to the public?

E.g., if user 10018 has user role 'non-member', how can I prevent user page (site.com/user/10018/) from being visible to the public and users of role 'member'?

Basically, I don't want to delete 'non-member' users unless it's absolutely necessary - but I don't want them to have user pages that are visible to anyone other than site admins.

Thank you!

I suppose you could use the Rules module to create a redirect (possibly to 404) when someone tries to view the user page of a user with a specified role.


How do I avoid a template get rendered from a preprocess function? I have a multilingual site with two view blocks, and a custom template for them.

I want to render both blocks in language A, but only one in language B.
Is it possible to avoid that one of them is rendered on a language basis, from the preprocess function?

Why preprocess?

Blocks have language visibility. Just configure that block to be shown only in a specific language.


"Manage Display" for taxonomy term does not allow management of the name field There is a taxonomy with an image associated. It is supposed to display with the image and no title. However, in going to the "Manage Display" section for this taxonomy, the name field is not displayed at all.

Searching for this has proven futile. I can manually remove it by modifying display code but then that leaves no way to change its display from the CMS.

Why is the name not manageable as part of the display?
Is there some way to manage the taxonomy term display including the name?

Why is the name not manageable as part of the display?

Because it's a 'property' of the entity, not a 'field' as such. The 'Manage display' tab is really a 'Manage field and pseudo-field display' tab, it doesn't take properties into account.

This is completely standard and is inline with all core entities. For example, if you check the display settings for one of your node types, you'll notice the 'Title' isn't available there either.

  Is there some way to manage the taxonomy term display including the name?

The simplest way is to manage it with templates, as you've already suggested (and again, exactly how it would be done for all other core entity types).

You could always implement hook_field_extra_fields() to expose the term name as a pseudo-field on the display forms; but bear in mind you'll have to link up the logic to hide the titles from the template file yourself, as the core taxonomy module doesn't have that functionality.

I think Add entity properties to "Manage Fields" form is a relevant D.o discussion, there's even some sample code to get you going.


Drupal 7 - Add two menu items with the same path but different query string On Drupal 7, there is a difficulty adding two or more items to a menu which are having the same URL but a different query string.

For example, when I add two similar paths:

node/add/alert?kind=regular
node/add/alert?kind=news

Only one of the links is randomly displayed. So frustrating...

Any ideas of how to by bypass this issue?

What I did is add the redirect module.

Then I created custom redirects for those menu items, e.g. "node/add/alert/kind/regular" goes to "node/add/alert?kind=regular".

No need for custom hook_menu programming.
It worked! But why doesn't drupal provide it work out of the box???


How to define custom messages in Drupal 7 I want to show a custom message to user after he/she adds a new content of a specific type in Drupal 7. If I change the '@type %title has been created' to what I want the message will change for all content types.

How can I do it? Is there any module to define messages for different actions?

I just did this the other day, it's a bit of a hack, but I couldn't find another way.  The basic premise is to get and clear all current messages, loop through and call drupal_set_message() on all of them over again, changing the one you want:

<?php
/**
 * Submit function for the message node form.  Check for new message notification and change it.
 */
function mymodule_message_node_form_submit($form, &$form_state) {
  $node = $form_state['node'];
  $t_args = array('@type' => node_type_get_name($node), '%title' => $node->title);
  $replace_message = t('@type %title has been created.', $t_args);

  // This call will get all messages and clear them from $_SESSION
  $messages = drupal_get_messages('status');
  foreach ($messages['status'] as $message) {

    if ($message == $replace_message) {
      drupal_set_message(t('Thank you your message has been sent successfully.  We will be in touch shortly.'));
    }
    else {
      drupal_set_message($message);
    }
  }
}
?>


Changing URL alias for search module action I'm struggling to make the Search module recognize the presence of a URL alias that I created for 'search/node'. It however stubbornly uses the default path.

In my template I use something like:

function mytheme_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id){
  case 'search_form':
    $form['#action'] = drupal_get_path_alias('/search/node'); // = '/' . drupal_get_path_alias('search/node') does not work either
    break;

  }
}

When the results are displayed, the URL still reads:

/search/node/[search-string]

Does anyone know whether the path is hard-coded and omits the alias function?

I've had a lot of misery trying to customise the URLs for the search module so I feel your pain!

It's a submit handler that redirects to the search/node page so you'll need to add your own handler to override the redirect:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#action'] = 'search';
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
  else if ($form_id == 'search_box_form' || $form_id == 'search_theme_form') {
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
}

function MYMODULE_search_form_submit(&$form, &$form_state) {
  $default = search_get_default_module_info();
  $form_state['redirect'] = str_replace("$default[module]/", '', $form_state['redirect']);
}

That code comes from a module who's sole purpose is to allow users to search at search/string rather than search/node/string so you'll probably need to change a couple of things to match your alias settings, but it might help start you off.

Here's a bit of extra code that's used to override the search URL using a hook_menu_alter():

function MYMODULE_menu_alter(&$items) {
  drupal_static_reset('search_get_info');
  $default_info = search_get_default_module_info();
  if ($default_info) {
    foreach (search_get_info() as $module => $search_info) {
      $path = 'search/' . $search_info['path'];
      unset($items[$path]);
      unset($items["$path/%menu_tail"]);
    }

    $items['search/%menu_tail'] = array(
      'title' => 'Search',
      'load arguments' => array('%map', '%index'),
      'page callback' => 'search_view',
      'page arguments' => array($default_info['module'], 1),
      'access callback' => '_search_menu_access',
      'access arguments' => array($default_info['module']),
      'type' => MENU_CALLBACK,
      'file' => drupal_get_path('module', 'search') . '/search.pages.inc'
    );
  }
}

It basically removes the menu items for the search path and replaces them with a single one. It's only useful in very specific conditions (i.e. when you've only got one search type enabled) but it's something to go off at least.


Cannot log in as Drupal admin I have installed phpMyAdmin.

I can see the admin user (uid=1) in each of the two databases

I have reset the password using;

update users_field_data set pass=Password("new_password");

I can see that the pass hash has changed confirming a changed password.

I got to http://mysiteURL/user/login and enter the admin name (shown in users_field_data table) and the new password.

Upon submit I only get the border of the login name field changed to red.

I have cleared the sessions table and removed the cache_entity data for uid=1 with no change in behaviour.

yum list | grep -i php

returns a lot of php packages from version 5.6 to 7.3. I am not sure if this is normal but php seems to work since both websites load and I can use phpMyAdmin and phpinfo() returns php7.2.7

I have checked error logs for each website, nginx, drupal and php with no obvious errors.

Curiously drush cli does not work i.e.

./drush uli

sh: module: line 1: syntax error: unexpected end of file
sh: error importing function definition for `BASH_FUNC_module'
Drupal\Core\Database\ConnectionNotDefinedException: The specified database          [error]
connection is not defined: default in
/app/jbi2/core/lib/Drupal/Core/Database/Database.php:361

I have now resorted to reviewing the Drupal 7 installation steps.

Thanks in advance for any well informed replies.

Drupal 7 and 8 do not use a straight md5 password hash.  The hash includes a site specific "salt" string that is created with you set up the site.  This is in the settings.php file generally.

To use SQL to set a password, you will need to use the password-hash.sh file which is located in the core/scripts directory.

Run this from your web root directory like ./core/scripts/password-hash.sh` newpassword

Use the string created as the value for your password in query with no Password function.

Re:Drush

You might try running it in the same directory as your site's settings.php file.  With D8, some versions of drush have a hard time finding this unless you run it there or set up an alias for the site.

Older version could find it settings.php based on your location (e.g. in a subdirectory of the site directory or would use the sites/default).  But newer Drush versions need more information.


How do I download a specific version of a module? The official documentation for Drupal Console says that the arguments for drupal module:download are the following.

drupal module:download [arguments] [options]

is there an argument or option to specify the dev/beta version of the module?

We can use following code to download latest stable release :

drupal mod modulename --latest

if we want to select a specific release other than latest then we can go for

drupal mod modulename --unstable

hope this will help.
https://docs.drupalconsole.com/en/commands/module-download.html


How to get commerce billing info fields I was wondering how I can get a list of the available checkout fields of Drupal Commerce like:
Billing information:

first name
last name
[custom field]
country
...etc.

So i'm only interested in listing the available field names, not the actual values. With code in my custom module.

Does anyone have a suggestion how to do that? Thanks!

If I understood you correctly, you want to get a list of the form fields that a user is presented. The isn't really a clean way of doing that, since Drupal forms can be complex. The best solution however would be to generate the form and traverse it. To generate the form, you could do something like this:

$form_state = array();
$fields = array();
$profile = commerce_customer_profile_new('billing');
field_attach_form('commerce_customer_profile', $profile, $fields, $form_state);
// $fields is now the customer profile form.


Display a Quicktab content in Colorbox pop-up Drupal 6 I have a quick tab (Drupal 6) which contains three tabs. One of it has a table which is larger in size. Hence, when the third tab was clicked I need to show the third table as a Popup using Colorbox.

I have that table as a node Page and I want to display that node as a Popup.

If the Quicktab content is a node or any other internal entity, you can do this by using the colorbox-load class and appropriate href. If you aren't able to alter the links in any of the preprocess functions, you can use JS to accomplish this and use Drupal.attachBehaviors() to add the colorbox functionality.


Why does "Read more" link not show up on view, but "Add new comment" does? As said in the title, I'm having a problem with the "read more" link.
I made my own view (wie-zijn-we-pagina) and content type (wie-zijn-we-) and am trying to add a custom "read more" and "add new comment" link to it. The code that I'm using gives me the correct custom "Add new comment" link but the "Read more" link doesn't work. At first it didnt even show up.

My code:

function ap_hogeschool_theme_preprocess_node(&$variables){
$variables['content']['links']['comment']['#links']['comment-comments'] = FALSE;
if($variables['view'] && $variables['type'] == 'wie_zijn_we_')
    {
    $variables['content']['links']['node']['#links']['node-readmore']['title'] ='

';
    $variables['content']['links']['comment']['#links']['node-readmore']['html'] = TRUE;
    $variables['content']['links']['comment']['#links']['comment-add']['title'] = '

';
    $variables['content']['links']['comment']['#links']['comment-add']['html'] = TRUE;

}
}

I don't know if the part where i call the view and content type is correct... I'm still a new drupal user.

An image of what i have:

An image of what in need to have:

Could somebady please help me along?

You have a mistake on your code. Instead of $variables['content']['links']['node'] you wrote $variables['content']['links']['comment'].

Corrected code:

function ap_hogeschool_theme_preprocess_node(&$variables){

  $variables['content']['links']['comment']['#links']['comment-comments'] = FALSE;

  if( $variables['type'] == 'wie_zijn_we_' && $variables['view_mode'] == 'teaser' ){

     $variables['content']['links']['node']['#links']['node-readmore']['title'] ='

';
     // Mistake was in this line:
     $variables['content']['links']['node']['#links']['node-readmore']['html'] = TRUE;
     $variables['content']['links']['comment']['#links']['comment-add']['title'] = '

';
     $variables['content']['links']['comment']['#links']['comment-add']['html'] = TRUE;

   }
  }


How to call site name in PHP block? I have a block in my footer that I currently use to display a copyright message using PHP, like so:

Copyright © <?php echo date("Y"); ?>

I'd like to add the site name to that code snippet, dynamically instead of typing the name. How can I do so?

So the end result would be:

Copyright © <?php echo date("Y"); ?> [[[php code to display site name goes here]]]

Thanks!

You can use variable_get() to get the site name, but you shouldn't use it directly in the template file or you could break caching.

Instead, define a preprocess function in your theme's template.php file:

function MYTHEME_preprocess_page(&$vars) {
  $vars['site_name'] = variable_get('site_name', 'Default');
}

Then you can use this in the template file:

Copyright © <?php echo date("Y"); ?> <?php echo $site_name; ?>

Before doing that, though, check whether you already have $site_name available in page.tpl.php. Some themes add it for you, some don't.


Remove html entities in forum topic I am using drupal advanced forum, due to migration from phpbb to D7 forum I noticed there are some HTML entities shown in my forum topic. I need to handle this in the tpl file. Can you please let me know where to implement it.

This sounds like data transformation problem; the import didn't format the HTML entity title data on import. Instead of trying to code around the problem in your template, you should reformat your node titles.

Run a code snippet (e.g. drush scr myscript.php) that can fix the formatting on your nodes. Something like:

// @TODO: Retrieve your list of imported node nids in the $nids array
$nids = array(4, 5);
foreach ($nids as $nid) {
  $node = node_load($nid);
  $node->title = html_entity_decode($node->title);
  node_save($node);
}


Why am I urged to include my source files via files[] instead of using include_once? What is the reason of using the .info file to declare the files used from the module, instead of including them at runtime?

From Writing .info files (Drupal 7.x):

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file (...). When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.

So it only makes sense to add a file to the files[] array, if that file contains declarations of classes or interfaces and is not included manually (e.g. by calling module_load_include()).


Is there a way to create custom page in panels with path "/search"? Is there a way to create custom page in panels with path "/search" ?
I need to replace default drupal 7 search page with my own views page. But I can't because this path is already exist (duplicate).
Also I can't disable "Search" module, because I use in views filter providet by search module "Search: Search Terms".
Any advise will be appreciated.

If you have Search Module enabled, you should see built-in search node panel page.


How to hook into an attachment? I have a field loading hidden in an attachment view and I need to hook into that attachment to alter the output of the field.

It involves PHP and I'd rather hook into template.php rather than download some PHP module to store PHP code in my database.

I've tried hooking into theme_views_pre_render but I can't find my attachment, I can only modify the $view->attachment_before output.

That, plus I can't actually obtain the field values in this hook?

So how can I hook into a field value in an attachment?

An attachment is just like any other view (except that it is attached to other views), and so can be manipulated as such:

In template.php:

function THEMENAME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name) && $vars['view']->name == 'VIEW_NAME' && $vars['view']->current_display == 'ATTACHMENT_NAME') {
    foreach ($vars['fields'] as $id => $field) {
      if ($id == 'FIELD_NAME') {
        $vars['fields'][$id]->content = 'new value';
      }
    }
  }
}

Remember to clear your cache.


Gallery related to the article I managed to create a gallery and show it under a page (creating a view of type page).

What I really need is having one different gallery associated for each article, so I created a view of type "block", but the showed gallery is always the same, while it should related to the current article.

You need to add to your view the Contextual Filter: Content: NiD

Click Provide Default Value and select Content ID from URL


How to run code after hook_node_delete has completely run? I have a node to which I have a number of images attached through the usual content type image field mechanism.  The attachment is done correctly, such that when I delete the node, the images are also deleted.

My problem is that these images are held in a subdirectory, which is not deleted by the file deletion process, and I end up with a bunch of empty and useless directories littering my file system.  I tried deleting the directory with hook_node_delete(), but this fails because Drupal hasn't yet gotten around to deleting the images when that hook gets called, and the rmdir() function I was using to delete the directory fails because the directory isn't empty.

So: Is there a hook I can call that will run after the files have been deleted?  I suppose I could write my own code in hook_node_delete() to delete the files and then the directory, but I'd rather not hack around the architecture like that, if possible.

You may want to look into hook_field_attach_delete().  This runs after all fields have been removed from a node/entity.  So, if all the file fields (and the actual files) have been removed, and all of them in such a node are all in one directory and they are the only files in that directory, removing that directory in this hook should succeed.


Images in sites/default/files are not allowed to be seen anymore Today I realized, that all images, that are located in sites/default/files/fields may not be accessed anymote, neither are they shown in my articles nor may I see them in the browser (e.g. http://daniel-stein.com/node/210#). All I get is a 403 - no permission - error. The folder and the files within are all set to 744 (and I also tested 777). I have not found any permissions I could adjust and I am not sure when this started or what I changed in that moment. Maybe it was around the time I changed from buedit to ckedit but the switch back was also useless.

Ok, so I found a solution that worked for me.

In the process of investigating in this problem and the fact why it does not appear on other Drupal installations I have running on the same server I messed up the permission settings on my server. In order to reorder things, I installed the module https://www.drupal.org/project/security_review - it produces a list with potential security problems of your Drupal installation. I worked myself down the list solving the issues one by one. I am not sure if this was the point in the beginning but after I changed the permissions of the .htaccess-file in sites/default/files to 444 (readonly) suddenly my images were accessible again.

For your reference, here are a lot of other approaches you can try if the one I presented is not helping: https://www.drupal.org/node/1170440


How do i increase length of existed link title field in Drupal 8? I want to increase the length of existed link title field. As matter of fact already have data in that field and don't want to lose.

Any suggestion? How can I do that nicely in Drupal 8.
thanks

What you can do is this:

Create new link field
Update configs, like form display, views etc to use new field.
Migrate all the data to the new field, in an update hook. Example code could look like this (Assuming link field is on a node)

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'node_type');
foreach ($nodes as $node) {
  $node->new_field = $node->old_field;
  $node->save();
}

Delete old field.
Done

Alternately you can update field field, manually update the SQL tables etc, but this is quite tricky to do properly. If you want to go down this road you should take a look at the entityDefinitionUpdateManager.


Taxonomy hierarchy via separate dropdowns I am building a view that requires users to select from a drop down menu containing a list of taxonomy terms, which will then filter the view results based on those terms. So far, so good.

I want to make the dropdown menu with only all of parent taxonomy terms of a specific vocabulary so that when one of the parent terms is selected, a second drop down menu shows all of the children of the selected term.

How can I accomplish this, preferably without an extra module? I will consider any means to accomplish this goal.

More specifically, I am building a view based on states and counties, and want users to first select a state and then select from the list of counties for that state.

You probably won't be able to do that without some custom code.

An existing module for the purpose is Simple hierarchical select:

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

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

There is also the more full featured module Hierarchical select


How to configure the CONTEXTUAL FILTER in a View for Rules? I want to make a component that receives a user as parameter, and will then do something with some of that user’s content.

That something is: delete nodes of contenttype FICHE that have a due date in the past and copy the content of that node to a variable_mailbody. Send the variable_mailbody when all records of that user are processed. (After testing the component, it will be called in a viewloop of all active users, so it will be executed for all members, one after another, periodically.)

I know how to make a view that selects all nodes with a due date in the past. This will give me all the nodes to delete, but I want only those for this respective user, because I do not want to send a mail for each deleted item.

So how to configure contextual filter to limit the result to only the nodes of the user for which the component is being executed? Or should I tackle this in a different way?

Make 2 rules-views on NODES, on both views add relationship to author, on first view only add one field UID using relationship and aggregation, filter your nodes as needed, this will display only one user for several nodes that matched your ‘delete criteria’. On second view add only one field NID (with no aggregation) and same filter criteria as first view, in this view add a contextual filter on UID. On both views set  row variable settings in middle column, make all fields and parameters as Data Type = Integer, do not send them as objects, it does not work well.
Now in your component or rule, first add your first view-loop (UIDs), fetch user by id using your UID variable, inside that loop, add your second view (NIDs), set contextual filter as your variable UID, loop all those nodes, fetch each node by id usig your NID variable, and do your stuff, outside second view loop, but inside first view loop send your email. On second view loop you can add node-content to a variable previously added to hold all node-data for that user and included in your email body.


RDF mapping of a single node? Is it possible to create RDF mappings for a single node in Drupal 8?

I've enabled the module RDF and also downloaded and enabled RDF UI and its submodule - RDFUI_builder.

I've already created RDF mappings for some content types but when I edit a single node there is no option to edit its fields.

Some consider it a best practice to create RDF mappings per a given content type but to also include a unique vocabulary for the Homepage node.

I suggest creating it for the Homepage by giving it a unique content type (you could clone an existing one and change by need).

This solution saves overriding the already RDF-mapped previous content type of the homepage node; An overriding that can be tiresome to create and maintain.


geofield map theme markers I wonder if (and how) it is possible to have dynamic markers on a geofield map created by views. I'd like to have different colors of markers depending on a field value, and also a count of matches from a proximity filter direktly printed into the markers (not the popup). I'm using the google map layer and cannot find an option to even have (e.g.) green instead of the default red markers. Google search on this topic didn't wield any solutions.

I'm using the following modules: address field, geofield, geophp & geofield maps for map display.

Has anyone done this already? Thanks!

An instruction how to do this can be found on:
http://purewebmedia.biz/article/2014/08/01/create-multi-layer-map-drupal-7-openlayers-2x


Choosing from multiple default images What is the best solution for letting users choose from an array of default images when creating a node with a teaser image field?

The functionality I'm thinking of is similar to
https://drupal.org/project/avatar_selection
, but for creating any node.

The best for your case is Media. You can use a existing library or you can upload a new image and many other stuff.


Using flags to approve user account I'm using the flag module to provide my site admins with a simple "Approve Membership" button. When the button is clicked the system automatically associates the new user account with several roles and then changes the accounts status from "Blocked" to "Active.

So far the roles assign perfectly. The problem is that I can't figure out how to switch an account from Blocked to Active using flags.

Any ideas?

You can switch users from blocked to active upon flagging with the Rules module, which integrates with Flag.  Create a rule on the Event "User is flagged with approval flag."  Then add the action Unblock a user  (under Users in the list).


How to trigger an event when node is saved? I am trying to execute a piece of code when a node is saved. I am using hook_node_update, but it's never triggered when updating a node. Here is my code:

function custom_node_update(Drupal Core Entity EntityInterface $node) {
 // Logs a notice
 \Drupal::logger('custom')->notice("entity was updated");
}

What is wrong with my code?

The parameter passed to code had syntax error.

The correct code will be

function custom_node_update(Drupal\Core\Entity\EntityInterface $node) {
  // Logs a notice
  \Drupal::logger('custom')->notice("entity was updated");
}


Hide page title on specific path I want to hide page title on a specific path, but I want to retain the page title between "title" tags in the header. I want the title to be exist in title bar of the browser, but that should not be displayed in the page for specific paths.

Is that could be done using theme_preprocess_page Or any other specific hooks out there ?

Is there any module?

What else could be done to prevent page title from displaying on the page in specific paths?

There are a number of ways to do this, but this answer focuses on the considerations for handling things programmatically in custom code.

The <title> variable (for the browser title bar) is calculated as part of the "html" theme template, while the <h1> title variable (printed at the top of the page) is calculated as part of the "page" theme template. So in this regard if you implement some preprocess logic on the "page" output, you can remove the title from the page display while still keeping it intact for the browser bar. This is of course in contrast to more heavy-handed approaches, like calling drupal_set_title(), which impact static variables that may apply on a more global scope.

The trick to this is that, in most cases, your "page" template title is not actually initiated as a theme variable until template_process_page(), which runs after any preprocess functions. So you may not see a "title" variable within the scope of your own theme_preprocess_page(). The appropriate snippet from template_process_page(), where the title is added, is just:

if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}

Given this background, you could manipulate the title variable direct by either:

Setting $variables['title'] to an empty string within your theme_preprocess_page() (based on whatever conditions your desire). This way it will be set and therefore won't get filled-in via the template_process_page() code that runs later, but it will still be empty when page.tpl.php template renders things.
Implementing a theme_process_page() function, which will run after template_process_page(), that unsets/nullifies the title variable set there.

You could also avoid touching the title variable itself altogether by just setting a boolean flag, like $show_title, in a (pre)process function. Then you would need to modify your page.tpl.php template with a very basic boolean check of $show_title that only prints the title <h1> if TRUE. That method is discussed in this post.

With any of these options you isolate your primary conditional logic, which can be as detailed as you want (should you discover new title visibility needs later), within the theme preprocessing layer. This will help keep things more maintainable for the long run.


Hide single menu item from users without a specific role (without 3rd party module) I have a menu and would like to hide a specific item if the currently authenticated users doesn't have the "editor" role, which i created.

Since this is such a small thing, i would like to achieve that without the use of a 3rd party module.

update::

This is not about security, I just want to hide the item regardless of the linked node's permission. In my specific case I'm even linking to a public node and just want to hide the menu item as long as the user hasn't the "editor" role.

Use hook_menu_item_link to alter menu items. See below example:

function mytheme_menu_item_link( $link ) {
  if( $link[ 'title' ] == 'My Account') {
    return '';
  }
}


Rules offset with a fixed time I'm trying to set data value for a date field. The value is 7 days after a node was created. This works fine but I would like to have a fixed time of 6pm as the time value. Currently the time is set as the same time as the created node. How do I fix this?

The Drupal way was easier than I thought.

I changed it to direct input and used

now +7 days 18:00:00

and it's working.


Configuration Menu Items How can I add a section to the admin/config route and populate it with my own modules? In Drupal 7 it was easy, but I can't figure it out now in Drupal 8. The closest I can get is adding my modules to the Configuration Menu List that appears in the sidebar.

module.links.menu.yml

module.admin_settings:
  title: 'Module Admin Title'
  description: 'Module Admin Desc.'
  route_name: my_module.my_module_settings
  parent: system.admin_config

You should assign your menu link to one of the specific groups on /admin/config by setting the correct path. You can find most of them in system.links.menu.yml and it usually matches the path, e.g. parent: system.admin_config_media.


How to use Solr Handlers when sending requests from Drupal I'm using Solr 4.10.2 and Drupal 7.X, I have the Apache Solr Module Framework operating and sending the requests to Solr From Drupal. Currently when we perform a search, Drupal builds the query and sends it to Solr. Solr just executes the query and returns the results without using it's internal handlers which can be configured through SolrConfig.xml.

I would like to know if there is a way to just send the searched terms (without building a query) from Drupal and let Solr use the internal handlers declared in SolrConfig.xml to handle the request, build the query and then return the data?

The reason for this is we have been working on trying to boost some results when we perform a search (we want exact match first & fuzzy search results after) by changing the "weight" of some fields.

We know that from Back Office we can use the "Bias" function to boost some fields but this is too limited for what we are trying to achieve.

We also know we can change the query sent from Drupal directly from code side by using hook_apachesolr_modify_query() but we prefer changing as little code as possible and using the SolrConfig.xml /handlers which we already have configured to return the results as we want.

Ok, we figured out how to do this. In order to choose the handler that is being used by Solr while sending a request from Drupal, we have to edit hook_apachesolr_query_alter() and add the following code:

$query->addParam('qt', 'MyHandlerName');

We did some extra coding to allow us to change the handler directly from back office in order to be able to switch handlers without touching the code.


Why can't I disable a module? I installed Drupal Chat just to try it out. I couldn't get it to work and now I can't disable the module.

In /admin/modules, the check box is selected but not enabled. i.e. it is active and I can't deactivate it.

Can anyone help me?

(and, once disabled, how can I un-instal it?)

Update: I forgot to mention that there are no dependencies on the module.

usually if conventional uninstall wouldn't work i'd try clearing the module's entry from system table removing tables from the module installation (after backing up the data) clear the cache and reinstall.. hope it works for you ...cheers!!


How to hide blocks based on menu_name I've a site with a main menu, and submenus as block. If I'm on node "50" I want to hide every submenu, except the submenu with the link to node "50".

Question: How can I hide a block based on it's variable menu_name (I think it is this variable) without javascript.

Here's a wireframe, so you can get an overview.

I use Menu Block for this purpose.  You can specify which levels of which menu you want to show, and the blocks display conditionally depending on the current active trail.


Replacing a 'Teaser'-themed node in a View its it's 'Full Content'-theme using ajax in Drupal 7 So, basicly, I have a Drupal 7 view that's displaying Teasers of Nodes.

WHen a user clicks this teaser, I want the node to load it's "Full Content"-content instead, and I would like this to be done using Ajax.

I've looked around a lot but I can only find solutions for Drupal 6, and many good solutions at that, but I'd love some help with figuring this out in D7!

Thank you!

You can try using the jQuery load method.

$('#teaser').load('node/exampleid #node-container');

Replace your teaser data with full-text.

The second method is to load hidden full-text with teaser in view; then, via jQuery on click method, just replace teaser by hidden-text.


How do I integrate postal code search? How to integrate number search along with string search in drupal 7?
As of now,I was able to implement string search i.e a user can search via name,place etc but I want to  implement number search so that users can search via postal code, date of birth, etc.

You can use Postal code module to integrate postal code in your site.

Please note at the moment the module only support:

USA, Canada, UK, Germany, France, Italy, Australia, Netherlands, Spain,Denmark, Sweden, Belgium, India, Poland


How to properly specify context for Drupal behaviours I have this code that does not work. I know why it does not work - first time page is loaded 'context' is all page and jquery easely finds '.view-SPECIFICVIEW .view-content'. After AJAX 'context' has changed and it is now just '.view-SPECIFICVIEW' and inside that there is no class '.view-SPECIFICVIEW' and therefore nothing happens. Script works if I remove '.view-SPECIFICVIEW' from find(), but then all views are selected.

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $(context).find('.view-SPECIFICVIEW .view-content').masonry({
          columnWidth : 300,
          gutterWidth : 20
        });
      }
    }
})(jQuery, Drupal, this, this.document);

I would like to have this code to work with '.view-SPECIFICVIEW' and also I would like to know how code changes if multiple, different specific views should be targeted.

Just stop using context in this case.  I've been playing around with jQuery Masonry and I've not needed to use it.

(function ($){
  Drupal.behaviors.myModule ={
    attach: function(context, settings) {
      $('.view-SPECIFICVIEW .view-content').masonry({
        columnWidth : 300,
        gutterWidth : 20
      })
    }
  }
})(jQuery);

FYI, I'd also take a look at the Masonry recommendation to use the imagesLoaded plugin if there are images in your view.  It takes a LOT of future frustration out.


Difference of two Dates in Computed Field fields: (Date to - Date from) = Total Number of Days

How can I compute the total number of days between two dates using Computed Field?

Here is a sample snippet (to be used in Computed Code PHP Block inside of a computed field)

$food_date_value = array_pop(field_get_items($entity_type, $entity, 'field_food_date'));
$food_date = new DateObject($food_date_value['value'], '');
$current_date = new DateObject('now', '', 'm/d/Y');
$entity_field[0]['value'] =$food_date->difference($current_date, 'days');

field_food_date is a date in the Unix Timestamp format (another field in my content type). DateObject can then be used for doing any date calculations.