How do I modify the "Formats" dropdown in CKEditor The CKEditor in Drupal 8 has a Formats toolbar button containing different text formats: "Heading 1", "Heading 2" etc. How can I add and remove items from this list?

I would use Styles instead of Formats, because styles are fully controlled by you, from admin interface, no need for editing files.

When you add it to the toolbar you can configure it and add as many elements as you wish.

Here is an example config:


configuring drupal to use unicode characters I'm working on a site for mathematics so every so often I have to deal with Unicode characters like "".  Right off the bat, this causes trouble for my Drupal 7.15.  For example: I create a Basic Page with Full HTML format, and paste that character in, and I get this error:

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value:
'\xF0\x9D\x94\x85' for column 'body_value' at row 1: INSERT INTO {field_data_body}
(entity_type, entity_id, revision_id, bundle, delta, language, body_value,
body_summary, body_format) VALUES (:db_insert_placeholder_0,
:db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6,
:db_insert_placeholder_7, :db_insert_placeholder_8); Array (
[:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 86234
[:db_insert_placeholder_2] => 29768 [:db_insert_placeholder_3] => page
[:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => en
[:db_insert_placeholder_6] =>  [:db_insert_placeholder_7] =>
[:db_insert_placeholder_8] => full_html ) in field_sql_storage_field_storage_write()
(line 448 of /home/joe/staging/drupal_planetary/modules/field/modules/field_sql_storage/field_sql_storage.module).

Now, I recognized that this was probably something to do with the way the database was set up, so I followed some guides around the internet, like this one: http://cameronyule.com/2008/07/configuring-mysql-to-use-utf-8/ and things are looking good, after a fresh install:

mysql> show variables like 'collation%';
+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database   | utf8_general_ci |
| collation_server     | utf8_general_ci |
+----------------------+-----------------+
3 rows in set (0.00 sec)

mysql> show variables like 'character_set%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)

I even adjusted the way the database is invoked inside settings.php:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'MYDB',
      'username' => 'MYUSER',
      'password' => 'MYPASS',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
                     PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                     )
    ),
  ),
);

But, no luck, I still get the error when pasting my .  Are there further database tweaks I should try?

One further note: I've tried running utf8_encode(...) on the content that I expect to have unicode symbols in it, and this works as a temporary work around.  In other words, I can save content, the pages display without problem.  But then I wait a while (24 hours?) and come back and the pages are full of garbled unicode expressions!

Can you help me figure out how to either make this workaround unnecessary, or how to make it work and stay working?

After further investigation: "" and other characters beyond the Basic Multilingual Plane need to be stored in a database set up with the "utf8mb4" charset.  The general configuration steps are very nicely described here:

http://mathiasbynens.be/notes/mysql-utf8mb4

In addition to updating MySQL to 5.5.28, and doing the basic tweaks outlined in that link, in order to get this working with Drupal, I needed to take some further steps:

Replace SET NAMES utf8 with SET NAMES utf8mb4 in includes/database/mysql/database.inc
Modify settings.php to include the following

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB',
      'username' => 'UN',
      'password' => 'PW',
      'collation' => 'utf8mb4_general_ci',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
                     PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
                     )
    ),
  ),
);

And modify the table and column (per the page linked to above) where the fancy UTF8 characters are to be stored:

ALTER TABLE tn CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tn CHANGE cn cn longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;


Global Filter as main menu drop down link I'm looking for right steps to implement Global Filter module not as a block, but rather as an main menu links. The biggest problem is that each user can see only links they have access to (taxonomy access). So it's not possible to make these links static.

I've tried to include a block in the menu link, but that's not what I want.

Has anybody an idea where I could begin?

To rewrite your taxonomy URLs (you should probably rewrite your question to this end) you can use the following.

/*
 * Modify taxonomy uris to point back to facetted search
 */
function my_module_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_my_module_term_uri';
}

/**
 * Rewrite term URIs to point to our search query.
 */
function _my_module_term_uri($term) {
  $path = null;
  // Do your stuff to get your path correct.

  // Return your path if you've managed to rewrite it.
  if ( $path ) {
    return array(
      'path' => $path,
      'options' => array(), // url style options
    );
  }

  // Otherwise just return the default.
  return taxonomy_term_uri($term);
}


Annotate term relationships with data via edit form I'm building a simple download area for a web site. All it should do is to provide material of lectures for users which are grouped into user groups. As I don't want to make the system to difficult I'm not using organic groups or similar but just a share taxonomy between users and my "document" content type. If a document has no terms of that taxonomy or the user has one of the documents terms the document will be shown. Here helps Access by Term (ABT) module perfectly.

However, one caveat is that the publish date of the documents is based on the group. Some groups. Thus some lecturers will use the same document in different courses. To avoid that someone can see the document too early I'd like to add a date to the document/term relationship and filter hide those documents by checking these values in a custom template.

Does anyone know how best to implement such a system. Thinking of adding multiple text fields and letting the editors add TERM NAME|DATE into it. Then I'll loop through all the values on creation of the teaser. Shying a bit away of creating my own module and database table to store maintain these values.

Just for reference. I found a solution: I used the field collection module to implement the needed relationships.


Can I highlight an invalid form field without assigning a message for it? I have a form which presents three input fields which are later combined into a single phone number. When that phone number doesn't validate (doesn't match /^\d{10}$/), I want to show a single message saying the phone number is incorrectly formatted, but I want to highlight all three input fields. Is this possible? The best I have come up with is this:

form_set_error('firstBox', $theMessage);
form_set_error('secondBox', " ");
form_set_error('thirdBox', " ");

This way, all fields are highlighted and I get the message only once, but I still get bullet points for the empty messages...

Is there a better solution for this?

D'oh.  In Drupal 6 at least, just call form_set_error(FIELD) without the message and it should highlight the field and not set a message.  You are sending a space, so you are getting a space as a message.

Code in Question:

function form_set_error($name = NULL, $message = '', $reset = FALSE) {
  static $form = array();
  if ($reset) {
    $form = array();
  }
  if (isset($name) && !isset($form[$name])) {
    $form[$name] = $message;
    if ($message) {
      drupal_set_message($message, 'error');
    }
  }
  return $form;
}


Theme suggestions for blocks in a region which has a dash in the name I have a Region in the theme called header-top. As you may notice this region has a dash in the name instead of an underscore.

This theme is a sub-theme of a master theme called Framework. I wanted to apply a certain template file to blocks in that region, so according to Drupal 7 Theme Hook Suggestions page I've created a template file called block--header-top.tpl.php and cleared the cache. After re-loading the page a few times, I inspect the HTML to see if this particular template file is being applied, but all evidence suggests that it's still using block.tpl.php. I've tried using template_preprocess_block and dpm-ing out the $variables and in there I see an array theme_hook_suggestions which has the following values: array(block__header-top, block__block, block__block__21). I've checked the existing template files and there's no template file named block--block.tpl.php or block--block--21.tpl.php. I've even tried to swap the dash with an underscore to be block--header_top.tpl.php but still no luck.

Finally I've switched the region name to become header_top and the renamed template block--header_top.tpl.php suddenly starts to take effect.

I'm wondering is there a certain naming convention for regions with dashes in the name? If so what would be the ways to try and find out what exactly the template name for this region should be? I'd like to not resort to renaming the region, as that may have a knock-on effect on modules and other template files which I may miss and mess up the production website.

Per the Theme suggestion docs you linked to the format for region-specific block templates go like this:

  An example of a region-specific template would be "block--sidebar_first.tpl.php"

It looks like Drupal flips _ and - in theme suggestions so

  block__header-top

becomes

  block--header_top.tpl.php

(I knew it replaced _ with - but I didn't know it was the other way round too; there may be more to it than that).


Unable to get PDFPreview working I have installed and setup PDFPreview module according to the instructions.  The PDF attachment file name has disappeared from the article pages with nothing in its place.  When I examined the HTML, there's an img tag pointing to the preview image, but it doesn't work.

When I access the preview image directly, it produces a 500 error with a (translated) error message indicating an error while producing the image.  The Drupal log at Reports > Recent log messages contains the error message

Unable to generate the derived image located at public://styles/medium/public/pdfpreview/3b350fd949abe27c0778b0f857ffa352.jpg.

I found this error report and tried the steps instructed in message #2.  I created the directory sites/default/files/styles/medium/public/pdfpreview/, have tested directory permissions up to 777, and tried switching the 'Image style' preference back and forth with no success.  The web server has ImageMagick 6.7.7-10 installed.

I have no idea how to even debug the issue further.  The Apache error logs contain nothing, and the Drupal error message doesn't provide any indication on what has caused the failure.

How can I further debug the issue?

Detailed Drupal error log:

(I have since reverted the configuration, so that users at least have the file name link visible.)

Its possible that there is an issue with ImageMagick.

Check your Drupal status report. Does it show any issues? Check the Image Toolkit page at admin/config/media/image-toolkit. Does it show any issues?
Check your PHP error log. More detail or a stacktrace may have been logged there.


How to move "description" below the "label" for a field in a form? Can I user form_alter to move move "description" below the "label" for a field in a form?

Let´s say I want to move the "description" of the "body" field for the basic page content type.

Have a look at Label help module. It just creates a second help field that will appear directly below the form element's label.

It is a simple way to turn around the problem.

Or try something like

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

  // move the help text from below the input field to directly below the field label

  $('.form-item .description').each(function () {  // description is the help text
    var desc = $(this);
    var label = desc.siblings('label:first');
     if (label.length) {
       desc.insertAfter(label);
     }
  })
  // the help text is tangled up in the text format stuff on a filtered text field
  $('.text-format-wrapper .description').each(function () {
    var desc = $(this);
    var label = desc.siblings('.form-item').find('label:first');
     if (label.length) {
        desc.insertAfter(label);
     }
  })
});

