How can I add markup above the table in a custom module? I am working on a Drupal 8 custom module which renders pages as shown in the following image.

So far, I am able to build the table and my code is the following.

  public function dexp_layerslider_list() {
    $header = [
        'ID',
        'Name',
        'Action',
    ] ;
    $results = db_select('{dexp_layerslider}', 'd')->fields('d', [
        'id',
        'name',
    ])->execute();
    foreach ($results as $row) {
        $url = Url::fromUserInput("/admin/dexp_layerslider/". $row->id . "/edit");
        $row->name = (Link::fromTextAndUrl($row->name, $url));
        $editslides = Url::fromUserInput('/admin/dexp_layerslider/'.$row->id.'/editslides');
        $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides))->toString();
        $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
        $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides))->toString();
        $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
        $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides))->toString();
     $tmp =  [
            '#type' => 'inline_template',
             '#template' => '{{ link1 |raw }}, {{ link2 | raw }}, {{ link3 | raw}}',
                '#context' => [
                         'link1' => $editslides_link->getGeneratedLink(),
                         'link2' => $exportslides_link->getGeneratedLink(),
                            'link3' => $deleteslides_link->getGeneratedLink(),
                            ]
                    ];
        // Row with attributes on the row and some of its cells.
     $rows[] = array(
            'data' => array($row->id,$row->name,$tmp )
                );
        }
     $table = array(
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#sticky' => FALSE,
        '#empty' => t('No slider created yet.'),
         );
        for($i= 0; $i
            $table['#rows'][$i]['data'][2] = $tmp;
        }
    return $table;
 }

How do I add a "Add slide" and "Export slide" links?

You have multiple solutions to achieve what you want

Using #prefix

 $table = array(
  '#prefix'=> '
my link
',
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

A better way to do this is

 $table = array(
  'links' => [
     '#type'=> 'container'
     'link_one'=> [
        '#type' => 'link',
        '#title' => $this->t('Add slide'),
        '#url' => Url::fromRoute('my_route'),
      ],
   ],
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

Add module definied actions: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-actions


How i can show the value of submitted form I have implemented normal form in drupal 7 , and i want to show the value it is retrieve by this functions (submit)

function parkingcalulator_form_submit($form, &$form_state) {

    $parkingType = $form_state['values'] ['parking_type'];
    $totalCost = 0;

    $from = strtotime($form_state['values']['from_date']);
    $to = strtotime($form_state['values']['from_time']);

    $difference = $to - $from;
    $timeInHours = floatval($difference) / floatval(60*60);

    //// if the start time is greater than the end time set the error here
    if ($timeInHours <= 0 )
    {
        form_set_error('$timeInHours',t('Time inserted error'));
    }

    if ($parkingType == 0) {
        // Normal
        if ( $timeInHours < 200 )
        {
            $totalCost = calculateShortTermParkingCost($timeInHours);
        } else {
            $totalCost = calculateLongTermParkingCost($timeInHours);
        }
    } else if ($parkingType == 1) {
        /// Valet
        $totalCost = calculateValetParkingCost($timeInHours);
    }

     return $totalCost;

}

it does not show the value of  (return $totalCost) ,how i can get the value on it

First of all the validation should not be done in the form submit function. It should be done in a validate function.

For example in your case there would be an additional function which would look like

 function parkingcalulator_form_validate($form, &$form_state)
 {
    $from = strtotime($form_state['values']['from_date']);
    $to = strtotime($form_state['values']['from_time']);

    $difference = $to - $from;
    $timeInHours = floatval($difference) / floatval(60*60);
    if ($timeInHours <= 0 )
        {
            form_set_error('from_time',t('Time inserted error'));
        }
    }

If you want to display the result with in the form, after submitting then you would add a value to the form_state with in your form_submit function such as

$form_state['total_cost'] = $totalCost;

And then tell the form to rebuild by adding this code again in the form_submit function

$form_state['rebuild'] = TRUE;

Now with in the function you create the form the variable $form_state['total_cost'] would be available. you place that in a form element of the type markup. something like this

if(isset($form_state['total_cost']))
{
$form['total_cost'] = array(

  '#markup' => t('Total Cost is : ') . $form_state['total_cost'],

);
}

The if condition is used so that it is not executed in the first stage when the form is not submitted as the value is not yet there in the variable. The above code should go in the form function in your case parkingcalulator_form($form, &$form_state)

For more details examples you should refer the Examples Module which has a submodule called Form Examples.


Create a module to access a 3rd party API and store the keys in the database I am new to Drupal module development, and have searched but haven't found any tutorials or guides on how to create a module to do the following:

Access a 3rd party API via a form
Store the user API key in the database
Access the API key when the user uses the 3rd party API via a form
    submission

Can someone show me how or point me in the right direction for at least steps 2 and 3?

You can handle the storage and retrieval of the API keys in the database via the Drupal API functions:
variable_set and
variable_get.

To store the key (step 2):

variable_set('mymodule_api_key', $api_key);

To access the key (step 3):

$api_key = variable_get('mymodule_api_key', t('-key not set-'));

Where "mymodule" is the short name of your custom module.

As for a comprehensive example: There are many bridge modules in the Drupal.org repos that connects to an external service using an API and authenticates using API keys. One example of this is Mollom.


Views - Date Filtering (Panels?) this is one of the most confusing tasks I've been asked to accomplish in Drupal. I have a Content Type called Latest News that has a Date field (not the creation date, a date that represent's the new itself and may be used for the filtering process).

What I need is the following page:

_________________________
|  _____  ____________  |
|  |   |  |          |  |
|  | A |  |    B     |  |
|  |   |  |          |  |
|  |___|  |          |  |
|         |          |  |
|  | C |  |__________|  |
|                       |
|_______________________|

Where A is a list of Latest News nodes' titles, B is the node itself (smells like Panels), and C is a menu that contains dates spanning from 2004 to now (dynamic preferably), that acts as a filter to view A.

Whenever a user clicks on a date on C, the titles in A are filtered (much like an exposed filter), and the node display on B should change to the topmost item of the currently filtered list on A.

The current displaying node's title should be highlighted.

If the user has filtered A to display news from 2011, clicking on one of them should retain the filter, and simply display that node.

How would you go about doing this?
I will be editing this question if more clarification is needed. Thanks in advance.

Here's what I would do.

First I'd enable the CTools Page Manager and Views content panes and create a page (admin/structure/pages) for that display that has arguments in it's path.

Then I'd create three views with display type "content pane": one that lists nodes based on a contextual filter (A), one that shows only one node (B) and one that lists dates (C).

Then I'd create the column layout in the page's content and would provide the arguments with Page Manager.

Here's a really nice tutorial from NodeOne that addresses most of the tricky parts here:
http://dev.nodeone.se/en/learn-page-manager-part-5-views-content-panes-basics


Add content type field programmatically My module provides a configuration form which allows to select a content type and on submit 2 new fields will be added to the selected content types.

I want to add these fields to the content types programmatically and I tried this using hook_entity_bundle_field_info but the fields don't get saved.

How can I save the fields? And how can I delete the fields (if the user changes the content type in the configuration form)?

You can use this example from the node module.

This adds a body field when a content type is created and at the same time configures the display modes (view modes and form modes):

core/modules/node/node.module:

/**
 * Adds the default body field to a node type.
 *
 * @param \Drupal\node\NodeTypeInterface $type
 *   A node type object.
 * @param string $label
 *   (optional) The label for the body instance.
 *
 * @return \Drupal\field\Entity\FieldConfig
 *   A Body field object.
 */
function node_add_body_field(NodeTypeInterface $type, $label = 'Body') {
  // Add or remove the body field, as needed.
  $field_storage = FieldStorageConfig::loadByName('node', 'body');
  $field = FieldConfig::loadByName('node', $type->id(), 'body');
  if (empty($field)) {
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => $type->id(),
      'label' => $label,
      'settings' => ['display_summary' => TRUE],
    ]);
    $field->save();

    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');

    // Assign widget settings for the default form mode.
    $display_repository->getFormDisplay('node', $type->id())
      ->setComponent('body', [
        'type' => 'text_textarea_with_summary',
      ])
      ->save();

    // Assign display settings for the 'default' and 'teaser' view modes.
    $display_repository->getViewDisplay('node', $type->id())
      ->setComponent('body', [
        'label' => 'hidden',
        'type' => 'text_default',
      ])
      ->save();

    // The teaser view mode is created by the Standard profile and therefore
    // might not exist.
    $view_modes = \Drupal::service('entity_display.repository')->getViewModes('node');
    if (isset($view_modes['teaser'])) {
      $display_repository->getViewDisplay('node', $type->id(), 'teaser')
        ->setComponent('body', [
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ])
        ->save();
    }
  }

  return $field;
}

Edit: Code updated from 8.8.x to remove deprecated functions, see change record https://www.drupal.org/node/2835616

The field storage itself is not added or deleted because it is shared between all content types. You have to do this once when you install the module. The easiest way is to put a yml file for the storage in /config/install. Example from the node module:

core/modules/node/config/install/field.storage.node.body.yml:

langcode: en
status: true
dependencies:
  module:
    - node
    - text
id: node.body
field_name: body
entity_type: node
type: text_with_summary
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: true
custom_storage: false


where is the source code for "Powered by Drupal" Someone told me the footer text "Powered by Drupal" in Drupal7 is provided by theme_system_powered_by(), which is turned into a block by system_block_info() and system_block_view(). I wonder in what file(s) these functions can be found. Thanks a million.

Here's the API documentation for all your needs:

theme_system_powered_by()
system_block_info()
system_block_view()