(thanks to El bandito !)


How to remove partricules and apostrophes in url I'm using drupal 8 and Pathauto.

I have title of the type (in French) Personnes d'Allemagne, I would like to delete d' to have like url personnes-allemagne.

Pathauto removes the apostrophes well, but preserves the particle before, which gives people-dallemagne.

I tried to add in the words to delete d' or just d, but it does not work. Pathauto continues to delete only the apostrophe and not the d.

I thought of replacing the apostrophe with a dash, but I would prefer to delete particle and dash.

Someone has a solution?

I have been able to achieve it with the Pathauto module 8.x-1.3, using the following settings (/admin/config/search/path/settings).

For Strings to Remove I used a, an, as, at, before, but, by, for, from, is, in, into, like, of, off, on, onto, per, since, than, the, this, that, to, up, via, with, d'
Under Punctuation, for Single quotation marks (apostrophe) ('), I selected No action (do not replace)

I used /content/[node:nid]/[node:title] as pattern for the nodes, and created a node with Personnes d'Allemagne as title. The path alias for that node has been set to /content/1/personnes-allemagne.

The disadvantage is that the apostrophe will not taken off from the path aliases, except when it is present in a string given for the Strings to Remove setting.


Prepend drag icon to each form element I am building a configuration form with a few sortable elements. I know, you can build a table using builtin Drupal draggable functionality (drupal_attach_tabledrag), but it's a bit too complicated for my task.

I am saving new order of elements inside a hidden input field value using Jquery UI Sortable function and dynamically set #weights in form elements:

    $weights = $config->get('sort_order');
    parse_str($weights, $weights);

    $form['el1'] = [
        '#type' => 'checkbox',
        '#title' => 'Title1',
        '#default_value' => $config->get('el1'),
        '#weight' => $weights['el1']
    ];

    $form['el2'] = [
        '#type' => 'checkbox',
        '#title' => 'Title2',
        '#default_value' => $config->get('el2'),
        '#weight' => $weights['el2']
    ];

Elements are draggable and sorting works fine. The only difficulty I have is prepending an icon to each element so that others could use that icon to drag elements up and down (just like Drupal does in a lot of configuration UIs).

I know you can create custom elements using #markup with an image tag inside it, or some div with image background. But adding custom markup to each element is problematic for several reasons:

I'll have to write different names for each markup separately. For example if I have a markup element:

$form['drag-icon'] = [
    '#type' => '#markup',
    '#markup'=> '

'
];

its name is drag-icon and to prepend it to another element, I'd have to use a different name each time (this is horrible).

Although it can be aligned well with the element using css, dragging on that icon, breaks the line while moving it up/down.
Would have to write this mark up manually for each element.

I also tried using a template file for this form, but among other things, I couldn't keep track of sort order inside it so easily as in buildForm() function using #weight.

I wrote a lot of explanations to show what I have tried.

I just want a simple method to append an icon to each element of the form to achieve something like this:

I want to implement this dragging functionality in Drupal 8,
may i know how you achieve draggable functionality in that or can you share the code


How do I get the node ID from the URL? So far, I came across these 3 functions in Drupal 7, but I am not really sure what the difference between them is, and which is more appropriated to get the node ID in a block preprocess function.

menu_get_object()
menu_get_item()
drupal_lookup_path()

Can you give me any insight?

I am not really sure what the difference between them is

menu_get_object() returns the object associated with the page currently shown. If the code is executed when Drupal is showing the page example.com/node/1, then menu_get_object() will return the node object for the node whose ID is 1; if the page being shown is example.com/user/1, then menu_get_object('user') will return the user object for the user whose ID is 1.
menu_get_item() returns an array containing an index for each field contained in the "menu_router" table. This includes:

path: the current path of the menu callback
load_functions: an array of function names (like node_load) to be called to load an object corresponding to a part of the current path
access_callback: the callback that checks if the currently logged in user has access to the menu item
page_callback: the name of the function that renders the page
title: the title for the page associated to the menu item

drupal_lookup_path() is the function that returns you the internal path associated with the alias passed as argument. If "homepage" is the alias associated to example.com/node/1, then drupal_lookup_path("homepage") will return "node/1". Path aliases can be associated to any internal paths, not only to node paths.

  and which is more appropriated to get the node ID in a block preprocess function.

If all you want to get is the node ID of the node currently shown, then you just need to use the following code:

if (arg(0) == 'node') {
  $nid = arg(1);
}

If you need to get the node object, then you can use the following code:

if ($node = menu_get_object()) {
  // Use the node object.
}

Of those snippets, the second is better, as it returns the correct node object for internal paths such as node/1/revisions/3/view.

Keep in mind that some preprocess functions, such as the ones for the page, or the node, have already a $variables['node']. This means that in those cases, you just need to use the following snippet in your preprocess function, without worrying about which function to use.

if (isset($variables['node'])) {
  // Check the node ID or other properties.
}

For other preprocess functions, check the documentation to see if there is any variable containing the node object. For example, that is the case for template_preprocess_comment() which makes $variables['node'] available to the preprocess functions for comments.


404 Could not find the controller I have a strange problem. This is my code:

function bd7_services_services_resources() {
  return array(
      'get' => array(
        'index' => array(
          'help' => 'Ritorna le immagini inserite.',
          'callback' => 'bd7_services_get_immagini',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
        ),

          'actions' => array (
            'immagini' =>
              array(
                'help' => 'Ritorna le immagini inserite.',
                'callback' => 'bd7_services_get_immagini',
                'access callback' => 'user_access',
                'access arguments' => array('access content'),
                'access arguments append' => FALSE,
              ),
          ),
          'operations' => array(
              // Define the index callback for a GET to /cart.
            'immagini2' =>
              array(
                'help' => 'Ritorna le immagini inserite.',
                'callback' => 'bd7_services_get_immagini',
                'access callback' => 'user_access',
                'access arguments' => array('access content'),
                'access arguments append' => FALSE,
              ),
          ),

      )

  );
}

If I call "rest/get" all works.

If I call "rest/get/immagini" I receive "404 Not found : Could not find the controller."

If I call "rest/get/immagini2" I receive "404 Not found : Could not find the controller."

Where is my error ?
"rest" is my "Path to endpoint".

Thanks.

I have also create custom resource using services module like:

function vintervals_resource() {
  $api = array(
'registration' => array( // Resource name
'operations' => array(
    'create' => array(
    'help' => 'Ticket System',
    'file' => array(
        'type' => 'inc',
        'module' => 'My_module_name',
        'name' => 'includes/My_module_name.services',
    ),
    'callback' => 'My_custom_callback', // callback
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'access arguments append' => FALSE,
    'args' => array(
        array(
        'name' => 'body', // parameter name in callback
        'type' => 'string',
        'description' => 'Function to perform',
        'source' => 'data',
        'optional' => FALSE,
        'default' => '0',
        ),
    ),
    ),
    ),
)
);
return $api;
}
   // callback
 function My_custom_callback($body)
 {
      // Your work here..
      $json_array = array($body);
      $json = json_encode($json_array);
      $body_Array = json_decode($json);
      $applicationId = $body_Array[0]->appno;
      $emailid = $body_Array[0]->emailid;
      $mobileNo = $body_Array[0]->mobno;
      $password = $body_Array[0]->userpwd;
      $returnArray = array('status'=>FALSE,'application_status'=>-1);
      return $returnArray;
 }

URL of my web service call is :

My domain + My endpoint + resourcename

"mydomain.com"+"api/ticketsystem"+"registration"

But it will not working directly in the browser.
For this I have sent post request to server with parameters and receive it in my callback then it's working perfectly.


How to invite Facebook, twitter, gmail friends into organic groups How can i invite Facebook, twitter,Gmail friends in to my Organic Groups in Drupal 6.
Is there any possibility about this. Let me know.
Thanks,
Thiru

You can make use of Contact Importer module.

  Contact Importer provides a form for your users to enter their email
  address and password. The contacts from their address book are then
  retrieved.

Of course you need to alter the module to send invites.

Or

Try using Rules Module with this, to make it a chained process.


Set permission for a specific column in view for table format in drupal 8 I have created a view in table format and added a field as global custom text field. I want to show this field to administrator only, not to other created roles. How can I do that?

you need to do something like this in global php field :

$uid = 1;
$user = \Drupal\user\Entity\User::load($uid);
$roles = $user->getRoles();
$v=$roles[1];
if($v == "administrator")
{
echo "your-content";
 }

Global php field will be available as Replacement pattern add that variable in your custom text field.


Permissions deselected, but user can still edit content Reproduce:

Create new content type with uid:1
In admin/people/permissions you can see that permissions are not given to Administrator role, they are deselected/unticked by default for the new content type.
E.g. create new user and give him Administrator permissions.
The new Administrator user (non-uid:1) can still edit/create/delete the new content type contents although the permissions are deselected?

How's that?

You need disabled option "view, edit, delete any content". If this option is checked, next options not used.


How to get custom entity data in custom page i have created Event entity, and I have custom page.

I want to load ALL Entity rows and then use it in my template.

This is the way everyone is prsenting, but i don't know how can i get NID value

$events = \Drupal::entityTypeManager()->getStorage('event')->load($nid);

Using Symfony i could do this like:

$events = $this->getDoctrine()->getRepository(Event::class)->findAll();

This is the solution

$storage = Drupal::entityTypeManager()->getStorage('event');

$nids = Drupal::entityQuery('event')->execute();
//Load all nids
$events = $storage->loadMultiple($nids);
//You can also use
$events = $storage->loadMultiple();


How to hide webform Results tab in webform? On my Drupal 7  how hide webform Results tab?

You can hide webform Results tab by restricting user's permission access e.g. uncheck the following checkboxes in permission section :

1. view all webform results.
2. view own webform results.


Can't delete entities using entity_delete_multiple() I was studying how  to work with entities following http://www.bluespark.com/blog/drupal-entities-part-3-programming-hello-drupal-entity.

I downloaded the module, created by the author of that article. Then I wanted to delete entities, using the following code.

entity_delete_multiple('basic', array(1,4) );

But it didn't delete anything. I though that the delete method should be implemented, and added it into the class.

class BasicController extends DrupalDefaultEntityController{

  public function delete($basic) {
    var_dump(1);exit;
    db_delete('basic')
      ->condition('basic_id', $basic->basic_id, '=')
      ->execute();
    field_attach_update('basic', $basic);
    module_invoke_all('entity_delete', 'basic', $basic);
  }
};

It doesn't work: 1 is not printed.

How do I delete an entity with fields?

entity_delete_multiple() is implemented by the Entity API module, which is not part of Drupal.

In order to be able to delete entities with entity_delete_multiple() you need to do one of two things.

Define a deletion callback for your entity
Use a controller class that implements EntityAPIControllerInterface

In fact, this is the code used by entity_delete_multiple().

function entity_delete_multiple($entity_type, $ids) {
  $info = entity_get_info($entity_type);
  if (isset($info['deletion callback'])) {
    foreach ($ids as $id) {
      $info['deletion callback']($id);
    }
  }
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
    entity_get_controller($entity_type)->delete($ids);
  }
  else {
    return FALSE;
  }
}

In the first case, you simply define a function similar to the following.

function basic_delete_entity($id) {
  // Delete the entity whose ID is $id.
}

You can use any name for the delete callback, as long as you refer it in your hook_entity_info().

In the second case, you normally sub class EntityAPIController. EntityAPIController::delete() should normally be sufficient.


How do I insert a   tag outside the   tag on my main menu I have been scouring the web trying to find a way to get a  tag just AFTER each of my main menu items. Looking at this solution I am able to get a  tag in there, but it's INSIDE the link. I just don't want it to be a link.

I'm pulling my hair out trying to figure this out. I just don't know enough PHP to place it outside the link. This is what I have so far in my template.php:

function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}

if ($element['#original_link']['menu_name'] == "main-menu"){

$element['#title'] .= ''.$element['#localized_options']['attributes']['title'].'';
}

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

Any help would be great!

If you want your menu link to be like this
Link 1Description
, ie., the description is outside the  tags, then try the code below.

function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $description = '' . $element['#localized_options']['attributes']['title'] . '';
  }

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

The reason your code didn't work was, you used the description tag within the l() function. In drupal the l() function always renders an  tag and so the description was inside the  tag.


See what database a site is connected to Is there a page in Drupal 7 (or a module) that will show me what the name of the database is that the site is pointing to?

I know this can be done via settings.php, but I am setting up a build procedure that I can have lower level developers (or even non-developers) handle and a UI would be better.  I recently had an issue with two sites pointing to the same database and it borked some things up.  I want to add checking this setting to our build procedures.

I think this is what you are looking for:

https://drupal.org/project/show_database_name

  Display the host and database name of the default database on the status report, toolbar (Drupal 7) and/or on the admin_menu bar if enabled (either Drupal 6 or 7) and/or in a block (to use with the admin module).

It is marked as dev but it looks like a simple use-case and I don't expect there should be any problems.


How can I theme the Responsive Image module in a specific Paragraph Type I have a responsive image field inside two different paragraph types. I am on Drupal 8.3.7. I want to theme the module in one paragraph type but not the other.  I want to render a modified version of this code :

https://api.drupal.org/api/drupal/core%21themes%21stable%21templates%21field%21responsive-image.html.twig/8.2.x

I tried putting my modified code inside responsive-image--field_my_resp_image.html.twig but it is not being used. I can't seem to find the correct filename for a theming a responsive image from a specific paragraph type. Any ideas?

My goal is to render embedded CSS for a background image instead of the HTML picture element that responsive images uses. Is there a better method than what I'm attempting above?

I found a solution, but I'm honestly not happy with it.  I can use 'responsive_image_style_id' to identify this responsive image. The problem with this approach is that it relies on specific keywords ('_style') in 'responsive_image_style_id' and if a site admin changes that, it will break :

function paia_theme_suggestions_responsive_image_alter(&$suggestions, $vars, $hook) {

  $newHook = str_replace('_style', '', $vars['responsive_image_style_id']);

  if ($newHook != $vars['responsive_image_style_id']) {
    $suggestions[] = $hook . '__' . $newHook;
  }
}

It seems I am using entirely the wrong approach for this, and I should probably be rolling my own module or something totally different. But I have a deadline to meet and I need to move on.


Drupal on nginx: 404 Error I'm migrating my drupal websites from a server running with Apache web server to a Nginx server. The problem is, I can't access any of my websites on the nginx server. It redirects me to a 404 error page for all websites.

Any suggestion?

Were you using clean URL's before the migration?  If this is the case, than you may need to set up mod_rewrite only for nginx. I have not used the server but found this article on how to achieve the same.

http://wiki.nginx.org/NginxHttpRewriteModule

Not sure if this is your problem though, although it might be.


How to insert user table I would like to know how I can show registered users in a table with profile pictures like this site has. I would like to make this kind of site where actors can make a profile so they are put in a actors user role and that I can give people who look for actors an other role, so they can look for them in the database and actors can't. I am kind of a newbie to this sorry for that. Thanks!

The Views module is typically how this kind of thing is done. There are options for outputting tables or unstyled divs that you can theme yourself.


Overriding hook_preprocess_html page contents set by a module I want to override/remove some HTML added to page_bottom by a Drupal module, using a second Drupal module.

I tried to use hook_page_alter but this appears to be run before hook_preprocess_html as I can't see the content that the first Drupal module inserts in the page variable at that point.

The only solution I've found at the moment is to use hook_process_html and remove the unwanted HTML from page_bottom using regex - at this point all page_bottom additions are merged into a single array value so I can't just unset the unwanted value. This seems very messy.

Edited to add, here's the preprocess hook from the original module:

function module_one_preprocess_html(&$variables) {
  $theme_variables = array(
    'var1' => $var1,
    'var2' => $var2,
  );

  $variables['page']['page_bottom']['module_one'] = array(
    '#markup' => theme('module_one', $theme_variables),
  );
}

Check out John Albin's graph for the different preprocess functions you can use http://john.albin.net/sites/default/files/theme-system.png (from http://john.albin.net/drupal/arrays-of-doom) for a "complete" reference of what could be happening.

Without looking to the code to see if you've got another alternative (such as field_attach or another render option), I'd go for hook_process, that's always going to go after preprocess. If it's a theme function, you can use hook_theme_registry_alter and override the theme callback.

Now an answer after seeing the code.

If you want, you can stick with hook_process_html, but as you said, the content is already rendered and is way harder to remove.

One thing you can do is to increase the weight of your second module in comparison with the one that has the preprocess that you want to override, that way, you could do a preprocess_html and it always will come after the other one.

A couple of ways of doing this, one is on hook_install as you can see in this doc page: https://www.drupal.org/node/110238

  $weight = db_select('system', 's')
              ->fields('s', array('weight'))
              ->condition('name', '[the_other_module_name]', '=')
              ->execute()
              ->fetchField();
  db_update('system')
    ->fields(array('weight' => $weight +1))
    ->condition('name', '[your_module_name]', '=')
    ->execute();

If you can't or don't want to do this, there are a couple of modules that can help you: Modules weight and Util


Temporary Drupal hosting I'm not entirely certain that this question belongs here but here goes. I've built a pretty basic Drupal site for a department at my University but now I need to migrate it from my laptop to the public. In order to do that I have to jump through a -lot- of hoops with the ITCS department of my University but the site needs to go live pretty soon (within the next 4 days or so) because it's currently hosted on my laptop and I'm leaving the country.

So, what I was wondering is: is there somewhere that I can put this thing for free for a while so that the folks I'm working with can get used to it and show it off (it's for grant purposes) while I work with ITCS to get it up on University servers?