Also, please note that modifying the output of theme_system_powered_by() should be done using a theme hook from your theme code. If you wonder how to achieve this, this might be a relevant article for you.


Module that allows to compare, edit and/or merge revisions At the moment I have installed on my site the Diff module, which allows me to compare the content of 2 revisions but I need a module that allows me to not only see the differences between revisions, but also to edit both revisions at the same time while comparing them and to copy the content of a field to either revision (like WinMerge or many other diff/compare applications)

I am well aware that revisions shouldn't be used this way, but i'm using the revisions system to allow unregistered users to post edit suggestions about my site's content so being able to copy only certain fields (since a suggestion might include both correct and incorrect data for different fields) in the current revision would save me a lot of time

I doubt there is an out of the box solution. But maybe you can Views of Pending revision items per content item using Views and if needed the Revisioning module and maybe Rules. Eg, somehow you want to list stuff with pending changes and Revisioning+Rules seems to be able to do that:

  Rules: when Triggers won't do, use the event-condition-action paradigm
  of Rules. More complicated to set up than Trigger, but very powerful.
  Revisioning adds its own events and conditions to Rules, for example
  "content is about to be published" and "content has pending
  revisions".

Then for the view itself you could try to link to a 2nd page that uses the Diff Different module to make the UI per field item you are talking about to move field data around.

I don't see any out of the box solution and you need to build a Workflow of pages/forms/views etc. I'm just trying to help by listing some tools to help achieve that.


How do I set the absolute path for an image? I use image upload default ckeditor and IMCE module for drupal 8. But both of them return relative paths.

Output code actual relative path:

Output code expected absolute path:

How to correct it?

IMCE has a checkbox setting to enable absolute paths in configuration page


Display date and time in header I would like to display current date and time to the header section.

I am using a subtheme of Bartik. Any suggestions?

You can also add code page.html.twig as well.

For print only date use {{ "now"|date("m/d/Y") }}

More Details

http://twig.sensiolabs.org/doc/2.x/filters/date.html

https://stackoverflow.com/questions/17364206/symfony2-how-can-i-set-twig-dated-f-y-filter-to-output-months-in-swedish


Sort nodes by latest comments on it I am using D7. I want to sort the nodes by the comment post date on it.

Like

Node a created on Jan 03
Node b Created on Jan 05

Normally i can sort it either asc or desc.

What i want is a node with latest comment will be in top of my views.

I am looking for a views3 solution.
Is it possible ?

"Last comment time" is sort.

Then use 'Sort descending'


Why will Panels not upgrade? I get this error when I drush up panels:

Code updates will be made to the following projects: Panels [panels-7.x-3.4]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control s
ystem.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate tho
se modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project panels was updated successfully. Installed version is now 7.x-3.4.
Backups were saved into the directory /home/bzisad0/drush-backups/newco/20141017210224/modules/panels.       [ok]
WD php: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't [error]
exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of
/var/www/vhosts/www.newco.com/releases/20131007153705/includes/cache.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;newco.cache_panels&#039; doesn&#039;t exis
t: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of /var/www/vhosts/www.newco.com/releases/20131007153705/includes/cache.inc).
Drush command terminated abnormally due to an unrecoverable error.                                           [error]
Backups were restored successfully.                                                                          [ok]

For some reason that table was never created in the database (this site started on an early version of 7, so perhap the Panels module didn't use a cache table back then???).  You can fix this by creating one that's identical to all the other cache_* tables:

CREATE TABLE `newco`.`cache_panels` (
  `cid` varchar(255) NOT NULL default '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL default '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL default '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL default '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY  (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT 'Panels cache, manually created because Panels module would not upgrade without it'

Then you should be able to successfully upgrade the panels module:

$ drush up panels


How do I make a panel visibility rule work when the element to check for has to be not set or empty? I am using Drupal 7, panels and page manager modules.

In page manager I created variants on the node template for showing a particular type of node in a different fashion to different user roles. My nodes have a Term Reference field called "Alternatives" that is NOT required to be set by the users so it can be either be "empty" aka "none" or set to some data value i.e. a taxonomy term of the vocabulary "Alternatives".

I created a visibility rule on another element on the same variant to hide this "other" element, a custom content.

From the element's gear icon (on the tab "Content" in the variant section) of the custom content, I have set the visibility rule to show: Alternatives is set to "". That's exactly what I want: if Alternatives is set to "nothing", this custom content should show and now it doesn't show.

It seems that the visibility rule doesn't seem to recognise or can't check if a term reference field (Alternatives) is empty or not set. How do I make this visibility rule work?

use flags module, and rules module, make a rule when save/update your content type, condition: your_field_value is empty, if true, flag your node, then in panels add your panels-rule visibility  based on your new flag.


How to hide completed event from view result based on it's end date? I have created an Event Type pages which have date field Start Date-End Date, how do I hide completed event in view result or else is there any other way to unpublished them automatically?

You should Enable the "Date Views" module first. Then you will be able to find the Date CCK fields available in the filter criteria as Expected. You will also be able to provide a relative date in the filter criteria. Refer Screenshot.

Hope this Helps!


Accessing text of a field with type "Text" I fear that my question could be covered in detail already somewhere, but I did not find something useful. So appologies if this is the case.

I added a field of type "Text" to content type "Article". Now, I want to access the string of this field.

I want to access this in file template.php of the theme I use. To be precise, I want it to access in function "tb_corpal_preprocess_page". (File from themebrain theme "tb_corpal".)

I can see that in another function the "field_image" is accessed like this:

if(isset($vars['content']['field_image']))

If I now want to extract my field_banner, which is a field of type "Text", how do I do that? I guess it should also be stored in $vars, right? If yes, how do I access the string?

start by downloading the devel module.

A suite of modules containing fun for module developers and themers
...
Devel
Helper functions for Drupal developers and inquisitive admins.
This module can print a summary of all database queries for each page
request at the bottom of each page. The summary includes how many
times each query was executed on a page (shouldn't run same query
multiple times), and how long each query took (short is good - use
cache for complex queries). Also a dprint_r($array) function is
provided, which pretty prints arrays. Useful during development.
Similarly, a ddebug_backtrace() is offerred. much more.

This includes a function dpm() which allows you to navigate through complex variables including $vars. dpm($vars) will create a user interface for navigating through it - then you can find the specific location for the field you want.
I included this as an answer instead of the presumed actual location of the field within $vars since this allows you future access to any variables you need. You can use this for example to go through a $form, $content, etc.


display suite modifications I am using Display Suite for the first time and experimenting with the 2-columns layout.

What I didn't expect is that the module will override my existing node layout.

Can anyone tell me if I can use my 2-column layout in combination with my existing layout? This is especially important as I have information which needs to be displays outside of columns above and below it.

Thanks

i will advice you to use "Fluid two column stacked" layout. This layout provides a header region, then two left and right columns and one footer region.
So you can display your data by putting appropriate fields in the right regions. Also if you don't have any fields in any region that region will simply not display and if you don't have data in the left column then the right column will shift to the left side.
Hope this solves your problem.


overlay does not work after enabling my custom module I am using latest Drupal 7.

I just noticed my admin overlay is not working.

First I thought its due to Jquery Update contrib module installation however that not it.
 Its apparently due to my custom module, overlay works if I uninstall my module.

My module consists of few basic hooks like hook_menu, hook_form, etc and a simple js file with delete confirm popup code in it.

Also in Home » Administration » Structure » Content types » Basic page, in manage fields tab, 'select a widget' select list (dropdown) shows all options. It is suppose to show options according to field type selected.

$(function() {
 $(document).ready(function () {

  $(".del-link").click(function () {
   var answer = confirm("This action will delete this record?")
    if (answer){ // if yes is clicked on the confirm box.
     var del_record_id = this.id; // get record id that needs to be deleted.
      window.location = "/delete_url/" + del_record_id; // go to url which trigs the delete function and the record is deleted.
    }
  });

  $("#edit-my-form-field").click(function () {
    $("#edit-my-form-field").is(":checked") ? $("#show-hide-div").hide() : $("#show-hide-div").show();
  }); // end of click function.

 }); // end of  $(document).ready(function ().
}); // end of $(function().

Has anyone come across similar issue?

I figured (googled) it out. :)

I added my custom js in my custom module's info file instead of using drupal_add_js in my module directly.

scripts[] = my_module.js

and added drupal behaviors in my js file as well, so now my custom js looks like below

(function ($) {
Drupal.behaviors.my_module = {
attach: function (context) {

// my js code

 }
};
})(jQuery);

I spent many hours figuring this out but it was as simple as could be be.

Hope this helps someone! :)


Hiding a Tab when the View from Field View is Empty I'm using Views Field to show a view in a Horizontal Tab in a content type. My trouble is that when the view returns empty based on filter criteria, the tab is not hidden.

The view itself has 4 fields from the content plus some custom text.

I tried going through some of the "Not Empty" tips for hding blocks when views are empty, but It didn't work and it was all a shot in the dark anyway.

Try with this

$node = node_load($argument);
if ((isset($node->field_fotos) ||
     isset($node->field_summary)) &&
     (is_array($node->field_fotos) &&
     count($node->field_fotos) > 0) ||
     (is_array($node->field_summary) &&
     count($node->field_summary) > 0)) {
  return TRUE;
}
else {
  return FALSE;
}


Set default frontpage to Front Page view I've setted the Default front page to the View Front Page, but when I go to www.mydomain.com the page don't redirects to www.mydomain.com/frontpage.

When I go and write www.mydomain.com/frontpage the Front Page view is displayed.

What is going wrong?

you need to set it here:

http://www.DOMAIN.com/admin/config/system/site-information

You set the "Default Front Page Link" there.

When you hit your root (/) url, it will not "redirect" to that custom url you set, but it will auto render the url you inputted.

If you want to do a true redirect when hitting the frontpage you might have to do it via the .htaccess file as I'm not sure if there is module that can do a redirect from the frontpage.


How do I get all ContentEntities? What I'm trying to do is

$entities = EntityInterface::loadMultiple();

That should give me all entities.

But when I call it, it gives me this

  Fatal error: Cannot call abstract method Drupal\Core\Entity\EntityInterface::loadMultiple()

What I need is the type and the bundles of the entities.

I don't want to get specific entities like Node, Comment, Block etc. I want to get them all.

$fields['node']['article'] =  <<<< I want that dynamic.

Something like that

foreach($entities as $entity) {
  $fields[$entity->getType()][$entity->bundle()] = ....
}

You can get around the error about the abstract method by using entity::loadMultiple, but you'll get a new error, because this only works from an entity subclass.

Instead of using the static method, you would have to do this dynamically:

First get all content entity types:

  $entity_types = \Drupal::entityTypeManager()->getDefinitions();
  $content_entity_types = array_filter($entity_types, function ($entity_type) {
    return $entity_type instanceof \Drupal\Core\Entity\ContentEntityTypeInterface;
  });
  $content_entity_type_ids = array_keys($content_entity_types);

Then load all entities for each type:

  $entities = [];
  foreach ($content_entity_type_ids as $type) {
    $entities[$type] = \Drupal::entityTypeManager()->getStorage($type)->loadMultiple();
  }


How to override an existing theme without subtheming it? Does anyone know how to overload/override an existing theme with one's own .css and .tpl.php file, without subtheming it?

You can call for your css

<?php
function mytheme_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=News+Cycle', array('type' => 'external'));
}
?>

and for your tpl file

<?php
/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
    // Defined path to the current module.
    $module_path = drupal_get_path('module', 'my_module');
    // Find all .tpl.php files in this module's folder recursively.
    $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
    // Iterate through all found template file objects.
    foreach ($template_file_objects as $key => $template_file_object) {
        // If the template has not already been overridden by a theme.
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
            // Alter the theme path and template elements.
            $theme_registry[$key]['theme path'] = $module_path;
            $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
            $theme_registry[$key]['type'] = 'module';
        }
    }
}
?>


Passing NID argument from views to panelizer I am working on a complex site using Views and Panelizer.

I am trying to use Panelizer to display Views generated data, filtered by NID, for each advertisement.

To do that, I created a view called Advertisements with a content pane called Display which takes an NID as a contextual filter.

The NID filter is set to Provide default value -> Content ID from URL.

With that I am able to preview the field data of an existing article node when I provide it's NID as an argument.

However I have problems beyond this point :-(

I find my View content-pane in the Views panes section of the content area of Article's panelizer area - but there is no preview.
This immediately suggest there is something wrong with the output.

This is confirmed when I save the configuration and visit an Advertisement node - my output does not display.

After some research, I return to Views and go into the pane settings -> argument input section. I set it to From context -> Content ID.

With the View saved, I return to my advertisement node to find the page still blank.

I am very stomped and a lot of time has been wasted on this.

Can anyone please advice what I'm doing wrong or missing.

I had the exact same setup and issue. I could see the title of the view pane but no content even after I had made sure to set Argument input:Edit (in content pane view) to be:

Argument source: From context
Required context: Content ID

The reason I was not seeing content and only the title of view was simply because I'd forgotten I'd made a tpl of that view and had not yet cleared cache...


Add theme_hook_suggestions only for nodes in content I am developing a blog with different categories (taxonomy terms) and I wanted to have custom node templates for the nodes displayed on the blog page and category pages. Because my blog page has a view, I am able to use this template for nodes on that view: node--view--blog.tpl.php. But there is no template I can use for the nodes loaded in www.example.com/category/cat_name (alias for www.example.com/taxonomy/term/3).

I tried suggesting a node template in template_preprocess_node() like this:

if(arg(0) == 'taxonomy') {
  array_push($vars['theme_hook_suggestions'], 'node__view__blog');
}

The problem with this is that now all the nodes inside that page are rendered with that template, including the ones in my sidebar.

Is there a way to filter inside template_preprocess_node the only ones that are part of the "main content" of the page?

I would recommend you override the default term page with a view, and then theme it like you are doing for your other view.
All you have to do is create a view with that same path (taxonomy/term/%) and it will override the default page.

There is even a view already configured for this purpose, you just have to enable it.

On the views listing admin page it is called "Taxonomy term". Just enable and configure this view and then you can override it's themeing.


How do I alter certain module form output Some of my node types use fields from extra modules (such as Open Hours or Get Locations). How do I change the way those modules render their fields inside the form? I mean Get Location for example renders fieldset with fields in it. I'd like to change it at all. Also I'd like to change the order of fields and so on.
Is there anyway to make it using something like field--field-name.tpl.php for output fields?
Sorry if this is a common question but I couldn't find any complete guidance on this.

The form elements for fields (or "Field Widgets" as Drupal calls them) are defined using hook_field_widget_form(), e.g.

function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  );
  return array('value' => $element);
}

They use the form API, and don't have associated templates/themes unless one is explicitly set on a contained element.

You can use hook_field_widget_form_alter() to manipulate the elements; the simplest example (from the docs) would add a class to a particular element:

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

But obviously you're only limited by what the form API can do. So if you wanted to provide a specific theme for an element:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'mytype') {
    $element['#theme'] = 'MYMODULE_some_theme';
  }
}

Then it would just be a matter of implementing hook_theme() and creating the template file to do what you need.

Just for posterity (and because I accidentally answered the question with this first time round); the following relates to formatting the output of a field when its parent entity is displayed:

As listed in Drupal 7 Template (Theme Hook) Suggestions, and originally defined in template_preprocess_field(), these are the built-in patterns you can use to override specific field templates:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php

You could also add your own using a template preprocess hook:

function MYTHEME_preprocess_field(&$vars) {
  // This will let you use field--foo.tpl.php as the template name for any fields that pass the condition.
  if (some_condition()) {
    $vars['theme_hook_suggestions'][] = 'field__foo';
  }
}

As far as changing the order of field output goes, that's usually done through the UI in the "Manage Display" forms available for the various view modes for each entity type.


Add intro text before profile 2 form in the registration page I have a site that use profile 2 to add some field in the user registration page (/user) and via LoginToBoggan I can ask email x 2 and password x 2.

Now I need to insert a little introductive text before profile2 fields, like a phrase that explain why I need to ask that fields to the user.

How can I create it?

You can use the markup module to display text. It is available as a field element.


How to alter a views current pager label to node post date I'm working on a website which features a daily updated "six word story" (a node for each day). I created a view to display the last node/story, with the option to scroll back one day at a time (using AJAX). The view has a full pager.

However, the pager is (of course) displaying "<< Previous ... 2 ... Next >>". Number 2 would mean "yesterday" (the first result is today's six word story, nr. 2 yesterdays and so on). What I want to do is alter the text (which now is just a number), so it would show the post date of the shown node/story.

I know that the labels can be altered, but there are only four labels (first, previous, next, last). It seems that there is no label in the pager plugin for the current page. Any ideas on how to alter the label without breaking the actual pager itself?

One thing that comes to mind is to override theme_pager() in your theme's template.php. In fact, this post covers how to do that without messing up the first, previous, next, last labels.


How to load an include file from Drupal's include folder? I am experiencing a problem with the GlobalRedirect module in that it seems like it is not loading the locale.inc which it relies upon. I tried using the module_load_include function but did not work as locale.inc isn't apart of a module.

I know I can use:

include(DRUPAL_ROOT."/includes/locale.inc");

Is there a Drupal specific function call to load include files for Drupal? I am curious if there is.

Thanks

require_once DRUPAL_ROOT . '/includes/actions.inc';

is the correct way.

Using 'content' just worked, because there is no module named content and just did work due to a side-effect. It also caused silent performance problems on Drupal versions < 7.50.

There is no Drupal specific function to load a core include file, and this is how it is done in includes/common.inc line 5242.

Fabianx, Drupal 7 core branch maintainer and core committer


How to display associated content through shared taxonomy? I have two content types, 'Topic Summary' and 'Clip Page.' Both can share the same taxonomy. For example, they might share the taxonomy 'raccoons.'

When a user clicks on a 'topic summary' I would like to display links to the related 'clip pages' through their shared taxonomy in a block underneath the content of the 'topic summary.'

I've tried doing this using views and contextual filters but I'm having no luck. I wonder if anyone could tell me how do achieve this? Specifically, it would be good to know the Drupal way of doing so.

If I am understanding your situation correctly you want to display a list of clip pages grouped by topic summary.

In Drupal 6 you can use the http://drupal.org/project/views_groupby module, in Drupal 7 it's built in to views.

HTH


Extending user reference I have built a content type named "Project" which will showcase some projects by the members of a group. I have used a user reference field in that content type, so that the contributors of a project can be enlisted.

Now I am trying to put in the user's profile page the links to the projects he contributed to. How can I achieve that?

You will need to use views and panels. You will create a new user home page using panels. Within that panel you will want to create a view that lists all the content types Project filtering on the user.

Otherwise, you will need to create your own module.


How do I get Rules to see my custom entity? From what I've read in the past few days, Rules will gather all information it needs from hook_entity_info.  I still can't get my custom entity to appear in the data selector to make things work though.  Here is my implementation of hook_entity_info:

function badge_entity_info() {
  $info = array();

  $info['badge'] = array(
    'label' => t('Badge'),
    'base table' => 'badge',
    'class' => 'DrupalDefaultEntity',
    'controller class' => 'DrupalDefaultEntityController',
    'entity keys' => array(
      'id' => 'bid',
      'label' => 'name',
    ),
    'module' => 'badge',
    'access callback' => 'badge_access',
    'admin ui' => array(
      'path' => 'admin/structure/badge',
      'file' => 'badge.admin.inc',
    ),
    'uri callback' => 'badge_uri',
  );

  return $info;
}

Everything else is working perfectly, I just need to understand how to make Rules recognize my custom entity.

Individual rules can have a type associated with them. Most rules work with Nodes but an Entity is 1 object up in the type hierarchy of Drupal. therefore rule(s) defined with the Rules module must be made aware that they are compatible with your custom entity type.

You would do this with an alter hook for Rules, or providing property information for your Entity:
I can't set a data value using rule on a custom entity


Drupal 7.2: Horizontal & Vertical Tabs- HOW? Using d7.2.  I'm looking to create this setup, possibly w/ JQuery (or something similar that would provide real time tabs w/o refreshing the page).

         Popular        Visits       Comments      Recent

Category 1

Category 2

Category 3

Category 4

So the user would click on one of the category tabs on the left side (vertical), and then they can sort w/ the links at the top w/ real-time refresh/results, no page refreshing or loading required.

I like the look of JQuery tabs- but want the best solution here. By best I mean easiest, lightest, and most compatible with most browsers.

I can setup various views to execute the searches/results- but do I make those 'pages', or 'blocks'? How do I create the tabs and links for sorting?

Thanks for all the help guys!

The best solution is using the Quick Tabs module. It allows you to create static or dynamic Ajax loaded tabs with nodes, blocks, and views.


How do I run hook_views_data_alter()? So I have already read and followed everything I could find on that issue:

putting my_module_views_data_alter(array &$data) in my_module.views.inc file in the root directory of my_module,
disabling cache for my view,
clearing caches million times,

but still I can never stop at a breakpoint inside this hook, nor can I see any effects of the code I have put in it.

What am I missing?

EDIT: updating with some code

In my_module I have already created a computed field user_age, calculating user age from a custom user profile field with date of birth.

my_module/my_module.module

function my_module_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields = [];
    $fields['user_age'] = BaseFieldDefinition::create('user_age_field')
      ->setName('user_age')
      ->setLabel(t('User age'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\my_module\UserAgeIntegerItemList')
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'weight' => -5,
      ]);

    return $fields;
  }
}
function my_module_field_formatter_info_alter(array &$info) {
  $info['number_integer']['field_types'][] = 'user_age_field';
}