I can't really do it and they don't have any one who can show them how (I'm working remotely) so it's been a pretty big hassle getting this thing off the ground.

Thanks!

I'd look for cheap shared hosting. Make sure you get PHP and MySql and some kind of temporary URL.


How can I filter a view by Content Type -or- Taxonomy Term and have both sets of items show? I have a basic view that works great. It shows a list of nodes that are filtered by content type.

To that list of allowed content types, I want to add a taxonomy term. That is, the view should show anything that is a certain special content type, but ALSO include any node that has a certain special taxonomy term, no matter what the content type is.

The view that already works fine has its filter setup this way:

FILTER CRITERIA:

Content:  Content type (is one of: Blog, IM, PI)

Easy, no problem. To add the taxonomy term, I set it up this way:

FILTER CRITERIA

    Content:  Content type (is one of: Blog, IM, PI)  OR
    Content: Has taxonomy term (= News Release) | Settings

Here's where it went all wrong on me. As soon as I added the taxonomy term filter, the items that should be there by Content Type completely disappeared. Only items with the taxonomy term show up in the view now. If I remove the taxonomy term filter, then items in the Content type pop back in again. It's like the taxonomy filter suppresses the content type filter in some way.

I tried:

using Content: Resource Type (= News Release) | Settings which was an alternate way of listing the taxonomy, "Resource Type" being the vocabulary
using AND instead of OR but, as you would expect, that returned no results at all because I do not have any of the special three content types that are also labeled as the special taxonomy "News Item". They are separate use cases.
using filter groups, listing the content type, an OR, and a content type AND taxonomy:

Content:  Content type (is one of: Blog, IM, PI)
OR
Content: Content type (= Article) AND
Content: Has taxonomy term (= News Release) | Settings

To be clear, either the node is a special content type OR the node is a regular content type with a special taxonomy term. Never both. Both types of nodes should appear side-by-side in this view.

Am I not allowed to make a view that shows stuff filtered by taxonomy alongside stuff filtered by content type at the same time? Can anyone suggest something for me to try?

For others Solution is adding a views relationship
see Documentation: https://www.drupal.org/docs/8/core/modules/views/add-a-relationship-to-a-view


Correct way for Attributes in Commerce I am building a small web site which offers photography services. So, basically, I offer some services and these services do have some additional options (attributes). For example, service:

Single product on photo
Group products

And attributes:

Delivery: standart or rush (+$5)
Background color: white or black (+$1)

I found at least three ways how to add attributes, but a little bit confused which way is correct.

Using Taxonomy: Drupal Commerce - Product Attributes.
Using the Commerce Pricing Attributes module:

Drupal Commerce Pricing Attributes Module Installation and Configuration.
Drupal Commerce Tutorials - Products With Attributes.

My question: which way is correct and better for me? I like the Commerce Pricing Attributes module because it is more understandable, but as we can see this module is not very popular.

There are always different ways to do things in Drupal. Drupal Commerce (DC) is the shining example of this. DC allows for project attributes out of the box using fields on product types that are set to be attributes (this creates an AJAX field as a select option in the add-to-cart form). This is an example of attributable fields. You will notice the price and the photo changes when you change the video type. You can also handle some attributes with line items added to an entire order (this is how shipping is done). If you have global attributes, the best way would be a line item added to the entire order.

You list delivery and background color; I am going to assume these would be global attributes that would apply to any order in your store. These would be prime candidates to use line items added to the order. But this also depends on how you are going to allow your customers to purchase products.

I would need more infomration about how you want to setup your shopping experience to be able to completely answer the question.

DC is an extremely powerful and flexible shopping cart. But it is complex.


webform date popup format I have a webform with a popop date the problem is the date in the textbox is shown in the format

2014-7-30

it need it to be

30/7/2014

how can I change this?

I use webform 7.x-3.20 it doesn't give text box option for date field rather it show select list except for year. If in your case it showing textbox make sure the configuration is as followed.

You can create new date format under date and time settings, Go to admin/config/regional/date-time/formats

Add new format in the form j/n/Y it will show date as 30/7/2014.

Under webform date field setting choose the Default value timezone to "Website timezone"

P.S If you want to reorder select boxes then see: Re-ordering the elements of a Drupal Webform Datepicker


Which node table in Drupal 6 stores the node published date, created date timestamps? I need to write a query to retrieve all nodes and their published dates for a Drupal 6 website and I would like to know which database table holds the nids and the timestamps. I am aware that there are 6 tables dedicated for storing info related to nodes.

I know about node_load but I do not want to use that?

The node created and updated timestamps are stored in the base "node" table.

e.g

$result = db_query("SELECT nid, title, changed, created FROM {node} ORDER BY nid ASC LIMIT 10");

while($row = db_fetch_object($result)){
  // drupal_set_message($row->title);
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}


How to attach a paragraph to a node using node_updatehook? I am trying to attach a paragraph, to a node. I am currently trying to do it in node_update hook.

The value for paragraph will come a custom field. Currently am trying to achieve this with hard-coded value. I tried two methods, but both are not working.

Method 1

function my_module_node_update(Drupal\Core\Entity\EntityInterface $entity) {

  $paragraph = Paragraph::create([
  'type' => 'attendance',
  'field_stakeholder' => array(
      "value"  =>  '. Roshni, UPS Kharwna from Dunda, Uttarkashi (UTK_130000377) (49645)',
    ),
  ]);

  $paragraph->save();

//this is working
 dpm($paragraph->id());

 $current[] = array(
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    );

   $entity->set('field_attendance', $current);
   $entity->save();

}

Method 2

function my_module_node_update(Drupal\Core\Entity\EntityInterface $entity) {

  $paragraph = Paragraph::create([
  'type' => 'attendance',
  'field_stakeholder' => array(
      "value"  =>  '. Roshni, UPS Kharwna from Dunda, Uttarkashi (UTK_130000377) (49645)',
    ),
  ]);

  $paragraph->save();

//this is working
 dpm($paragraph->id());

   $entity->field_attendance->appendItem($paragraph);
   $entity->save();

}

However, I am getting an error:

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity
  constraint violation: 1062 Duplicate entry '213436' for key 'PRIMARY':
  INSERT INTO {node_revision} (nid, vid, langcode, revision_timestamp,
  revision_uid, revision_log) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 41374
  [:db_insert_placeholder_1] => 213436 [:db_insert_placeholder_2] => en
  [:db_insert_placeholder_3] => 1535117690 [:db_insert_placeholder_4] =>
  1 [:db_insert_placeholder_5] => ) in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 777 of
  /home/rupali/fa-rupali/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

I feel like the error is coming as the hook is called twice. The code is working till paragraph creation. I am able to verify it.

I used this code in hooky_entity_presave

       $paragraph = Paragraph::create([
              'type' => 'attendance',
              'field_stakeholder' => array(
               "value"  =>  '". Seema Bist, PS Manjkot from Dunda, Uttarkashi (UTK_130000379) (49647)"',
               //"value"  =>  '49645'
            ),
          ]);
              $paragraph->save();

            $entity->field_attendance->appendItem($paragraph);

Paragragh array is display (target id), but didn't display value of target id  in input value.
in
Means data added in node__field_at table, but not target id with node id is doesnt add in paragraph__field_st (st is entity reference field in paragraph type.

How to save data in paragraph entity reference field


CKEditor break quotes: Why? On the forum I made a quote using the Quote module. It works fine for the administrator, but it doesn't work for the anonymous users.

The module defines a function, called via an ajax request, which filters the text before passing it to the editor, to prevent certain XSS attacks on content edits (that the JavaScript library might not handle). Because the function did not check a CSRF token for anonymous users, it was possible to perform reflected XSS against anonymous users via CSRF.

Quotes breaks the function module (line 229 in "ckeditor\includes\ckeditor.page.inc").

function ckeditor_filter_xss() {
  header('Content-Type: text/plain; charset=utf-8');
  $GLOBALS['devel_shutdown'] = FALSE;
  if (!isset(
$_POST['text']) || !is_string($_POST['text']) || !isset($_POST['input_format']) || !is_string($_POST['input_format']) || !isset($_POST['token']) || !drupal_valid_token($_POST['token'], 'ckeditorAjaxCall', false)) {
    exit;
  }

I need to fix it.

Can I delete ckeditor_filter_xss()?

If deleting any function from a contributed module works for you without giving any issues, then it's totally ok except that the next module update will override your change and you will have to delete the offending lines again. So the best course is to report this to the contributed module's developers, so they fix and commit necessary changes.

By the way, this seems to have already been reported on https://www.drupal.org/project/ckeditor/issues/2957580.


Adding autocomplete to a CCK text field I have a form with a field which I would like to be an autocomplete field.

I've tried the form_alter hook:

function autocomplete_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == office_node_form) {
    $form['field_office_name'][0]['#autocomplete_path'] = 'autocomplete';
  }
}

The autocomplete path is correct because I use it elsewhere for another field in another form but the field it's not working as autocomplete.

Anything else I should change in the form_alter hook in order to make it work?

Why don't you try Autocomplete Widgets for Text and Number Fields

This module adds 3 autocomplete widgets for CCK fields of type Text and Number.

Autocomplete for allowed values list: This widget can be used for Text and Number fields and it takes candidate values from the defined list of Allowed values of the fields. You can even generate your allowed values list using PHP, so the limit to provide a widget with autocomplete features is your imagination!
Autocomplete for existing field data: This widget can be used for Text only and it takes candidate values from existing values in the database for that field.
(7.x only) Autocomplete for predefined suggestions: This widget can be used for Text only and allows an admin to provide a list of suggestions but still allows users to enter anything they want in a text field. Use this widget to help avoid (but not prevent) variations of the same value. Ex: burger, hamburger, Burger ...
(7.x only) Autocomplete for existing field data and some node titles: This widget works just like the "existing field data" widget above except it will also suggest node titles for nodes of a specific content type(s).


Taxonomy terms with associated nodes: display page by page navigation in node page? Hi i have a content type called Product and have fields(title,description,code,image) and also have vocabulary categories like below formate

parent term 1
 -child term 1
    --sub child term 1.1
    --sub child term 1.2
    --sub child term 1.3
    --sub child term 1.4
    --sub child term 1.5
parent term 2
  --child term 2
    --sub child term 2.1
    --sub child term 2.2
    --sub child term 2.3
    --sub child term 2.4
    --sub child term 2.5
.
.
parent term 5
  --child term 5
    --sub child term 5.1
    --sub child term 5.2
    --sub child term 5.3
    --sub child term 5.4
    --sub child term 5.5

so i want to display my product node page first parent terms list when i click parent term 1 then it's display all related child terms in next page after that when click child term 1 display all related sub child terms list in another page after that when i click sub child term 1.1 need to display related products list with above fields.Please find below flow of screen shots.