This field is working and is accessible in my user profile template.

Knowing that since Drupal 8.4

  Computed fields can now be displayed by Views

I wanted to use field user_age as an exposed filter in my search_users view:

my_module/my_module.views.inc

/**
 * Implements hook_views_data_alter().
 */
function my_module_views_data_alter(array &$data) {
  if (isset($data['users_field_data'])) {
    $data['users_field_data']['user_age'] = [
      'title' => t('User age'),
      'field' => [
        'id' => 'my_module_view_user_age',
      ],
    ];
  }
}

my_module/src/Plugin/views/field/MyModuleViewUserAge.php

<?php

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\ResultRow;
use Drupal\views\Plugin\views\field\FieldPluginBase;

/**
 * A handler to provide proper displays for user user_age.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("my_module_view_user_age")
 */
class MyModuleViewUserAge extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    $relationship_entities = $values->_relationship_entities;
    $age = '';
    // First check the referenced entity.
    if (isset($relationship_entities['user'])) {
      $user = $relationship_entities['user'];
    }
    else {
      $user = $values->_entity;
    }

    $type = get_class($user);
    if ($type === 'Drupal\user\Entity\User') {
      $age = $user->get('user_age')->getvalue();
    }

    return $age;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // This function exists to override parent query function.
    // Do nothing.
  }
}

but my_module_views_data_alter() seems to never be executed and user_age field is not present in the filter criteria for my view.

You can't xdebug in hook itself, you need to go to method calling this hooks which is in class ViewsData  path /core/modules/views/src/ViewsData.php
and put breakpoint in getData, clear cache and you will get what you need.


For Drupal 7, is there a hook debug mode equivalent to the theme debug mode? As a beginning developer, it seems like I spend a significant percentage of my time googling to find out what hook to call in order to modify something before it renders.

In the drupal 7.33 release, the theme debug mode was introduced, which provides contextual information in the page's HTML to theme developers and can be accessed by setting the theme_debug variable to TRUE.

Obviously there is no hook debug mode supported in core, but is anyone aware of a module that would provides contextual information about attempted hook calls, similar to how theme debug mode displays theme suggestion attempts?

Specifically, I am wondering if there is a module that would generate a list  of every call to drupal_alter(), module_invoke_all(), or module_invoke(), along with the $type, $module, and/or $hook arguments supplied to these functions.

You could create a custom module and use hook_module_implements_alter which takes two arguements - $implementations and $hook.

Try this:

function MODULE_module_implements_alter(&$implements, $hook) {
  if ($hook == 'form_alter') {
    print_r($implementations);
  }
}

This will print out a list of all the implementations, in order, for hook_form_alter.


Programmatically rearrange order of entity reference list on node My content type has a node reference field that allows users to enter an unlimited amount of nodes in. I need to programmatically change what comes first in this list.

Using the code below I'm able to obtain the data from the field.

$node = \Drupal::entityTypeManager()->getStorage('node')->load($function);
$focus = $node->field_focus_area->getValue();

And it produces:

array(2) {
  [0]=>
  array(1) {
    ["target_id"]=>
    string(2) "31"
  }
  [1]=>
  array(1) {
    ["target_id"]=>
    string(3) "161"
  }
}

In order to rearrange it I tried doing

$newOrder[0] = ['target_id'=> 161];
$newOrder[1] = ['target_id'=> 31];

$focus->field_focus_area->rekey($newOrder);

But it was then when I realized that rekey was a protected function so I could use it. How would I programmatically rearrange the deltas (if that's what you'd call it) of an entity reference field programmatically?

After getting and rearranging the field data you can set it again:

$node->field_focus_area->setValue($newOrder);


Hide the email address when searching for users When using the Drupal custom search form, and searching for users (search/user), the user's email address is displayed to administrator users. I want to hide it, even to the administrator users.

How can I do this?

I think there is no such an option to hide email addresses from drupal system. You can create your own search-results.tpl.php in your theme or use template_preprocess_search_results() in your template.php to alter the user names.


Why does drupal_set_message not appear in the message area? I often use something like drupal_set_message( krumo( $row ) ); to output debug information. This is suppose to output that message within the $message area placed via the page.tpl file, however sometimes this is output in line where the code is suppose to be rendering (via a field template.)

Is there any way to make drupal_set_message output to the right place when being used in the the theme layer?

You do not have to call krumo directly. You can just use the helper function dpm, this will print a krumo output on the message variable.

Example:

dpm($row);


How to hide or remove field set on user profile page I have user relationship installed. When i enable the user relationship node access module, the "Share content" field set appears on my user profile.

Is there a way to hide, remove or change the weight of the field set as I do not like the position it occupies on my user profile?

Thank you.

You can hide, change weight of any form element by help of form_alter().

You will have to create a small module for it with any name like - myModule.

Put .info file in there & a .module file. Declare the information of the module. Enable the module.

Use my given hook & see what is available in form by DPM(You will need devel module to use this).

Write some thing like this

function myModule_form_alter(&$form, &$form_state, $form_id){
  dpm($form);
}

When you will visit the form you will get output of $form variable, where you can find $form_id to use to put in condition & the element which you are looking to remove or change properties.

Then you will have to put your logic in the function to have this working according to your need. Like see, how you can remove description from name/password field at login form --

function myModule_form_alter(&$form, &$form_state, $form_id){
  if($form['#id'] == 'user-login'){
    $form['name']['#description'] = t('');
    $form['pass']['#description'] = t('');
  }
}

This is not the exact solution you are looking for, but this is the way you can do it from yourself. I hope this help..


Content type with multiple different flavours I want to create content type (document) with title, comment and file attachment (PDF or doc). I don't want to create different content types (for each document type form, policy, abuse etc..) because if i need to add/remove/change field in it it's need to be repeated on all content types. I'm thinking about taxonomy but I'm not sure.

What's the best solution for one content type with multiple different "flavours"?

You can use taxonomy to categorize the content. If you want categorize the content like form, policy, abuse etc... create a taxonomy vocabulary name as Document Type then add form, policy, abuse etc... as terms in it. Then Add a term reference field(in D7) in manage field settings. And also you can use Conditional Fields for display fields according to the document type.


Autocomplete JavaScript module I have created a custom autocomplete function. The autocomplete field is populated with user name and last name from the content profile.

It is possible that there will be few users with the same name and last name. How I can pass content type ID to Drupal autocomplete, and add this ID to a hidden form field, so I can be more accurate?

I don't want to put the content type ID straight to autocomplete field, so I need some callback to current implementation.

Thanks to @googletorp advice the solutions is so easy and I want to share it with others.
All I need was to overwrite two Drupal autocomplete object functions: found and select.

My autocomplete works on content profile fields. I pass nid of selected profiles to JS:

PHP:

function messagi_autocomplete($string) {
  global $user;

    $cache = cache_get('messagi_auto_complete_'.$string);
    $items = array();

    if ($cache) {

        $items = $cache->data;

    } else {

        $sql = "
              SELECT
                n.nid AS id
              FROM
                node as n
              WHERE
                n.type = 'profile'
              AND
                u.status = 0
          ";
          $result = db_query($sql);
          $disabled = array();
          while($obj = db_fetch_object($result)) {
              $disabled[] = $obj->id;
          }

          $items = array();
          $sql = "
                        SELECT
                    profile.nid AS nid,
                    profile.field_profile_name_value AS name,
                    profile.field_profile_surname_value AS surname
                  FROM
                    content_type_profile AS profile
                  WHERE
                    lower(profile.field_profile_name_value) LIKE lower('%s%%')
                  OR lower(profile.field_profile_surname_value) LIKE lower('%s%%')
                  LIMIT 10
          ";
          $result = db_query($sql, $string, $string);
          $sql = NULL;
          while($obj = db_fetch_object($result)) {
            if (! in_array($obj->nid, $disabled)) {
                  $key = check_plain($obj->name).' '.check_plain($obj->surname);
                  $items['nids'][$key] = (int) $obj->nid;
                  $items[$key] = $key.', '.check_plain($obj->venue);
            }
          }
            if (! empty($items)) {

                cache_set('messagi_auto_complete_'.$string, $items, 'cache', 1000);

            }
          $disabled = NULL;

    }

  print drupal_to_js($items);
  exit();
}

JS:

$(document).ready(function() {    if
    (Drupal.jsEnabled) {
            Drupal.jsAC.prototype.found = function (matches) {
              if (!this.input.value.length) {
                return false;
              }

              var ul = document.createElement('ul');
              var ac = this;
              for (key in matches) {
                var li = document.createElement('li');
                //to avoid of showing nids object in the select list
                if (key !== 'nids') {
                    $(li)
                      .html('<div>'+ matches[key] +'</div>')
                      .mousedown(function () {
    ac.select(this); })
                      .mouseover(function () {
    ac.highlight(this); })
                      .mouseout(function () { ac.unhighlight(this); });
                    li.autocompleteValue = key;
                    $(ul).append(li);
                } else {
                 //add all nids to prototype
                    Drupal.jsAC.prototype.nids = matches[key];
                }
               }
                //rest of the code
              }
            };

            Drupal.jsAC.prototype.select = function (node) {
              //get selected value nid and put it on form hidden field
              $('#edit-nid').val(Drupal.jsAC.prototype.nids[node.autocompleteValue]);
              this.input.value = node.autocompleteValue;
            };
} })

I hope this help somebody in the future. Thanks for the others advice to this code.


How to write a service module for Drupal 7 and Services 3.x? Can somebody please give instructions on how to write a simple service module for Services 3.x and Drupal 7.x? I simply cannot find any that works with D7. Anything! Just a reworked version of echo_service module would do!

At the very least please link to a working example. Thanks.

In addition to the link mentioned, here's some code from a module I wrote that uses webservices. Under "structure" the service should be enabled and an endpoint defined. You also set the allowed return types there.

So if you define 'api' as endpoint and want a json array, you would do a request like yoursite.com/api/servicename/arg1/arg2.json. You define the service name in  hook_services_resources.

<?php

// $Id$
/* * **********************************************************************************************
 * @file
 * Based on the RESTful API shell module http://drupal.org/node/1034540
 */

/* * *************************************************************************************************
 * Include necessary files
 */
require_once (drupal_get_path('module', 'graph_data_api') . '/model/highchart_graph.php');

/* * *************************************************************************************************
 * Implementation of hook_help().
 * @see http://api.drupal.org/api/function/hook_help/6
 */

function graph_data_api_help($path, $arg) {
  $msg = t('
Provides a API for graph data for use with Highcharts.
');
  switch ($path) {
    case 'admin/help#graph_data_api':
      return $msg;
    case 'admin/modules#description':
      return $msg;
  }
}

/* * *************************************************************************************************
 * Implementation of hook_disable()
 * @see http://api.drupal.org/api/function/hook_disable/6
 */

function graph_data_api_disable() {
  cache_clear_all('services:methods', 'cache');
  //eco_debug( '*** graph_data_api_disable() called!' );
}

/* * *************************************************************************************************
 * Implementation of hook_enable()
 * @see http://api.drupal.org/api/function/hook_enable/6
 */

function graph_data_api_enable() {
  cache_clear_all('services:methods', 'cache');
  //eco_debug( '*** graph_data_api_enable() called!' );
}

/* * *************************************************************************************************
 * Implementation of hook_perm().
 * @see http://api.drupal.org/api/function/hook_perm/6
 */

function graph_data_api_permission() {
  return array(
      'request graph data' => array(
          'title' => t('Request graph data'),
          'description' => t('Allows user to use the graph api for Highchart graphs'),
      ),
  );
}

/* * *************************************************************************************************
 * Access callback
 * For now only view/retrieve is implemented and if the user is logged in, he gets access
 */

function _graph_data_api_graphdata_access($op) {
  global $user;
  $access = FALSE;

  switch ($op) {
    case 'view':
      if ($user->uid) {
        $access = TRUE;
      }
      break;
  }

  return $access;
}

/* * *************************************************************************************************
 * Implementation of hook_services_resources().
 * For now only retrieve with a GET request is implemented
 */

function graph_data_api_services_resources() {
  return array(
      'graphdata' => array(
          'retrieve' => array('help' => 'Retrieves graphdata',
              'callback' => '_graph_data_api_graphdata_retrieve',
              'access callback' => '_graph_data_api_graphdata_access',
              'access arguments' => array('view'),
              'access arguments append' => FALSE,
              'args' => array(
                  array('name' => 'parameters',
                      'type' => 'string',
                      'description' => 'The parameters that define requested data',
                      'source' => array('path' => '0'), // first argument in the url
                      'optional' => FALSE,
                  ),
              ),
          ),
      ),
  );
}

/* * *************************************************************************************************
 * Callback for the retrieve resource
 */

function _graph_data_api_graphdata_retrieve($arg) {

  $data = 'hello world';
  return $data;
}


How to add default text that clears on focus to a form in Drupal? I would like to display a default text in a field of a views filter form. That default text would then be hidden "on focus", and would re-appear "on blur".
So far I have tried to follow the instructions given here:
How to add default text that clears on focus with jQuery to a search form text field in Drupal
but with no success.

What I did:

1. Downloaded the Jquery files (https://github.com/mudge/jquery_example/downloads), and copied them in my /sites/all/libraries/mudge-jquery directory

2. Added a helper.js file into that directory with that code

(function ($) {
  Drupal.behaviors.helper =  {
    attach: function(context, settings) {
      $('input#edit-title.form-text.beautytips-module-processed.bt-active').example('TEXT TO HELP');
    }
  };
})(jQuery);

3. Created a simple module with that code:

function helper_preprocess_page (&$vars) {
  // Let's add some js to page for the search box.
  $path = drupal_get_path('module', 'helper');
  drupal_add_js($path . '/sites/all/libraries/mudge-jquery/jquery.example.min.js');
  drupal_add_js($path . '/sites/all/libraries/mudge-jquery/helper.js');
}

Still nothing is displayed in my "input#edit-title.form-text.beautytips-module-processed.bt-active" field. What am I doing wrong here?

What you want here is:-

a) hook_form_alter to change the form

b) #attached to add JS to the form

c) add clear-text to ['#attributes']['classes'] where necessary.

Then you can use this little JS.

 Drupal.behaviors.clearText = function(context) {
    var inputs = $('input.clear-text:not(.processed)');

    // Store the original values
    inputs.each(function() {
      $this = $(this);
      $this.data('default', $this.val());
    }).addClass('processed');

    // Set up inputs to clear on focus & reload default (if blank) on blur
    inputs
      .focus(function() {
        $this = $(this);
        if ( $this.val() == $this.data('default') ) {
          $this.val('');
        }
      })
      .blur(function() {
        $this = $(this);
        if ( $this.val() == '' ) {
          $this.val( $this.data('default') );
        }
      });
  }


Registered custom block not showing up I tried to register two custom block in my custom_blocks module with the following code.

function custom_blocks_block_info(){
  $blocks = array();
  $blocks['featured_items'] = array(
    'info' => t('Featured Items'),
    'status' => TRUE
  );
  $blocks['workflow_illustration'] = array(
    'info' => t('How it works'),
    'status' => TRUE
  );
  return $blocks;
}

function custom_blocks_block_view($delta = ''){
  $block = array();
  switch ($delta) {
    case 'featured_items':
      $block['content'] = featured_items();
      break;
    case 'workflow_illustration':
      $block['content'] = workflow_chart();
      break;
  }
  return $block;
}

But the    problem is 'Featured Items' block is shown in the block administer page. But the 'How it Works' block is not shown (may be not registered :?) in the block administer page.

I tried deactivating the module >> clear drupal cache >> clear browser cache (?) >> activate the module again.

Still the 'Featured Block' is the only block showing up. Please help me to get my block accessible via block administer page.

First, try to provide $block['subject']. Second,  omit status in hook_block_info implementation, it may cause problems when there is no region assigned.


How to do push data to datalayer after Ajax callback? I have a view with many elements and use views load more -> view using views load.

Modules:

Views Load More.
dataLayer.

Is it possible send datalayer event after load elements with AJAX?

I am tracking with Tag manager (Google).

I had the same problem. Events were only sent first time and then never.
I solved it purging completely cache, and fixing my google tag.


Using a custom field as a sub-field in another custom field I posted a while back and have now successfully implemented a custom field (this was an extension of the DateRange field type to add control over presentation etc...)

I have a few other use cases where I could do with having a modified daterange field as a sub-field in another custom field type, now I know I could implement in the same way in each new custom field type, however, it would be much simpler if I could just drop in my custom daterange field. If this is not possible, is it best just to make my custom daterange the base type and extend this for each field type I need to create? Or is there another solution (I don't want to use paragraphs as I can't get the degree of customisation I want)

Basically, the question is how to use a custom field in another field as a property.
In an entity a custom field is added by using BaseFieldDefinition::create(). However a property of a field type is added by DataDefintion::create() or MapDefinition::create() and only basic types are defined (in DataDefintion class) to be used as DataDefintion. So It doesn't look like it is possible to have a custom field in another custom field.
References:

Fieldable field explains the problem of having a field inside a field
Entity API explains how each data type and field type are defined.
Same issue filed in d.o at #2874458


How do I find out which module loads which javascript file? I have been experiencing script related problems and would like to go through all the script files by disabling/enabling, to find out which is causing the problem.

So I'd like to be able to find out which module loads which javascript file. Then I can go by enabling disabling the modules.

How can I do that?

"If you look at the source of the page you can see the path for each script. This will identify where the script is."

Example

Typically the script located at...

sites/all/modules/contrib/panels/js/panels.js

...would more often than not only be used by the module of the same name

sites/all/modules/contrib/panels/panels.module

...or possible an include file

sites/all/modules/contrib/panels/includes/SOME_FILE.inc

Obviously bare in mind that Drupal uses the jQuery library so references to errors might fallback to these files just because its been implemented wrong by the developer in the module. Its more than likely never going to be something wrong with the libraries.

/misc/jquery.js
/misc/jquery.once.js


When to use a Webform vs. simply utilizing the Add Content page Where is the line between using the Webform module vs. simply letting users create new content of a certain content type?

I am fuzzy on when each would be more appropriate. Especially after seeing the ambiguity of answers and comments to this question.

Use case: Users aren't entering data for a survey, they are actually entering content in to the site. They are entering data for a node that will be displayed as a normal content page. But it needs to be validated, have conditional fields, etc.

I think Webforms is usually more appropriate when the entered data is intended to be used by the organization behind the website and never shown to the public.

Webforms is also useful to send the entered data by email to who should receive it. You could also do this with a content type but you would require some kind of Workflow or trigger and action which might end up being "heavier" to the server

If you intend visitors / end users  (authenticated or not)  to see the data entered by others users then you just make a content type and use the add content form.


Disable image autoscale when dimensions are bigger than my settings As you may know, in Drupal 7 you can set max and min dimensions for an image field, when you upload a small image, Drupal returns an error, but when you upload a bigger file it resize the image automatically instead of return the error "Your image is too big...".

I was looking for the reason of that autoscale configuration but looks like it will never be fixed. I need to override it because some of my users still uploading pictures with other dimentions, even with a different aspect ratio.

I found the condition in includes/file.inc line 1809 ... it tries to scale the image if it's bigger. I know that i can comment that condition and it will work, but is not a good idea, so:
Does anyone know how to override that condition using a custom module, hooks or something?

You don't want to return the message "your image is too big" as people nowadays are uploading directly from their mobile phones and do not have (or know) a way of resizing/cropping themselves before uploading.

So you should try it via another way: do not impose restrictions on the original image, but use an image style to display the uploaded images and add some smart/user/custom crop effect to that image style. There are a number of modules that let users/editors custom crop images, e.g:

Imagefield crop
Manual Crop
Smart Crop
...

Also see Comparison of image cropping and resizing modules.


Can't assign roles in admin panel The day before yesterday I created a new role (writers), and when, after adding quite a few modules, I wanted to add another earlier today, I discovered there was no way for me to do this anymore, nor to edit the role I already created. Now, I am a newby with Drupal, only started out about 4 days ago, so I probably (un)ticked a box somewhere I shouldn't have, so I hope someone can help me out figuring out how to change this?

I added a screenshot of the page I think the possibility to administer roles should be. :)
(link)

Thanks in advance!

Looks like you're on /admin/people/permissions, which is the page for configuring permissions per role. You want to be on /admin/people/permissions/roles, which is the page for configuring the roles themselves. If you can access /admin/people/permissions/roles, you'll be able to add more roles there.

If you get an 'Access Denied' error when you try to access that page:

Go back to /admin/people/permissions.
Make sure you've given the 'administrator' role all permissions.
Go to /user.
Click the 'Edit' tab.
Scroll down and make sure your account has the role 'administrator'.


How to get Address Field to display correctly with Autocomplete? I want to create a postal field for addresses in the Philippines.

I have set up a sandbox site with a content type that has just one field, of type addressfield and using the autocomplete widget. Only one country is allowed.
However, when I create content, all I can see is the field for entering the address and the Google map, I cannot see the Address Field fields.
When I enter an address in the Philippines, it gets coded correctly by Google and displays properly on the map. However, if I then try to save the field, it tells me that obligatory fields ("Address 1" and "City" in this case) are missing.

If I click on "enter one manually", then nothing happens.

This is only accessible by a logged-in user, so I presume that caching is not the problem.

I have tried using FF45 and the lastest release of Chromium, all to no avail

I also presume that I must have made a mistake setting something up, but i cannot work out what that might be...

Turns out that there is an incompatibility between Addressfield Autocomplete and/or the geocomplete.js library it uses, and the version of JQuery that gets bundled with Drupal 7.

The solution is to install the JQuery Update module, and set the JQuery version to 1.10


ApacheSolr Search results with AJAX (D7) I've been searching the web for ways to display my search results directly in a block after submitting the input form with AJAX.

Unfortunatly, i haven't found alot of good information on this subject. Can anyone here point me in the right direction? I'm using Drupal 7.

Thanks in advance! :)

Apache Solr AJAX module is available for D6

Project page says

  The Apache Solr AJAX module AJAXifies Apache Solr Search Integration –
  if you change your query or filters, you see the new result set
  instantly – no need to reload the full page.

For D7 there exists a Sandbox Project

You can try the module, Download module using below commands,

git clone --branch master http://git.drupal.org/sandbox/darthsteven/1116776.git apache_solr_ajax___d7
cd apache_solr_ajax___d7

Found an article here Drupal7 AJAXified Solr Search with facets. Search API, Panels and some custom code. you can give a try..


Get the Dimensions of the Theme Logo In Drupal 7 theme settings, you can upload a logo.
How do you print the width and height of this logo in your theme?

Background Research:

theme_get_setting('logo') lets you get the path of a logo uploaded in the theme settings.

image_get_info lets you get the height and width of an image.

However, image_get_info(theme_get_setting('logo')) does nothing.

You can use the following code. (Add error checking where necessary.)

  $image_url = parse_url(theme_get_setting('logo'));
  $image_path = str_replace(base_path(), realpath(DRUPAL_ROOT) . '/', $image_url['path']);
  $info = image_get_info($image_path);
  $height = $info['height'];
  $width = $info['width'];

As side note, theme_get_settings('logo_path') returns the path of the uploaded file used as logo. While theme_get_settings('logo') always return a value, whatever the logo is the default one, or one that has been uploaded, theme_get_settings('logo_path') returns a value when the logo has been uploaded.
The value returned for "logo_path" is similar to public://logo.png. To obtain the real path, you would use code similar to the following one.

  if ($image_uri = theme_get_settings('logo_path')) {
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($image_uri)) {
      $image_path = $wrapper->realpath();
    }
    elseif (!empty($image_uri)) {
      $image_path = realpath($image_uri);
    }
  }


How to add a php to a custom page Here is what I am trying to do, I have a bookmarklet with the following code

javascript:location.href="http://mywebsite.com/getsource?url="+encodeURIComponent(location.href);

I want to fill in the url into a field on the page "http://mywebsite.com/getsource"

After asking around a bit, I was provided this piece of code.

<input type="text" id="edit-url-field" value="<?php echo $_GET['url']; ?>" />

My question is .. how do I implement this in Drupal 7?

You need to implement a custom module which defines a form and a path to this form.

In Drupal forms are implemented with the Form API. Please check this links for more information

http://drupal.org/node/751826
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7

You can define the path by implementing hook_menu.


Pager should start from last page instead of first one I have a block view including pager and shown on front page. when I go to front page I see the pager under block shown in normal way(ie start from first page). But I want that pager start from last page instead of first one.

Result of My View:

Result that I want:

I want that when I visit my view, it's pager should look like this

At the view, you can use SORT CRITERIA. It can help you arrange in post date, title page or even content field.


Print the comment form with PHP I'm trying to print a comment form with the following code.

<?php
    print drupal_get_form('comment_form', array('nid' => $row->nid), t('Post new comment'));
?>