Taxonomy Parent Terms list
Step 1

Step 2 when i clk Parent term 1 need to display all related child terms in another page like below

step 3 when i clk child term 1 need to display all related sub child terms in another page like below

step 4 when i clk sub child term 1.1 need to display all related node i.e product items list with above fields info.

Please advice
Thanks.

For this you will have to use view module.

Step 1: Create a new view from Administration > Structure > View. Click on + Add new view.

Step 2: Give a name to your new view. From 'Show' select Taxonomy terms and from type select appropriate taxonomy vocabulary (I assume name is 'product' here). Check either page or block and click 'Continue & edit'.

Step 3: In First Page or Block under 'Filter Criteria' click on Add and select Taxonomy Vocabulary and set it to use product. Click on Add again from Filter Criteria and select Taxonomy term and set it to Parent term 1, Parent term 2, ..... Now in preview section you will see the Parent terms.

Step 4: Under FIELDS click on Add and select Taxonomy term: Term ID and click on Apply. In Configure field page check on Exclude from display and click on apply. (I assume Taxonomy term: Name is already there.)

Step 5: Rearrange the order of fields by clicking on drop down icon besides Add under FIELDS. Make user the Term ID appears above Term Name and Apply.

Step 6: Click on Taxonomy term: Term Name and expand REWRITE RESULTS. Click the checkbox Rewrite the output of this field and in text area name Text, type in [name] and Apply.

Step 7: Create a new page in same view +Add > Page or create a different view as in Step 1 & 2.

Step 8: In new view page set the path under PAGE SETTINGS to subchild/tid (here tid refers to parent tid or taxonomy id).

Step 9: Follow the steps 3 to 6. Instead of Parent term 1, select Child term 1.1, Child term 1.2, ... assuming Parent is 1. And set href to child/tid for step 6 here tid refers to child term 1.* tid.

Step 10: Follow the same procedure as in step 8 & 9 for other child terms.

Step 11: Follow the same procedure as in Step 8 to 10. However set path under Page Settings to subchild/tid and href attribute for step 6 would be product/tid, here tid is subchild tid or taxonomy ID.

Step 12: Follow the same procedure as in Step 11 for all subchild terms.

For Displaying Products:

Step 1: Create a new View from Administration > Structure > View. Click on + Add new view.

Step 2: Select Content from Show with appropriate type. Check on page and click on Continue & edit.

Step 3: Set the path in Page Settings to product/tid and from Filter Criteria select the Taxonomy term appropriate to the product to be displayed.


How can I check if a module is enabled? In Drupal 7, you can use module_exists() to check whether a module is enabled (as well as whether it exists).

For example,

if (module_exists('devel')) {

How can you check whether a module is enabled in Drupal 8?

Just like Clive mention....

injecting the module_handlerservice would be preferable to using \Drupal (assuming it's an option in current context)

Here is an example of checking if a module is enabled using a service (without injecting it).
$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('devel')) {
  // Code Here
}


Specification of an Image field attached to forum topic node type? I have somehow a strange issue with Fields : I've created an Image field for each of my content types. This image field allow the insertion of images into the node body with Insert and Colorbox. Everything work as wonder for all the content types... except for forum topics.

Indeed, when creating a new forum topic, my users can't see the Image field in the form. Also :

Admin can see it, but not other users
Users can perfectly see Image field when creating a new content of other type.

I've also checked : it's not a question of CSS or other modules hooking the field.

Do you have any idea of what has to be done ?!  :/

have you created one image field that is shared between all of your content types, or a different image field for each content type? if it is the latter, this sounds like it is likely a permissions problem where one of the image fields is restricted to admin users only.

i'm not sure about D7, but there's a module in D6 called "content permissions" that seems like you should enable it but you really should avoid it if you can. There's probably an equivalent in D7 - the module denies access to all new fields for all user roles by default, and you have to explicitly give permissions back.

alternatively, it could be a caching issue. Drupal caching is much less aggressive for admins than for anonymous users so if you've made a few changes to your views that admins can see but anonymous can't, try clearing your site's cache.


Ajax call while adding node I have created a content type 'Property', has fields 'Property name','Address line1','Address line2','Address line3'.

I don't want to add duplicate properties in database, so that I want an AJAX call while filling above fields and check is there any property available in database or not with current provided values of fields.

If there is any one result, I want to show it on modal.

The only problem is, Where should I write an AJAX code?, And where will the business logic ?.

Is there any way to do this?. kindly suggest me. thank you.

You'll need to use a validation function alongside an ajax call to check for validity, you might want to look at other solutions like How to validate and submit a form using AJAX? to get an idea about how this could be done.

If you are using the Addressfield module (D7) you may find some of these problems are already taken care of, or are easier to solve than with a standard set of input fields.


Will Drupal or PHP use APC if its installed on the server? So I have AuthCache installed with XCache but I am not getting any noticeable speed. Im on D6 so its not possible to use APC?  I mean if APC is installed on the server , will Drupal use it even if I don't install the APC module?

Thanks!

Drupal, like any other PHP app will an APC opcode cache if it's available.  Though there are a few settings that may prevent Drupal from using APC as it should.

First and foremost make sure APC has enough memory to work with.  Drupal can eat up a ton of memory and if your APC cache is too small it may actually hurt your performance.

The first memory relevant setting I would look at is the apc.shm_size.  APC's defaults setting have never worked out of the box for any of my Drupal installs. On some servers I have this is as high as 512M.

apc.shm_size = <MB Allocated>

APC may not be caching .module and .inc files by default!

Depending on your setup, APC may not be caching .MODULE and .INC files at all. This means that the majority of Drupal's slowest code may never make it to the APC cache in the first place.

The fix?  apc.filters

On many of my Ubuntu servers adding the following line to my apc.ini has an enormous performance impact on my Drupal installs.

apc.filters = "+module$,+php$,+inc$,-admin"

You may also want to monitor your APC cache using the apc.php script that's generally bundled with APC.

You can also use apc.php to verify that .module and .inc files are making it into your APC system cache.


Insert videos from media module into Ckeditor I've been working the media module and inserting images with the ckeditor media widget and It's been great.

I've also used some embbed media plugins to add vimeo and youtube media elements wonderfully.

But when I try to insert some of this media into the ckeditor it only inserts the rendered image form this media instead of the widget i get when I render the media in a node.

I need to know if I have to configure the file-types/ output in the media module or config anything in the ckeditor.

Thanks

I believe this is just how it works with the media module.  You might could experiment with the http://drupal.org/sandbox/DevinCarlson/1823634 to select the view modes for files displayed inserted into wysiwyg editor.


Should I use Drush or Drupal Console with a new site? Between Drush and Drupal Console, which seems to have similar functionalities, which one should I install?

You should use Drush.
Drush is about to be added to the drupal/recommended-project, see #3159647, while Drupal Console seems to be abandoned and currently is incompatible with Drupal 9 due to mismatched dependencies, see #4251.
Maybe Drupal Console finally accomplished its mission by triggering the modernisation of Drush. And there's no need for two CLIs. Now forces can be joined again.


hook_node_access called more than once I have this very simple implementation of hook_node_access

function applx_node_access($node,$op,$account){
    drupal_set_message($node);
}

This returns

applx_application
forum
article
page
forum

And because of this i am not able to proceed further. I'm not sure why it prints the name of all bundles.

$node contains all the content-type in your application as value. So, you need to set your node access based on the $node value.

function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if($type == 'forum') {
    //set your permission based on $op value.
  }
}


Wrong number of Cart items in Foundation theme topbar I use AuthCache and Drupal Commerce in my Drupal 7 site. I am currently building a new Foundation subtheme for the site with the Foundation topbar activated for mobile only.

Now, to show the number of items in the cart I simply replace the default cart block content with this in my template.php:

function mynewtheme_block_view_alter(&$data, $block) {
  global $user;
  if ($block->module == 'commerce_cart') {
    if ($order = commerce_cart_order_load($user->uid)) {
      // Count the number of product line items on the order.
      $wrapper = entity_metadata_wrapper('commerce_order', $order);
      $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      if($quantity){
        $data['content'] = ('('.$quantity.')');
      }else{
        $data['content'] = (' (0)');
      }
    }else{
      $data['content'] = (' (0)');
    }
  }
}

The above shows a basket with the number of items in the cart.

Then, to show the number of items also in the Foundation topbar on mobile devices or narrow windows I use this code in a preprocess_page hook in template.php:

  $cartblock = block_render('commerce_cart', 'cart');
  $vars['varukorgen'] = $cartblock;

Followed by this line in page.tpl.php:

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

Now to my problem... the number of items shown by the variable $varukorgen in page.tpl.php is incorrect on smaller window sizes when the topbar is toggled. It think that is shows a cached version of the number.

In the AuthCache settings in the block in question i have set "Never" for the Cache lifetime, Per user and I also enabled Ajax.

So why is the number not showing correctly when it is rendered by means of a custom variable in page.tpl.php?

EDITED: the solution was as suggested below to create a new region in the .info file, place the cart block in that region in the UI and then render that region inside the topbar region in page.tpl.php like this:

    <?php if ($page['topplist']): ?>

        <?php print render($page['topplist']); ?>

    <?php endif; ?>

Now the the number of items in the cart is updated as it should on every page by the means of Ajax (enabled in the cart block).

You don't want to put this code directly into your tpl, as it will indeed cache. What you want to do is create a region in your template and then add your cart block to that region in the UI. You will also have to set that block to load via ajax or ESI so that it works properly with Authcache. You will see those settings if you go to configure the block.

Ideally you don't ever want to include any code that "does stuff" in your tpl files, as it can get cached. This is more obvious in Drupal 8 thanks to twig making this harder, but it is very easy to do incorrectly in Drupal 7.

You can be even more efficient if you change your code to save the cart quantity as a session variable or cookie and only calculate it when the cart changes, thus saving you from performance heavy order loads on every page. This is outside of the scope of your initial question though, but I thought I would mention it.


How to use the youtube module? I've added and enabled the YouTube module and I'd like to put a YouTube video on my page but I can't figure out how.

I think there is a youtube widget somewhere but I can't find it or get it onto my site.

I assume you mean this module? https://www.drupal.org/project/youtube

If so this module provides a field for your content type of choice where you need to display the video. The most basic content type to start with is "Basic Page".

Once you add this field, when you "add content" for this youtube field you can specify it's URL. When you view this node/entity the video player should show up. This module does have the ability to render the Youtube player, but there's a chance you may have to configure your content type view mode.

This Youtube video has more details on the setup for the Youtube Field module - Youtube Field Setup Video


How to show data of user that flagged a content(5 flag types or more)? This is a followup question about this Old question
I have 5 flag types for a content type. consider we have 5 flag types and we don't know how many flags our user used. I mean, the first user can flag a content by flag type 1, type 2 and type 5, and other user can flag same content by flag type 2 and type 4, and etc, OK?
I want to show a list of users that flagged same content, some users can use all flag types and others can use some flag types. thus I don't know users will use what flag types. You consider moreover "username", I want to show user's "E-mail". thus in this table I want to show "username", user's "E-mail" and "flag fields".
In below picture, I showed that a content can has different value. because any user can input different value in flag field. this table will appear in content page. I mean any content page has its specific table.

UPDATE
Now I have a new Idea that I would explain.
I can use Global custom text field. Consider I have 5 flag types, I added my 5 flag types username fields and hide them in views(exclude from display). As you know, First I should add flag types in Relationship part of views. when I add a username field, I should choose relationship in username field. Thus I should add 5 username fields.
After that I can use REPLACEMENT PATTERNS in "global custom text". Now I have 5 patterns for my 5 username fields. Now I have a problem.
Consider when one user use 3 flag types(3 of 5 flag types that I enabled for specific content), I mean when he(she) flag(s) a specific content by 3 flag types, in custom text field we can see username that repeated 3 times, because we use all 5 PATTERNS of username fields in global custom text field.
How can I solve this problem?
Is there any HTML code to show one of these patterns?
Also I can use global PHP. Is there any PHP code for this problem?
alternatives welcome also

As per the "alternatives welcome also" in your question, I would format/present the data in your table in a different format/layout. which will make the data shown in it way more easy to digest/understand.

Have a look at this alternative, which shows the same data (to which I added a few more similar sample rows to illustrate what I mean):

---------------------------------------------------------------------
| User   | Email       | Flag A | Flag B | Flag C | Flag D | Flag E |
---------------------------------------------------------------------
| John   | John@a.com  | 4333   |        |        |        |        |
---------------------------------------------------------------------
| Jack   | Jack@b.com  | 9000   |        |        | 1390   | 7677   |
---------------------------------------------------------------------
| Hamed  | Hamed@c.com | 0123   | 0456   | 0789   |        |        |
---------------------------------------------------------------------
| Niall  | Niall@d.com |        | 3377   |        | 5566   |        |
---------------------------------------------------------------------

If you agree, note however that creating such table is not obvious if you're trying to do so with the Views module. However, using the Forena module (disclosure: I'm a co-maintainer), creating such table is straight forward: it's what is called a Crosstab table. This is a table with a special layout. It is formatted as a grid, with:

the rows representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), names of Models, etc.
the columns representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
the intersections of rows and columns containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) include a hyperlink to a drill-down report.

For more info on this, have a look at the "Northwind database" demo videos, i.e:

How to create a report/graph about Shipping summary (fast forward to about 4:15 if you're not interested in the SQL query prototyping part of it).
How to create Crosstab Tables and (related) charts (fast forward to about 2:15 if you're not interested in the SQL query prototyping part of it).

To create such table for each "content page" (as in your question), you can use an appropriate Report parameter, which is like the equivalent of a Contextual filter. In your case, the node's id (= nid) would probably be a good candidate for such parameter. Have a look at this example report, and note the query string (= state=OH) in its URL. Just change that string to, eg,state=IL (or select some other value for state in the Parameters form) to get the basic idea about such parameter. Refer to the tutorial about Forena report parameters for more details about this topic.

This technique can also be applied to any of your entities you want to create reports about (nodes, users, whatever). For example, after you enabled Forena in your own site, you'll have access to one of its sample reports (= Active users), located at /reports/drupaladmin.active_users. If you then follow the link "logs" in that report for any of the users in the report (say with user name = SomeUserName), you'll get the (log) details about that user, via an URL similar to /reports/drupaladmin.user_logs?name=SomeUserName. So in this case the user name is used as such report parameter also.


Is it possible to replace the original RSS content? Is it possible to replace the original RSS generated for the front page by custom content?

I know how to create custom RSS channels using views, but not how to replace the original RSS.

When editing the Feed display of your view you have the Feed settings box with two settings there - Path and Attach to. If you set Path to 'rss.xml' or if you're using a view for your frontpage and you choose it in "Attach to", that should do the trick.


Possible to use EntityStorageBase::loadByProperties() to specify that field is or is not empty? Is there a way to use EntityStorageBase::loadByProperties() to specify that a field is either empty or not empty? I just want to check whether or not a field_date_completedhas a value set one it.

Looking to do something like $this->myEntityStorage->loadByProperties(['field_date_completed'=> notEmpty]) or $this->myEntityStorage->loadByProperties(['field_date_completed'=> isEmpty])

EDIT:
Sorted out a solution using the accepted answer. Per How get empty record on date field with entityQuery?, we can do something like

$query = $this->myEntityStorage
  ->getQuery()
  ->notExists('field_data_completed');

$entity_ids = $query->execute();

Only in a narrow scope where "empty" for the field means the empty string ('') and it's stored as such in the DB.

EntityStorageBase::loadByProperties() uses a helper method, ::buildPropertyQuery(), that chains comparisons using the IN operator. As such, you can't use negation or special comparison cases (e.g. IS NULL if "empty" means NULL in the DB).

Unless you have simple string comparisons for your field, you're better off skipping ::loadByProperties() and using EntityStorageBase::getQuery() to retrieve a query object that you can customize to fit a "empty" / "not empty" query.


Create a View Linking to Content I'm new to Drupal in general and am having some trouble with creating a view to display and link the information I want.

I have a content type called Project. This content type has a boolean called "Project Status" where "true" is labelled as "In Progress" and "false" is "Completed".

I want to create a block view to use as a sidebar on my page that lists all projects where the project status is true, and links to those projects by their title. I can make the view display the list of the projects that are in progress, but I can't figure out how to make it link back to those projects.

How do I do this?

The title field will have an option on its settings to "Link this field to its content". Check off that box and save the view, and the titles should be linked to their node detail page.


How to change the default mail template for subscriptions module It's probably a silly question but I just can't find the answer: Where can I change the default email template for the Subscriptions email? I'm using Drupal 7 and installed the module Subscriptions.

I would expect to change the mail templates at http://[mydomain]/admin/config/system/mail-edit. However at this location I only can add language translations for 4 languages which I've enabled but not the default email templates.

Can anybody point me to the right direction?

There is no template but you can solve this by adding the mail_edit module to your site. Here's the notes from the documentation:

http://drupal.org/node/344030#Configuration

(scroll down to "Mail Templates")

  If you have installed and enabled the mail_edit module then you can go
  to admin/build/mail_edit to edit the mail templates.


Printing taxonomy terms as an un-ordered list How to print taxonomy terms as an un-ordered list in page.tpl.php. Where i want to print a taxonomy term called "Article Category" and all its vocabularies one by one as a un-ordered list, so it can be used as a menu. Can't understand, please give me ideas?

EDIT: I know about a module "Taxonomy Menu" but looking for a programmatic direction, idea or any kind of reference that will help me to get started.

Thanks

OK, there is a module for that! Taxonomy Menu. Once installed, you can quite simply turn your vocabulary into a menu by going to admin > structure > taxonomy > {your vocabulary} > edit

You can also play around with it and get multi-level menus, which I think is what you are after/asking for.

Hope this helps!


Beginner - How to make CSS changes? I have very little Drupal experience and recently inherited a Drupal 6 site. I want to make some CSS changes, but from what I can tell all the CSS is in /home/saybrook/drupal/sites/default/files/css, where there are a bunch of CSS files that seemed to be cached. If I make changes to those files, they'll probably be lost eventually.

Can someone point me in the right direction?

Find out what theme you're using (visit /admin/build/themes)
Find the files in your Drupal installation for that theme (if it's a core theme it'll be under /themes, if contrib it'll likely be in /sites/all/themes)
Change what you need to.

If it's a core theme, don't edit it (you'll lose the changes when you next update Drupal core) - create a subtheme instead.

The files in /sites/default/files/css are the optimised files produced when CSS aggregation is turned on; for development you'll want to disable that (/admin/settings/performance), or you'll need to clear the css cache every time you make a change.


Slash at the end of the breadcrumbs How can I remove the slash at the end of my breadcrumbs?

Markup:

  Главная
    /
  Управление
    /
  Конструкция сайта

Screenshot:

I guess the slash is not in the end. It is the way you styled your breadcrumb thats why you are seeing it in the end. You can aid it using CSS, just tweak it a bit so you can hide it.


D7: HTML email sent shows markup, how to fix? Im using Linode VPS but mails are routed via SMTP authentication to Google. Email is sending correctly and I'm using mail system and html mail with smtp authentication.

When I send test email as html to test mailbox, it shows markup and wont render to html. How can I fix this?

HTML Mail > Send Test

Creating HTML mail and sending it with SmtpMailSystem sending class. Output when viewed at gmail receiving it:

This is a test letter.

Lets add some html

So all markup is visible. What I'm missing?

Fixed.

Edited php.ini:
/etc/php5/apache2 # nano php.ini

-->

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = /usr/sbin/sendmail -i -t

Set mailsystem to htmlmail, voila.


Can you allow user to add another item without editing the administrator post? I have a field which allows multiple inputs. What I want to achieve is to allow user to add another item only and not edit the content of the post of the admin. Thank you.

My suggestion is to use hook_form_alter for your node edit page and set '#disabled' => TRUE for your content field (assuming here as body field) by checking the current user role or something.


How to override theme for quicktabs which actually renders a view In D8, I want to display a view through quicktabs. For this, at first I have created a view file and call the view through QT. The view is displays well through QT. Now, I want to change the look & feel of the view. Please look into the screen of view which I've created before.

Now, based on the below theme suggestions I created the file block--quicktabs-block--gallery-tab.html.twig to override and place it under the "templates" folder in my theme.

When I write something fixed like "Hello Test" in the block--quicktabs-block--gallery-tab.html.twig, its showing well. However, when I tried to do something dynamic coding like below, nothing appeared.

{% if title %}

{{ title }}

{% endif %}
{% for key, row in rows %}
  {% if key in rows_with_tabs %}
    {{ tabs }}

  {% endif %}
  {% if key in rows_with_page_starts %}
    {% for page_key, page in rows_with_page_starts %}
      {% if key == page %}

 0 ? ' quicktabs-hide' : '' }}" id="quicktabs-tabpage-{{ quicktab_id }}-{{ page_key }}">
        {% set page_number = page_key %}
      {% endif %}
    {% endfor %}
  {% endif %}
  {{ row.content }}
  {% if key in rows_with_page_endings %}
    {# close .quicktabs-tabpage #}

  {% endif %}
  {% if key == last_index %}
    {# close .quicktabs-main #}

  {% endif %}
{% endfor %}

Am I overriding the correct file? Any suggestion?

PS:
after implementing the template file as said above, the suggestions looks like:

As Sunil says you are probably using view variables in your block template

Perhaps look for another template to override further down in order to find a views template to override and use your html/twig code

Here is what I would do.

Find the first template inside views-view.html.twig in my case it is views-view-unformatted.html.twig (red arrow above) and copy it in your theme templates folder.  Clear cache and make sure it is used and than explore the possibility of renaming it to be specific and used only for the quicktabs block.

See here for more info on how to name your templates


Print query result on form page I'm writing a custom module to obtain an online quote.

The form has an additional button and once it is clicked, a database query runs and print a value.

//My code for custom button
function garden_form_alter( &$form, &$form_state,$form_id ){
if ($form_id == 'webform_client_form_4208') {
$form['actions']['garden_quote']  = array(
    '#type' => 'submit',
    '#value' => t('Get online estimate'),
    '#submit' => array('mymodule_custom_submit'),
);
$form['#validate'][] = 'mymodule_custom_validate';
}
}

//Custom submit handler
function mymodule_custom_submit($form, &$form_state) {
$query = db_select('gardenvalue', 'f');
$query->fields('f', array('total_cost'))
    ->condition('meters', '2', '=');
$result = $query->execute();
dpm($result);
}

Once the form has been submitted dpm shows the 'meters' value as'db_condition_placeholder_0' and not number 2. What can be the reason?

Also I would like to show the $result value on a new text field once the form reloads. If we assume this new text field key is 'total_garden' how can I change its' value to $result on form reload?

Thanks in advance!

//My code for custom button
function garden_form_alter(&$form, &$form_state, $form_id ){
    if ($form_id == 'webform_client_form_4208') {
        $form['actions']['garden_quote']  = array(
            '#type' => 'submit',
            '#value' => t('Get online estimate'),
            '#submit' => array('garden_custom_submit'),
        );
        $form['#validate'][] = 'garden_custom_validate';
    }
}

//Custom submit handler
function garden_custom_submit($form, &$form_state) {
    $query = db_select('gardenvalue', 'f');
    $query->fields('f', array('total_cost'))
        ->condition('f.meters', 2, '=');
    $result = $query->execute();
    dpm($result);
}

You have spacing errors and identation errors, the condition is not pointing to a field in the table, and you have to dig into the results array to extract the value, as far as I know you only can print results in a form with

drupal_set_message(t('your message', 'success'); instead of dpm hope this help you a little bit...


How can I securely expose data through Drupal (via REST or something else) I'm looking to use Drupal to pull in data through forms etc, probably in the form of content types, and then expose these, probably via REST, to other things. I've had a look at the services module, but I'm concerned about securing this, and am going to be using certificates to do so. Is there anything out there that currently supports this sort of thing, or am I getting into custom made module territory here?

Services has a pluggable architecture for authentication, so if there's nothing that supports certificate authentication, all you need to write yourself is such a plugin.

That is basically responsible for mapping that certificate to a Drupal user and then everything after that will check that this user has permissions to access whatever entity/content it requested.

Drupal Module as web service with SSL looks like a related question but doesn't have any answers.


Why cant I configure or remove this module? I was trying to figure out Google Analytics and installing it broke my site so I uninstalled it.  Now I have reinstalled it, There is no link to configure it and the configuration page isn't even accessible from the URL.

So I tried to uninstall the module again and when I try to uninstall it goes to white screen and when I refresh I get back to the modules list and the module is still there.  I cannot configure or uninstall or get the module to work. It seems to be stuck there.

I have even tried to WinSCP into the server and straight up delete the module.  This removes the file from the list but when I reinstall the module I am back to square 1 where I cannot do anything with it.

I checked the error log and when I try to uninstall I get the following error PHP Fatal error: "Call to undefined function google_analytics_clear_js_cache()"

Is there anything I can do?

I checked the error log and when I try to uninstall I get the following error PHP Fatal error: Call to undefined function google_analytics_clear_js_cache()

This means that there is a bug in this module (and off-topic here).

But this is a general problem, and this anser provides is a general solution to this problem, that can also be used with other modules.

Whenever you get a WSOD upon uninstall and the log tell you it is because a "Call to an undefined function" - locate that call in the module's source code, and just delete the statement with the call.  Then try to uninstall again.

After doing this, make sure you report the problem to the module's issue queue on Drupal.org to make the maintainer fix it (and alert others about it).


Views Related Items Block when Taxonomy term is not on URL I have a "Views Related Items Block" problem which I thought was simple but have stopped me dead in my tracks for the last 2 weeks. I have Googled lots and lots of "Drupal Views Related" to no avail and hope someone will be kind enough to help me out.

Here is a sample content node:

TITLE: ABC123 (simple text string)

SHAPE: Square (stored as a taxonomy vocabulary called "Shape" with possible terms of "Square / Circle / Triangle")

COLOR: Red (stored as a taxonomy vocabulary called "Color" with possible terms of "Red / Green / Blue")

I have successfully created a VIEW PAGE configured to display the details of a product item at the URL:

http://www.mysite.com/products/square/abc123

where "square" (as a taxonomy filter) is the shape of the node item and "abc123" is the title of the node.

I would like to create a related items block on this page that will display all items that have the same SHAPE AND COLOR as item "ABC123" (square and red in this case).

I've played with MANY different configurations of "Content: Has taxonomy term ID / Load default filter from node page, that's good for related taxonomy blocks". But it seems like I can only successfully filter for "shape" and not "color". I just don't seem to be able to extract "color" given the above URL path.

I am open to using PHP code filter or even pre_execute() SQL modification, but I have zero experience in doing that in Drupal.

Any help will be most appreciated!

Thanks.

Andrew

Okay, I spent another day working on this and finally kind of got it working.

The goal here is to create contextual taxonomy filters that will retrieve all products with the same shape AND color as item "ABC123" as displayed on the browser URL, where item ABC123 happens to have a shape of "square" and color of "red".

Getting "square" into the taxonomy filter is easy,

create a view block
add a contextual filter of type "Content: Has taxonomy term ID"
since this is a block with no path, we need to give it a default value, do that and select "Taxonomy ID from URL" and "Load default filter from node page, that's good for related taxonomy blocks"
select the vocabulary you want (in this case "shape")

Now comes the hard part, we need to filter for "color" of item ABC123, but it is not on the browser URL in any shape or form. We need to somehow get the node contents of item ABC123, look into its "color" field, and then scan for all products with that color.

create a 2nd contextual filter of type "Content: Has taxonomy term ID"
click "Provide default value" and select PHP code

$title = arg(2, drupal_get_path_alias()); // arg #2 is title of item on URL
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'product'); // product is the machine name of my content type
->propertyCondition('status', 1)
->propertyCondition('title', $title);
// title is a node property, for other fields use ->fieldCondition

$result = $query->execute();

if (isset($result['node'])) {
$items_nids = array_keys($result['node']);
$items = entity_load('node', $items_nids);
}

reset($items);
$first_item = key($items);

$item = node_load($first_item);

$color = field_get_items('node', $item, 'field_color');
return ($color[0]['tid']);

For "Views Related Items Block", we also need to filter out ABC123, but that is an exercise left for another day.

Please note that this is the very first time I dabble into Drupal API calls, and the code above is clobbered together from various places on line. The code above make some assumptions (e.g. title is unique), is not efficient, may or may not handle translations and may not be totally secure. Reference at your own risk!


Remove "required" status from the Date field I have a field that is currently marked as required.  However, I want this to be required for all roles but the Admin.  I've made a module that implements hook_form_alter(), and I have been able to remove the required status for all fields but the Date fields.  Any idea what settings I need to change?

Also, I've tried altering it in hook_form_alter(), as well as doing it in the '#after_build'. I had no luck there either.

This is most probably because you don't just use a simple datefield, but one provided by e.g. the Date Module.

You should make sure that the module implementing your custom hook_form_alter runs last. That way, no other module can change it back to "required" again.

Furthermore, some modules implement a different "required" allthogether. E.g. the business-logic "if start-date is set then end-date is required too" cannot be implemented with simple "required" flags but will fire on the hook_validations for that form.

To override that, you will need to either exclude certain validations from running, by removing them from the element_validate or from the entire forms #validate.

You might want to replace these original validations with your own copies, to be sure you don't change ugly behaviour.


Embed a single webforms different fields in to two different pages - Drupal 6 In Drupal 6 , I have a webform which asks for basic info like the Name and email. Then on the basis of if the user is a special user (asked with option button) will choose to ask more questions if they are one else will not ask anything else.

I have created 2 webforms to do that. Is there a way to do that with only 1 webform?
More so is it possible to embed the remaining fields in to a different page.

Thanks.

Have not received an answer So based on my research I believe the Webform paging can solve this problem since it can display the webform in two parts.


More than one modules implementing the hook_module_implements_alter How can I know what module will implement earlier?

I have a module (custom) which implements hook_module_implements_alter and an other module (contrib) which is also implements it. In this case the contrib module is being executed later, overriding my implementation.

So, how can I ensure that my module will be executed later?

You need to change the weight of the modules in system table to modify their execution order.

One module that can help you in that is the Modules Weight, which provides an admin interface and avoids changing the SQL record directly.


How to use Views PHP to code if a view exists and has content then echo... I have a view displaying a list a menu of all the content for a node. It contains a list of all the fields and views on the page, with the output rewritten as a link eg link to field A .
I can do this fine for each field but I also have a view 'teachers' exposed as a block. If the view has content I want to have a link to it in the menu.
I'm trying to use Views PHP to code if the view has content, echo ''
What function do I call to see if the view exists and has content?
I've tried if(views_get_view('teachers) == TRUE){ echo "";} but this always returns TRUE even if there is no content for that view for a specific node.

I want to do something similar to

You can look at views_get_view_result() and do something like this:

$result=views_get_view_result('teachers');
if (isset($result[0])) {
  // we have results
} else {
  // we don't
}


Getting wrong output after implemented `theme_item_list` I have Drupal version 7.41 and I am using xubuntu 14.04 as my OS.

I have a module that displays footer links as a list. The module will fetch available links from the database and show them in individual blocks. Here is my fetch function:

function footer_links_footerblock_contents($variables) {
switch ($variables) {
    case 'group_1':
        $query = db_select('footer_links', 'fl')
                ->fields('fl', array('name'))
                ->condition('fl.group', 1);
        break;
    case 'group_2':
        $query = db_select('footer_links', 'fl')
                ->fields('fl', array('name'))
                ->condition('fl.group', 2);
        break;
    case 'group_3':
        $query = db_select('footer_links', 'fl')
                ->fields('fl', array('name'))
                ->condition('fl.group', 3);
        break;
    case 'group_4':
        $query = db_select('footer_links', 'fl')
                ->fields('fl', array('name'))
                ->condition('fl.group', 4);
        break;
    case 'group_5':
        $query = db_select('footer_links', 'fl')
                ->fields('fl', array('name'))
                ->condition('fl.group', 5);
        break;
}

return $query->execute();
}

The result array produced from the $query->execute(); will be going to my module's block_view function:

function footer_links_block_view($delta = '') {
switch ($delta) {
    case 'group_1':
        $block['subject'] = t('Footer Group 1');
        if (user_access('access content')) {
            $result = footer_links_footerblock_contents($delta);
            $items = array();
            foreach($result as $node) {
                $items[] = $node->name;
            }
            if (!empty($items)) {
                $block['content'] = theme('item_list', $items);
            }
            else {
                $block['content'] = t('');
            }
        }
        break;
    case 'group_2':
        $block['subject'] = t('Footer Group 2');
        if (user_access('access content')) {
            $result = footer_links_footerblock_contents($delta);
            $items = array();
            foreach($result as $node) {
                $items[] = $node->name;
            }
            if (!empty($items)) {
                $block['content'] = theme('item_list', $items);
            }
            else {
                $block['content'] = t('');
            }
        }
        break;
    }
    return $block;
}

In there I used the theme function theme('item_list', $var) to display them as a list. I have overridden the theme function like this in my template.php file:

function mytheme_item_list($variables) {
$output = '
';
$output .= '
';

foreach ($variables as $member) {
    $output .= '
' . $member . '
';
}

$output .= '

'; return $output;
}

And here is my problem. When I looked at the output in the footer section, I see list items that are not even in my database in which I fetch. I see 'Array', 'ul', 'item_list' extra added list items. What is the source of this extra output? Am I not properly overriding the theme function?

Your code is wrong, since the items to render are in $variables['items'] not $variables as evident in theme_list_items().

function theme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];

  // Omissis
}