All I get is the following error repeated 40 times:

  Warning: Attempt to assign property of non-object in comment_form() (line 1845 of /home/admin/public_html/website.com/modules/comment/comment.module).`

The comment form is called from inside a PHP Views field. What is the proper way to add a comment for to a node in Drupal 7?

There are actually a lot more errors, most of which repeat at least once:

  EntityMalformedException: Missing bundle property on entity of type comment. in entity_extract_ids() (line 7501 of /home/admin/public_html/website.com/includes/common.inc).
  Notice: Trying to get property of non-object in comment_form() (line 1854 of /home/admin/public_html/website.com/modules/comment/comment.module).

comment_form() is expecting the parameter to be an object rather than an array so you should be doing something like this:

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);

Note the lack of a 3rd parameter passed to drupal_get_form(), comment_form() only accepts the comment as a parameter, if you want to add a title you'll have to print that separately.

Finally drupal_get_form() returns a render array rather than a string so you need to pass it through the render() function:

print render($form);

The extra errors you're getting are just side-effects of passing an array rather than an object to the comment_form() function.


How do I add static html files to my Aegir install I have Aegir install running on a rack space server. In addition to the Drupal sites I am running, I would also like to be able to create static websites and server them from the same server. What steps do I need to do to get this to work with Aegir.

I tried the following

1.create a new file within vhostd containing

<VirtualHost *:80>
DocumentRoot /var/www/vhosts/mysite
ServerName mysite.mydomain.com

# Other directives here

</VirtualHost>

add html file to var/www/vhosts/mysite
3 restart apache ? (actually i'm not sure how to do this form aegir)

Your static websites cannot be managed by Aegir, so you should setup them separately on your server.

If you really need to restart apache from Aegir interface, just run 'Verify' task for any of the websites installed (hostmaster will work too). On verify, Aegir runs 'apache2ctl graceful' which effectively restarts apache.


What's the best way to delete all content without a content type? Due to an error during migration, some of the content has been left hanging without a content type and did not port over correctly.

What is the best way to delete these around 1000 records? Unfortunately they do not share any particular characteristics to be able to search them from the frontend easily.

Due to an error during migration, some of the content has been left
  hanging without a content type and did not port over correctly

If you're comfortable writing code you could write an SQL query to look for nodes or entities without a type set -- and output or save their IDs to a list. You may be able to use EntityFieldQuery for this but it may blow up, I'm not sure.

Once you have the IDs of content missing it's type you could try to use Drush Entity on your site to delete the entities. It supports deleting a list of entities by their ID (I assume in the Node table). Below is an excerpt from entity.drush.inc

  $items['entity-delete'] = array(
    'description' => 'Delete entities.',
    'arguments' => array(
      'type' => $type,
      'nids' => $nids,
    ),
    'options' => array(
      'json' => $output_json,
      'bundles' => $bundles,
    ),
    'examples' => array(
      'entity-delete' => '.',
      'entity-delete node 64' => '.',
      'entity-delete node --type=story' => '.',
    ),
    'aliases' => array('ed'),
  );

So you could try to take your IDs and issue the command:

drush entity-delete node -v --nids=<list-of-nids-seperated-with-commas>

If this fails try:

drush entity-delete node --debug --nids=<list-of-nids>

Obviously you could try to do this all by hand with a query, and using node_delete() for instance, but I'm trying to find  you a slightly less programming intensive solution.

EDIT

1) ALWAYS BACKUP YOUR WEBSITE FILES + DB FIRST BEFORE ATTEMPTING DISASTER RECOVERY.

2) If the data is somehow improperly save and fragmented across disjointed tables good luck -- I've fixed mess-ups like this but end up scanning tables visually by hand and dropping obsolete fields or field_instances for example.


What are the technical implications of choosing asynchronous or synchronous billing cycle? When using the Commerce License Billing module the "/admin/commerce/config/license/billing-cycle-types/manage/monthly" page clearly states:

  Asynchronous

  Determines whether the billing cycle starts at the time
  of purchase, instead of starting at the beginning of the calendar
  period.  For an order placed on Jan 5th, a monthly synchronous billing
  cycle would start on Jan 1st 00:00 and end on Jan 31st 23:59:59,
  while a monthly asynchronous billing cycle would start at the time of
  purchase (Jan 5th) and end a month later (Feb 5th).

I wonder what are the technical implications of choosing asynchronous or synchronous billing cycles. I mean if I go with synchronous billing period will all the recurring services be renewed on 1st of each month at the same time? Won't that make it difficult for cron?

Synchronous billing cycle seems very convenient and more appealing to the end-customers, however my main concern is that Drupal cron might stack in posterity with growing number of orders for the recurring services in the system.

Could anybody elaborate on this to confirm or mitigate my concern?

The "implications" are that it mimics how you want to charge your customer for access. If you want to provide a revolving 30-day access to some content, an asynchronous billing cycle might make the most sense. Whereas if you're charging for a service and want everyone to have the same billing cycle, then you'd end up prorating the first month to get to the first point of your billing cycle.

At a technical level, cron should be running in daemon mode (or at least every 5-10 minutes) since your license provisioning requires it. You shouldn't have to do anything different.


Node translate tab access Why translate tab only available for super Admin in node & taxonomy form.
how can i view this tab & also button of save & translate for both Node & Taxonomy
to another roles (Editors & Translators), what is the proper permission access
should be given to show the translation tab ?

Forget to mention, this happen only when the node or content is unpublished,
but if its published the tabs appear normally.

I think it's because the not-super-admin users don't have permission to edit unpublished content that they didn't create.

If you want to alter this behavior you can add a new permission "edit any unpublished content" and use hook_node_access to allow editing unpublished nodes (if they have that permission)


Display content not updated from specific date I can generate a views with provides a list of content has been updated from an specific date (by adding field "Content: Updated date" in Filter criteria). However, I cannot find the opposite option, I mean built a list from a specific date which has not been moderated or updated. How can I get it?

Thanks a lot!

When you create your filter criteria you have an Operator drop down list that will offer the option like Is not equal to or is empty (NULL)

Then you can expose this filter and set the date manually or use an offset from the current date.


Minimum Items in Cart for Checkout I am working in Drupal 7 in Ubercart 3, and I am looking for a way to set a minimum on the number of items that a user can have before being able to start the checkout process.

Is there a module out there that handles this need?

There is Ubercart Product Minimum & Maximum

  Adds minimum, maximum and order in multiples limits on products.
  Checks that the quantity selected matches the limits during both Add
  To Cart and Checkout actions. Quantity checks are disabled when
  product is added to the cart as part of a product kit.

If you want to do it with code this is one way to do that.

You can make use of hook_add_to_cart to get the product add event.

To get the number of items use uc_cart_get_contents

The ides is

function <modulename>_add_to_cart($nid, $qty, $data) {
  $items = uc_cart_get_contents();
// Display a message if the cart has more than 5 products.
  $item_count = count($items);
  if ($item_count < 5) {
    drupal_set_message('Your cart Should contains more than 5 products to checkout !');
    // drupal_goto to product listing page
  }
  return $result;
}


Facets are missing post updating Apache Solr Search to 7.x-1.4 version I just updated Apache Solr Search module to 7.x-1.4 version, and since then the facets are missing in the assigned region.

Facets of all taxonomy terms are missing, the rest of the default facets like content type, etc are appearing on the settings page.

Plus the Taxonomy term fields are missing under Bias settings as well.

I have tried to disable > Uninstall > re-install all the Apache solr search and Acquia search modules but Facts are not appearing back on the Apache Solr Settings page.

I have this issue on the production server.

Regards,
Anand

Just wanted to log the answer that is suggested on Drupal.org: https://drupal.org/node/2123683, since this question is the first thing that popped up when I ran into this issue.  :0)

Here is the issue: the taxonomy facets are the ones affected by the upgrade, because even though your taxonomy terms are probably hidden in the 'Search index' view mode on your content type's configuration page, apachesolr used to ignore those settings (a bug).

The new update fixes that, which means you need to go back to your content type's manage display page -> search index tab -> make sure the taxonomy terms in question are not hidden.

Hope this helps!


Vote from list of existing nodes I have a Content Type "Picture". The contentmanager now wants to choose specific nodes of this ContentType and put them in a voteable list. The voting list should be auto generated if possible.
Users can vote one this list. A user can only vote once and give exactly one vote. After voting, the user should see the ranking results and within his profile he should be able to see for what he voted.

Whats the best way to achieve this?
I thought about using flags, but I would need to restrict a flag to a number of nodes and not per node. And with standard polling I don't see a way of generating the voting list.

You need to distinct those specific nodes using taxonomy or a custom field, like a boolean field, say, 0 means no vote and 1 means needs voting. Then use the the flag module to filter those nodes. like this

UPDATE :

The basic idea is, when user flags a content, you can set all of the 1s to 0 in this way no more content will be votable. To do so you need to use hook_flag_flag function. in this function use node_load to load the nodes of boolean value 1, set it to 0 then use node_save to save the node.


Splitting up the .module file I wrote my first module which happens to be in Drupal 7. The module uses hook_menu to correlate URLs with three custom-coded, page call backs. These callback functions that construct the custom html are currently inside the .module file.

The file is getting a little long and I would like to put the three custom-coded page call backs into another file. My first attempt did not work this morning, I'm not sure what I did wrong...

1) Added this line to the .info file:

files[] = my_module.pages.inc

2) Placed the callbacks into my_module.pages.inc

What is wrong or missing in this approach?

You can enter a file parameter in the hook_menu function and the file will be included before calling the page callback function.

<?php
function my_module_menu() {
  $items = array();
  $items['my/custom/path'] = array(
    'title' => 'My title',
    'page callback' => 'my_function',
    ...
    'file' => 'my_module.pages.inc',
  );
  return $items;
}

Now, you can place your my_function in the my_module.pages.inc file.
You can place submit and validate handlers (forms) in this page as well.

files[] = my_module.pages.inc

will not work. It's to autoload classes. A good example would be Views file includes.


How to add a div class to menu link? I would like to add a specific class to specific menu item, so that the menu item would show an image on hover.

Basically I want to implement this in a menu item link:

Some_name

I have tried Menu Attributes module but I couldn't specified a class I wanted to add. Is there any other way how to do it please?

Menu CSS Names

  This is a very simple module that takes the link text of each drupal
  menu item and adds it as a css class name to the menu's element.
  Using these class names, each menu item can be styled separately with
  css. This is also very useful for css sprite techniques.

  There are no admin settings for this module, it starts doing its work
  once the module is enabled. All caches are automatically cleared at
  this time also. This module works with menus in blocks (including
  Primary Links) and menus in themes (menus that are enabled from the
  theme's configuration page).


Rendering a generic file field containing an image Drupal 7.34
Media 7.x-1.4
Views 7.x-3.8

I have a generic file field. Sometimes the uploaded file is an image, and in these cases I want to render it in a View as a thumbnail.
So I do the following:

Go to admin/config/media/file-types

Choose "manage file display" next to Image

Pick a View Mode, let's say "Small"
Check the box next to the Image display
Pick my desired Image style from the dropdown in the display settings

Add the file field to my View

Choose "Rendered file" formatter
Choose "Small" view mode
hit Apply

…and the view puts a big blank space where the image should be.
I've checked the database, and Drupal has correctly identified my upload as image/jpeg. It opens fine in the browser.
If I choose a different formatter in the view, like Table of files or Generic file, it shows up fine.
If I choose a different formatter in the file display settings, it still shows nothing in the view.
Am I misunderstanding something? What's going on?

Check admin/config/media/file-types/manage/image/display/media_small and check that File is actually being displayed and not set hidden.


How to send mail with multiple images from node using Rules module? $language = field_language('node', $node, 'YOUR _FIELD_NAME');
foreach($node->YOUR_FIELD_NAME[$language] as $file) {
  echo drupal_realpath(file_load($file['fid'])->uri);
}

I used this code to send mail in attachments but image file does not work

<?php
foreach($node->field_name['und'] as $file) {
  echo  drupal_realpath(file_load($file['fid'])->uri);
echo ("\n");}
?>

This code worked for me!!!


Commerce cart line item to show original price, not the one with discounts subtracted Using Drupal Commerce Kickstart, when the user is at the shopping cart and activated any kind of discount (most of the times, a coupon) the line item price in the Cart table is updated with the discount.

I'd like to show the original price there and let the Summary describe what kind of changes the prices went through.

Here is a screenshot that might help https://www.dropbox.com/s/matvseodarii41m/Screenshot%202014-08-19%2014.46.45.png?dl=0

I'd like the top Price value to be $395 and everything else could stay exactly like this.

How can I make this happen?

Thank you!

Maybe this could help you out. https://www.drupal.org/project/commerce_price_savings_formatter


How can i access MySQL of a local Acquia Dev website using the command line? Can we post about Acquia DevDesktop here? i cannot figure out how to log in locally to MySQL using the command line. i posted on their forum and got no response.

Local Acquia DevDesktop sites do not put the DB config info in settings.php. instead it refers to files in an a folder name .acquia which is hidden. on my set up, a typical included looks like this.

Users/myname/.acquia/DevDesktop/DrupalSettings/loc_mywebsite_local.inc

i have managed to open the DB array looks like this.

$databases['default']['default'] = array(
 'driver' => 'mysql',
 'database' => 'mydbname',
 'username' => 'drupaluser',  //this is real default setting for username
 'password' => '',
 'host' => '127.0.0.1',
 'port' => 33067 );

am kind of mystified why there is no DB password?

can any tell me how to access MySQL via the command line. very aggro right now, thanks!

The easiest way to access a CLI database on any site is with drush:

~$ drush help sql-cli
Open a SQL command-line interface using Drupal's credentials.

Examples:
 drush sql-cli                             Open a SQL command-line interface
                                           using Drupal's credentials.
 drush sql-cli --extra=-A                  Open a SQL CLI and skip reading
                                           table information.

Options:
 --database=<key>                          The DB connection key if using
                                           multiple connections in
                                           settings.php.
 --db-url=<mysql://root:pass@127.0.0.1/db  A Drupal 6 style database URL.
 >
 --extra=<--skip-column-names>             Add custom options to the mysql
                                           command.

If you don't give it any options, then it will use the normal drush magic to find the settings for the current site you are in or from the site alias that you are using.

$ cd /path/to/your/drupal/docroot
$ drush sql-cli

TL;DR, if you can drush to your site, you can instantly connect to it with drush sql-cli


How to order a node's taxonomy terms hierarchically? Are the terms in a node's taxonomy array ordered hierarchically by default?

If not, what is the most efficient way to do so?

No they are not ordered hierarchically by default...

In order to do it yourself you could take a look at the following functions: taxonomy_get_parents() and taxonomy_get_children().

Here is a great article with nice examples: http://davidherron.com/content/improving-navigability-drupal-taxonomy-hierarchies


How to create a View showing subscribed content? I want to create a view which will display all the posts user has subscribed to (very much like the Facebook homepage).

I have used the Subscriptions module for allowing the user to subscribe to posts, but I am unable to configure the Views.

Any help will be appreciated.

Subscriptions does not currently have views support.

There is an issue for it here - http://drupal.org/node/269472 - with a patch, however it is missing some parts and the author has not yet responded with the missing code.

I need it so I will be finishing the patch sometime in the next week unless someone beats me to it.

Until then, unless you want to code the views support yourself there is no views/subscriptions solution.


Drupal 6 Search module double ID's I'm currently busy with a website for a costumer. This website has to be W3C validated. There was a problem on the search page of the site with a double ID:

  Enter your keywords:

  <input type="text" maxlength="255" name="keys" id="edit-keys" size="40" value="" class="form-text" />

The ID: id="edit-keys-wrapper" comes up two times! This is not W3C allowed.

I've downloaded and installed a clean Drupal 6.28 to be sure it's not a theme error.

Is there a patch for this "problem"? If not, what is the best option to fix this without ruining core?

I can confirm this happens out of the box all the way back to at least 6.25.

You can 'fix' it pretty simply with the following code:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    unset($form['basic']['#id']);
  }
}

That gives this markup in place of the old:

  Enter your keywords:

      <input type="text" maxlength="255" name="keys" id="edit-keys" size="40" value="book" class="form-text error">

    <input type="submit" name="op" id="edit-submit" value="Search" class="form-submit">


Show count in view grouping I'm building a index view to use as search. I'm grouping the results by a term field and everything works fine. What I want to do is add a count after the group title to show how many results that exists with this term.

Can't find a way to do this in drupal 8 so I'm asking you.
I've google for half a day without finding anything.

Using this answer as a base you can add views_field_view to include a view of content filtered by term.

In more details

1. Create a view of terms that includes count of content using each term

Create a view that displays terms
enable aggregation
add relationship Content with term
add sort content uuid with aggregation type: count (optional)
add field content uuid with aggregation type: count
add field taxonomy term

Your view should look similar to the following

2. Create a view that will display the content

Include contextual filter on the vocabulary of your interest (tags in this case)
Add any filters or fields that you need

This view will look similar to

3. Add last view as a field to first view (step 1.)

Download and enable views_field_view module
Go to view from step 1. and

add field Taxonomy term: Term ID
add field Global view ) (made available from views_field_view)
on the settings find the view from step 2.
use {{ raw_fields.tid }} as contextual filter

Next screenshot shows the changes from original view and settings for view field

You are done

Your view now should display the terms with count and all the content that have used it.


Data export import failed to import into Drupal 7 I using "Data Export Import" module to export all articles from site Drupal 6 and import it to site Drupal 7.

I export all taxonomy terms in site Drupal 6 and import the dataset into site Drupal 7.

The error messages:

  There is a mismatch between the vocabularies in the dataset file and
  the current vocabularies - vocabulary name: News The Taxonomy Terms
  dataset file 20150824_113732_taxonomy_terms.dataset was not imported.

How should I correct the error?

It is possible you can't since this module wasn't created for 6-7 migration. (It's too bad, too.)
From the Data Export Import project page:

NB - This module has primarily been developed to move data between the same versions of Drupal - to move data between a live site and a development/beta site.
It may be possible that the taxonomy terms and users data files exported from Drupal 6 can be imported into a Drupal 7 site (or the other way around). This has not been tested yet and any feedback would be gratefully received.

You could try contacting the maintainer through the issue queue, see if it's a small thing they can fix, but since the project is currently looking for a new maintainer I wouldn't expect a quick response.


How to show hide other content fields when we select radio buttons? I have created 2 radio buttons. When i select 1 radio button, then represented field has to display and hide other field represented to next radio button.
When I select radio1, only textfield1 has to display and radio2, only textfield2 has to display.

This could also be done by using states that are available in Drupal core. For example you could set that an element in a form should only be visible if another element has the value "x".

    $form['my_element']['#states'] = array(
      'visible' => array(
        ':input[name="some_other_element"]' => array('value' => 'some_value_that_has_to_be_set'),
      ),
    );

More examples at form_example_states_form.

You can add states to elements in an implementation of hook_form_alter or add it directly to the form if you are programming it yourself.


How do I find what content is supplying my current page? I have a webpage on my site that doesn't have edit tabs, so I am not sure where this website is retrieving content. How can I find out what content represents this webpage? I am using Drupal 7.

Take a look if you can see the contextual "settings wheel" in the top right corner.
This can provide you with a direct link to edit the "page"/"view" or Panel that you are on


Site name\logo in a panel pane? I want the site's name\logo to appear in a column in a Panels pane (instead of it's regular appearance in the header region). is there any way to achieve this without programing?

Yes.

Go to the pane where you want the logo or site name. Click on the 'Add content' gear wheel and then you'll find the site name and logo under the 'Page elements' section.


How do I print the body of a node? I am struggling to work out how to print a node body on a page.

I normally use something like this print $node->field_manufacturer[0]['view']; but I am unsure how to print the body of a node.

How can I achieve it?

For Drupal 7, a better style is to use field_get_items. E.g.:

<?php
  $body = field_get_items('node',$node, 'body');
  print $body[0]['value'];
?>