You are confusing what the theme function gets in Drupal 7 with what the same theme function gets in Drupal 6.

In general, in Drupal 7 what the theme functions need to render is always an index of the array $variables passed them; they never use $variables directly like your code does.

function theme_table($variables) {
  $header = $variables['header'];
  $rows = $variables['rows'];
  $attributes = $variables['attributes'];
  $caption = $variables['caption'];
  $colgroups = $variables['colgroups'];
  $sticky = $variables['sticky'];
  $empty = $variables['empty'];

  // Add sticky headers, if applicable.
  if (count($header) && $sticky) {
    drupal_add_js('misc/tableheader.js');
    // Add 'sticky-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
    $attributes['class'][] = 'sticky-enabled';
  }

  $output = '<table' . drupal_attributes($attributes) . ">\n";

  if (isset($caption)) {
    $output .= '<caption>' . $caption . "</caption>\n";
  }

  // Omissis
}


Is it possible to show a view's page in the admin overlay? I created a view with a page display, which has an path alias, say: node/*/something/somethingelse
Now I would like that, if someone clicks on a link leading to the above path, the view's page is shown in the admin overlay. I tried following:

function custom_api_admin_paths_alter(&$paths) {
  $path['node/*/something/somethingelse'] = TRUE;
}

But it does not work. What did I wrong?

It may be a bit late and unfortunately I can not assist with your php script but you can try the Overlay Paths module which can achieve something similar to what you are trying to do.

It kind of did what I needed and I say kind of because it does not work that well with Views.


Create token with translatable variable in pathauto I would like to be able to create my own tokens for pathauto. In D7 I was able to create with the variable module some variables to represent a portion of an url. These variables where available as tokens and I had a different per content types and where translatable.

For example I would like to be able to do that:

[content-type-monthly-theme-base-url]/[node:title]

I can do that:

featured/[node:title] but the word 'featured' is not translatable

Another solution would be able to translate patterns. ATM only the pattern title is translatable! Not usefull...

As a last resort I can add a field base_url in my content type Monthly theme and use it as a token. But this means each time someone would create a node of this content type he or she would have to make sure the base_url field is in the right translation. This should really be configurable else where.

There are issues open about making patterns translatable.

And patterns actually can be per-language, so you can have multiple patterns, one for each language.

You could also implement the token yourself but be aware that for example during bulk generation, pathauto might create aliases for different languages in the same request, so you can't rely on the current language.


How to create RSS feed for particular content type in drupal 8? I have to create the RSS feed for particular content type and found some module and try to generate some RSS feed but I won't. If you have any idea or if anyone did this Please share with me.

Can create the views as well for generate the rss feed with following steps:

Enable Serializer and RESTful Web Services module, available in Drupal 8 core.
Create views for retrieving the contents of required content type.
Select the option Provide a REST export, present in the REST export settings (present at the bottom of views).
Configure the views as per the requirement.

Example:


How do I exclude a single menu item from the home page? I have a menu that displays on every page, and the top link for that menu is the "Home" link.  The clients do not want this menu item to appear when a user is viewing the home page, but wish it to be there at all other times.  How can this be accomplished?  There's no way I see to set an excluded page for menu item links.

Here is one method, and I must confess it may not be the absolute best. This method works for a menu that is not inside a block.

In your page.tpl.php use the following snippet:

if (drupal_is_front_page()) {
  foreach ($primary_links as $key => $value) {
    if (in_array('Home', $value)) {
      unset($primary_links[$key]);
    }
  }
}

The snippet will hide the element that contains the value 'Home' in the 'title' attribute.

Place that snippet before this chunk of code (so that $primary_links is modified before it is printed out):

<?php if (isset($primary_links)) : ?>
   <?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
<?php endif; ?>


Prepopulate the field twice I'm using Entityreference Prepopulate module. Is there way to pre-populate the field more than once?

Example:

example.com/add/node/custom&field_venue=92,92,92,183

I want the field venue to prepopulate 3 times. I can only do this if I type in the referenced node on the field, but I want it to prepopulate from the URL.

D7; Just adjust your contentype, fields names, and token.

Your title