How to use two pages of a View with the same path depending on users's profile? I created a View on a custom Content Entity.
I'd like to have 2 pages:

the first with all the fields from my entity, no filters, accessible
by users with Edit rights on the entity,
the second one with some of
the fields, filtered by one criteria, accessible by users with View
rights on the entity.

And, of course, with the same path, e.g. [mysite]/myEntity.
How do I do that?
I use Drupal 8.3.4.

In Drupal 7 this was quite easy to implement just using Views. In D8 I couldn't manage to implement it only with Views.

You can create a panel page with two different variants. Place the relevant block in each variant and control the accessibility though the 'Page access'. (I used roles but you can even create your custom condition)


Geolocation Field - Map Marker in Views I'm trying to show a map with multiple markers with the help of Views and Geolocation field. It would be nice for example if I can show the image in the tooltip display of the marker. But when I add an image as a field to achieve this, the image automatically gets selected as the icon source field by default (See Views UI - FORMAT - Advanced settings). Is it possible change this behavior?

You need to create a display in your content type where you will put the field that you want to show in the tooltip.

Home » Administration » Structure » Content types » YOUR CONTENT TYPE » Manage display

Then in your view select in the format to show Content and in the View mode the display that you created before with your fields.


Why does core use print rather than echo? I've read somewhere, and I don't remember where, that echo is a more efficient way of outputting data then print.

Why does Drupal core use print so much? Is there any special reason behind that?

echo is only faster in academic environments. The difference is very marginal. A quick benchmark I just did: The time fetching one row from a table with more than 2000 nodes is 1 unit.

In order to get an improvement of 1 unit, I would need to replace about 3.700.000 (over 3 milion) print statements with echo. In other words, if you want performance improvements, this is hardly the place to start.

Seen that print can be used in a much wider range of cases then echo, the first has some advantages. It leaves you three options:

Always use print
Use echo where possible and fallback on print
Use echo always and refactor your code if echo cannot be used, to use it

Drupal has defaulted on the first.

To answer your actual question as to why this was chosen: It was not. It simply grew this way.


Multi-site bulk module activation For a Drupal multi-site installation, is there any method to activate a module for all sites on the system at once instead of logging into the admin for each site individually?

I got an answer for this in the Drupal Community on Google+: Use drush @sites en your_module -y.


paragraphs_update_8018 takes very long time to finish The paragraphs_update_8018 update takes very long to complete (we have over 1 mio. paragraphs), as of now it's already been over 1h40m and it's still running. EDIT: it finished after 1h47m

My question is: is it possible to run this update without maintenance mode? I don't want to take the site down for so long for this update.

Disclaimer: act on your own risk!

After looking into what this update exactly does, I decided to execute it without maintenance mode. It worked without any problems. It depends on your situation though. You have to make sure that nothing interferes with the tables in question (no editors editing paragraphs, no automatic content imports/updates etc.).

Note that drush updb automatically enables maintenance mode, you have to disable it explicitly.

Of course generally speaking it's not a good idea to disable the maintenance mode during drush updb and problems may occur.


Modify date popup structure I would like to modify the date popup structure, in the image below you can see how date module builds the element. Drupal's default label is hidden, and it generates other to display the title. I want to show that label, and hide the date module label. Where should i modify this? Using some hooks in a .module, create a custom template or just overwrite it with css? Thanks all for help!

PD: This change must concern to every page in my site.

Override theme_date_popup in your theme or custom module.
See the following tutorial how to do it.


hook_form_alter add field after submit button to exposed view I'm trying to add a field that would be displayed after the submit button in the rendered HTML in my hook_form_alter.
e.g.
$form['include_card'] = [
  '#type' => 'checkbox',
  '#title' => t('Include gift card'),
  '#weight' => 25,
];

Weight doesn't seem to have any bearing on it.  How would you set that up?

The submit button will likely be inside an Actions element, which has a default weight of 100.
You could add your field to the actions element:
$form['actions']['include_card'] = ...

At which point the weight of include_card will be relative to the buttons/etc that are inside the actions element (and 25 will probably work).
Another option would be to position your element directly after the actions:
$form['include_card'] = [
  '#type' => 'checkbox',
  '#title' => t('Include gift card'),
  '#weight' => $form['actions']['#weight'] + 1,
];


How can we apply group_concat using views? Is there any way we can apply group_concat clause using views and without applying any customization to views ?

After some R & D on the above issue. I found that Views Aggregator Plus has that feature which I require. However, there are some minor configuration to be made but this module is quite helpful the result which I was expecting.


Creating a caption for images in Drupal 7 Media module Is there a way to create a caption field on images? I have seen in the latest Media module you can add your own fields on images now but I can't seem to get them to output in the WYSIWYG module correctly or on the final page.

Modules
 - Media 7.x-2.10
 - WYSIWYG 7.x-2.4
 - IMCE 7.x-1.11

You would need to edit the output of the media tpl file. First inspect the media html output and find any unique identifying code and then do a search in the media modules folder to find this line of code in the tpl. That's how I would do it.


How do I throw values calculated back to buildForm()? I am trying to throw back values that are calculated in submitForm() to buildForm().

How do I add more state values into it?

    /**
     * @file
     * Contains \Drupal\resume\Form\ResumeForm.
     */
    namespace Drupal\resume\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;

    class ResumeForm extends FormBase {
      /**
       * {@inheritdoc}
       */
      public function getFormId() {
        return 'resume_form';
      }

      /**
       * {@inheritdoc}
       */
      public function buildForm(array $form, FormStateInterface $form_state) {
         $form['number1'] = array(
          '#type' => 'textfield',
          '#title' => t('number 1'),
          '#required' => TRUE,
        );

        $form['number2'] = array(
          '#type' => 'textfield',
          '#title' => t('number 2'),
          '#required' => TRUE,
        );

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
          '#type' => 'submit',
          '#value' => $this->t('Save'),
          '#button_type' => 'primary',
        );

  $header = array(
    'total',
  );
  $output = array();
  foreach ($form_state->getValues() as $key => $value) {
     $output['total'] = $total;
  }
  $form['mytable'] = array(
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $output,
    '#empty' => t('No Data'),
  );

        return $form;
      }

      /**
       * {@inheritdoc}
       */
      public function submitForm(array &$form, FormStateInterface $form_state) {

        foreach ($form_state->getValues() as $key => $value) {
          drupal_set_message($key . ': ' . $value);
        }

$total = $form_state->getValue('number1') * $form_state->getValue('number2');

    $form_state->setValue('total',array($total));

           }
        }

You can add the following code:

/**
 * {@inheritdoc}
 */
  public function buildForm(array $form, FormStateInterface $form_state) {
     ...
     if (!empty($form_state->get('total')) {
       $form['total'] = array(
         '#type' => 'markup',
         '#markup' => '
 Total is: ' . $form_state->get('total') . '
',
       );
     }
    //$header = array(
    //  'total',
    //);
    //$output = array();
    //foreach ($form_state->getValues() as $key => $value) {
    //   $output['total'] = $total;
    //}
    //$form['mytable'] = array(
    //  '#type' => 'table',
    //  '#header' => $header,
    //  '#rows' => $output,
    //  '#empty' => t('No Data'),
    //);
    return $form;
   }

Add the following code to your submit handler:

/**
 * {@inheritdoc}
 */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   ...
    $total = $form_state->getValue('number1') * $form_state->getValue('number2');
    $form_state->set('total', $total);
    $form_state->setRebuild(TRUE);
    return $form
 }


visually resize images when uploaded inline in ckeditor is there a way to resize images after uploaded in the inline ckeditor?

if i have a big picture 2000x2000 and upload it (not via IMCE) to the editor, the image is huge and it is displayed in full size.

i have to scroll to left and down and drag the resize button multiple time until i get the result i can work with.

i miss the settings dialogue from D7 where i can define an image size upon upload. i cannot find any extension and i read many discussions that the D8 ckeditor has a lot less functions than in D7.
i read about the reason is responsive design but when i resize the image via drag there is still height and width added. so whats the point on this?

There's a pretty simple solution, but it does feel a bit hack-y.

Add a CSS file to a module/theme with contents like

img { max-width: 200px; height: auto; }

Implement hook_ckeditor_css_alter() to get that CSS file loaded in the WYSIWYG iframe:

function hook_ckeditor_css_alter(array &$css, Editor $editor) {
  $css[] = drupal_get_path('module', 'mymodule') . '/css/mymodule-ckeditor.css';
}

Once that's up and running images in the WYSIWYG should be constrained in width to whatever you set in the CSS file. You might need to resort to !important, depending on what other styles are already active; it'll need some tweaking no doubt.


How can Display Suite be used with Book module links? After settings some node types to use Display Suite I have noticed those which are in Books don't show the book links at the bottom of the page.

Is there a work around for this?

you've to activate the full display to show the book navigation field on Display Suite display settings.

There is only a problem: the book navigation links are always rendered after the comment form. I know it was a known bug some months ago but I don't know if it has been fixed recently.


"Translate" tab does not appear for every content I have installed the Localization module in my drupal project. All was working fine until now but i just noticed the "Translate" tab isn't visible for all my contents...

What i'm doing is simply :

-I go to content management
-content
-edit

-> Translate tab isn't visible...

On the other hand, when i try to translate another content of another content type, translate appears...

did anyone else face this problem previously?
thanks in advance

The "Translate" tab is handled by the Translation module that comes with Drupal; the Internationalization module that handles the translation for nodes just overrides the page callback for that tab.

function i18n_node_menu_alter(&$items) {
  if (isset($items['node/%node/translate'])) {
    $items['node/%node/translate']['page callback'] = 'i18n_node_translation_overview';
    $items['node/%node/translate']['file'] = 'i18n_node.pages.inc';
    $items['node/%node/translate']['module'] = 'i18n_node';
  }
  // Take over node/add pages for string translation
  $items['node/add']['page callback'] =  'i18n_node_add_page';
  $items['node/add']['file'] = 'i18n_node.pages.inc';
  $items['node/add']['file path'] = drupal_get_path('module', 'i18n_node');
  // @TODO avoid iterating over every router path.
  foreach (node_type_get_types() as $type) {
    $path = 'node/add/' . str_replace('_', '-', $type->type);
    if (isset($items[$path])) {
      $items[$path]['title callback'] = 'i18n_node_type_name';
      $items[$path]['title arguments'] = array($type->type, $type->name);
    }
  }
}

In order to have that tab visible for a node, the multilingual support for the content type must be set to Enabled, with translation.

In Drupal 8, that is done in admin/structure/types/manage/<content type ID>, but the option is titled Enable translation.

In Drupal 7, that is done in admin/structure/types/manage/<content type ID>.

In Drupal 6, it is done in admin/content/node-type/<content type ID>.


How to automatically add http prefix to links in a form? I am trying to come up with a solution to fix the D8 Link module to allow URLs like example.com (the most common use case, imho). I was thinking it would be simple enough to modify the submit value during a custom validate function; but regardless of what I set the value to it still validates on the original value.
In a form alter I have done this:
$form['field_linktest']['widget'][0]['#element_validate'][] = '_fix_link_field_value';

and then in that validate function I set the url uri value:
function _fix_link_field_value(&$element, FormStateInterface $form_state, &$complete_form) {
  $url = $form_state->getValue('field_linktest');
  $url[0]['uri'] = 'http://example.com';
  $form_state->setValue('field_linktest', $url);
}

But I still get the error: Manually entered paths should start with one of the following characters: / ? #

Thanks to those who provided answers; I couldn't quite get those to work, but they got me to my answer. My final solution ended up being this:
function my_module_form_alter(&$form, $form_state, $form_id) {
  // add a global validator to fix stupid Link fields - add to all Link fields
  // only worry about entity forms
  if (isset($form['#entity_type'])) {
    $bundle = $form_state->getFormObject()->getEntity()->bundle();
    $entity_type = $form['#entity_type'];
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);
    foreach ($fields as $field) {
      if ($field->getType() == 'link') {
        $field_name = $field->getName();
        $form[$field_name]['widget'][0]['#element_validate'][] = '_fix_link_field_value';
        array_unshift($form[$field_name]['widget'][0]['uri']['#element_validate'][0], '_fix_link_field_value');
        $form[$field_name]["widget"][0]["uri"]["#description"] = t('This must be an external URL such as http://example.com, https://example.com, example.com, www.example.com.');
      }
    }
  }
}

and then the validator/fixer:
function _fix_link_field_value(&$element, FormStateInterface $form_state, &$complete_form) {
  $url = $form_state->getValue($element['#parents'][0]);
  $urlOriginal = $url[0]['uri'];
  if (!$urlOriginal) return;

  if (!stristr($url[0]['uri'], '//')) {
    $url[0]['uri'] = 'http://' . $url[0]['uri'];
  }
  if (filter_var($url[0]['uri'], FILTER_VALIDATE_URL) === FALSE) {
    $form_state->setErrorByName($element['#parents'][0], t('%url is not a valid URL format. This must be in a format like
      http://example.com, https://example.com, example.com, www.example.com.',
      ['%url' => $urlOriginal])
    );
  }
  else {
    $form_state->setValue($element['#parents'][0], $url);
  }
}

The array_unshift isn't right but doing an unset() didn't seem to cut it. I am sure all this is doing is preventing the original validator from running; which is good as the error message it generates is stupid. Not sure why 5 years into D8 they still don't have this fixed.
Also, this will need an extra loop if you are dealing with multi-valued fields.


commerce product display news I have a problem that I am not sure how to address. I am using commerce guys and Drupal 7. I have some products around 200. But each one will have updates or news of what it is going on with them. How could I accomplish this so each product will display its news. For instance

Product Name
Description
Origin

PRODUCT NEWS

Month 1
lorem Ipsum is simply dummy text of the printing and typesetting industry.

Month 2
lorem Ipsum is simply dummy text of the printing and typesetting industry.

Month 3
lorem Ipsum is simply dummy text of the printing and typesetting industry.

view all product news

The first part is easily done with view mode but I have no clue what it is the best way to integrate news to a product display. I have searching in commerce guys and display suite but still don't have an idea. Do you have any advice, experience or module or how could I accomplish this?

A similar way would be to use Entity Views Attachment (EVA) along with a Product News content and utilize the tagging on the product to obtain a related news view


What is the purpose and differences between drupal_goto(),drupal_redirect_form() and $form_state['redirect']? May you explain me the differences between drupal_goto(), drupal_redirect_form() and $form_state['redirect'] with examples?

How can I pass the form values with these functions, and how can I retrieve the values using $_GET and $_POST in Drupal 7? Which is the better one to use?

First off, drupal_redirect_form() is not a function that a third-party module should use; it's a function used by Drupal code, and it is only used from two Drupal functions. In your code you should use drupal_goto(), or $form_state['redirect'].

The difference between drupal_goto(), and $form_state['redirect'] is that a form submission handler should never use drupal_goto(), which should be used, for example, from a page callback for a page without forms. The main reason not to use drupal_goto() in a form submission handler is that calling it would stop the other form submission handlers to be invoked. drupal_goto() contains the following code:

  // Drupal 6.
  // Even though session_write_close() is registered as a shutdown function, we
  // need all session data written to the database before redirecting.
  session_write_close();

  header('Location: ' . $url, TRUE, $http_response_code);

  // The "Location" header sends a redirect status code to the HTTP daemon. In
  // some cases this can be wrong, so we make sure none of the code below the
  // drupal_goto() call gets executed upon redirection.
  exit();

  // Drupal 7.
  header('Location: ' . $url, TRUE, $http_response_code);

  // The "Location" header sends a redirect status code to the HTTP daemon. In
  // some cases this can be wrong, so we make sure none of the code below the
  // drupal_goto() call gets executed upon redirection.
  drupal_exit($url);

Both exit() and drupal_exit() cause Drupal to stop running, and the output be returned to the browser; this means that other form submission handlers are not executed. Even if the form submission handler is for a form you use in your own module, you cannot know for sure how many form submission handlers need to be executed, and if your form submission handler is effectively the last one to be executed; other modules can add any form submission handler to your form. Using drupal_goto(), you are also avoiding that other Drupal code is executed; this could have any collateral effect, in the case of forms.

As per passing values to the page where the user is redirected, you can use code similar to the following one.

$form_state['redirect'] = array(
  $redirect_path,
  array(
    'query' => array(
      'foo' => $form_state['values']['foo'],
    ),
  ),
);

This snippet would cause the user to be redirect to http://your.site.domain/$redirect_path?foo=$form_state['values']['foo']. That page will get the value of $form_state['values']['foo'] in $_GET['foo'].

Consider also that, in the case you need to pass to the page where you are redirecting the user all the values submitted by the user in the form, you probably need to rewrite the code you wrote. If the page to which you are redirecting the user needs those values to, e.g., save them in the database, then that code should be in the form submission handler, and not in the other page callback. If the page needs those values to output HTML, then the form submission handler could render the output, and save it in a session variable, which is then used from the new page handler to show its own output.
In any case, all the values submitted from users in the form should not be passed to another page handler through $_GET or $_POST. Passing some of the submitted values is fine, though.


how to set Default time zone and date format I have user registration page in that I could see Time Zone as in screen shot attached now problem is I want to make it as default time  zone for all users as well Need to use same date format throughout drupal7 i,e in content type views also, can anyone tell me how to achieve this?

You can set default timezone and whether user should be able to edit default timezone settings or not.

Go to Regional and language settings:

http://yousite.com/admin/config/regional/settings

And uncheck : Users may set their own time zone.

On same page other settings also available. See :

To add any new format you can add from here :

http://yousite.com/admin/config/regional/date-time


Open Webform in a modal, but deny access to the form url I have a Webform being opened in a modal from a menu link. I want to have the modal be the only way to access the form, meaning I don't want someone to type in '/form/(name)' to the URL and access it by page. Is there a way to support opening in a modal but denying page level access in Webform?

Not sure if its the best way but I had something similar to do to allow viewing an entity only on a specified route and if some other conditions were met.
I created an EventSubscriber which basically decides if the user is allowed to access the page or not.
<?php

namespace Drupal\MY_CUSTOM_MODULE\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Custom class RedirectSubscriber.
 */
class RedirectSubscriber implements EventSubscriberInterface {

  /**
   * Custom function to check if we should redirect.
   */
  public function checkForRedirection(GetResponseEvent $event) {

    $route = \Drupal::routeMatch()->getRouteName();

    // If route is group add form.
    if (isset($route) && $route == "entity.group.add_form") {
      if ("MY CONDITION IS NOT MET") {
        //REDIRECT OR DO SOMETHING ELSE
        $event->setResponse(new RedirectResponse('/random-page url'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => 'checkForRedirection',
    ];
  }

}

Also, if you decide to do this, don't forget to register your event subscriber in the services.yml file.
services:
  MY_CUSTOM_MODULE_redirect_event_subscriber:
    class: Drupal\MY_CUSTOM_MODULE\EventSubscriber\RedirectSubscriber
    tags:
      - {name: event_subscriber}


Enable a node's menu item when on that node? I have a node for which there is a menu item. I want this menu item to be disabled except when the user is viewing that node. Can I do this, and if so how?

I will write a method that you can use by simply editing your theme's template.php file (without having to write your own module), and overriding

theme_link(),
theme_links(),
theme_site_map_menu_link(),
theme_superfish_build() AND
theme_menu_link()

functions. YES, that's correct, unfortunately for the correct markup, you have to override all of the above mentioned functions in your own theme, to avoid rendering empty
 elements in the default main menu, in the Superfish menu or the Site map module's own menu. I will assume you haven't already overridden them.
I tested it, so this code should be working, but please ask if you have any kind of questions.

First, please open your theme's template.php in a text editor of your choice.
Paste the whole code below into the opened template.php.

/**
 * Should this link be hidden?
 *
 * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
 *
 * @param string $link_path The path that should be inspected.
 * @return boolean
 */
function YOURTHEMENAME_link_should_be_hidden($link_path) {

    // in this example, I let "contact" and "node/9" links only be visible
    // on their own path (so for example, I let "contact" path be visible
    // in the menu if the user opened "example.com/contact").
    $your_paths_to_show_in_menu_only_on_their_own_path = array('contact', 'node/9'); // SUBSTITUTE IT with yours - empty cache every time you change that
    $is_link_to_hide = in_array($link_path, $your_paths_to_show_in_menu_only_on_their_own_path);
    if ($is_link_to_hide) {
        $is_current_page_self = ($link_path == $_GET['q']);
        // these links will be visible only on their own paths -
        // BUT here you can define other paths too where they can be visible at!
        // So for example, you want "example.com/node/9" to be visible when visiting its own path
        // AND when visiting "example.com/node/3" OR "example.com/any_other_path".
        // But if you do NOT want any other pages for these links to be visible at, then
        // just leave it empty (like this: array()).
        $link_also_visible_at_paths = array('node/3', 'any_other_path'); // SUBSTITUTE IT with your paths! - empty cache every time you change that
        $element_can_be_visible = $is_current_page_self || (!empty($link_also_visible_at_paths) && in_array($_GET['q'], $link_also_visible_at_paths));

        if (!$element_can_be_visible) {
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * Overriding theme_menu_link()
 *
 * @see http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7
 */
function YOURTHEMENAME_menu_link(array $variables) {
    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($variables['element']['#href'])) {
        return '';
    }

    $element = $variables['element'];
    $sub_menu = '';

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

/**
 * Helper function that builds the nested lists of a Superfish menu.
 * @see theme_superfish_build()
 */
function YOURTHEMENAME_superfish_build($variables) {

    $output = array('content' => '');
    $id = $variables['id'];
    $menu = $variables['menu'];
    $depth = $variables['depth'];
    $trail = $variables['trail'];
    // Keep $sfsettings untouched as we need to pass it to the child menus.
    $settings = $sfsettings = $variables['sfsettings'];
    $megamenu = $settings['megamenu'];
    $total_children = $parent_children = $single_children = 0;
    $i = 1;

    // Reckon the total number of available menu items.
    foreach ($menu as $menu_item) {
        if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
            $total_children++;
        }
    }

    foreach ($menu as $menu_item) {

        $show_children = $megamenu_wrapper = $megamenu_column = $megamenu_content = FALSE;
        $item_class = $link_options = $link_class = array();
        $mlid = $menu_item['link']['mlid'];

        /**
         * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
         */
        if (YOURTHEMENAME_link_should_be_hidden($menu_item['link']['link_path'])) {
            continue;
        }

        if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
            $item_class[] = ($trail && in_array($mlid, $trail)) ? 'active-trail' : '';

            // Add helper classes to the menu items and hyperlinks.
            $settings['firstlast'] = ($settings['dfirstlast'] == 1 && $total_children == 1) ? 0 : $settings['firstlast'];
            $item_class[] = ($settings['firstlast'] == 1) ? (($i == 1) ? 'first' : (($i == $total_children) ? 'last' : 'middle')) : '';
            $settings['zebra'] = ($settings['dzebra'] == 1 && $total_children == 1) ? 0 : $settings['zebra'];
            $item_class[] = ($settings['zebra'] == 1) ? (($i % 2) ? 'odd' : 'even') : '';
            $item_class[] = ($settings['itemcount'] == 1) ? 'sf-item-' . $i : '';
            $item_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
            $link_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
            $item_class[] = ($settings['liclass']) ? $settings['liclass'] : '';
            if (strpos($settings['hlclass'], ' ')) {
                $l = explode(' ', $settings['hlclass']);
                foreach ($l as $c) {
                    $link_class[] = $c;
                }
            }
            else {
                $link_class[] = $settings['hlclass'];
            }
            $i++;

            // Add hyperlinks description (title) to their text.
            $show_linkdescription = ($settings['linkdescription'] == 1 && !empty($menu_item['link']['localized_options']['attributes']['title'])) ? TRUE : FALSE;
            if ($show_linkdescription) {
                if (!empty($settings['hldmenus'])) {
                    $show_linkdescription = (is_array($settings['hldmenus'])) ? ((in_array($mlid, $settings['hldmenus'])) ? TRUE : FALSE) : (($mlid == $settings['hldmenus']) ? TRUE : FALSE);
                }
                if (!empty($settings['hldexclude'])) {
                    $show_linkdescription = (is_array($settings['hldexclude'])) ? ((in_array($mlid, $settings['hldexclude'])) ? FALSE : $show_linkdescription) : (($settings['hldexclude'] == $mlid) ? FALSE : $show_linkdescription);
                }
                if ($show_linkdescription) {
                    $menu_item['link']['title'] .= '';
                    $menu_item['link']['title'] .= (!empty($menu_item['link']['localized_options']['attributes']['title'])) ? $menu_item['link']['localized_options']['attributes']['title'] : array();
                    $menu_item['link']['title'] .= '';
                    $link_options['html'] = TRUE;
                }
            }

            // Add custom HTML codes around the menu items.
            if ($sfsettings['wrapul'] && strpos($sfsettings['wrapul'], ',') !== FALSE) {
                $wul = explode(',', $sfsettings['wrapul']);
                // In case you just wanted to add something after the element.
                if (drupal_substr($sfsettings['wrapul'], 0) == ',') {
                    array_unshift($wul, '');
                }
            }
            else {
                $wul = array();
            }

            // Add custom HTML codes around the hyperlinks.
            if ($settings['wraphl'] && strpos($settings['wraphl'], ',') !== FALSE) {
                $whl = explode(',', $settings['wraphl']);
                // The same as above
                if (drupal_substr($settings['wraphl'], 0) == ',') {
                    array_unshift($whl, '');
                }
            }
            else {
                $whl = array();
            }

            // Add custom HTML codes around the hyperlinks text.
            if ($settings['wraphlt'] && strpos($settings['wraphlt'], ',') !== FALSE) {
                $whlt = explode(',', $settings['wraphlt']);
                // The same as above
                if (drupal_substr($settings['wraphlt'], 0) == ',') {
                    array_unshift($whlt, '');
                }
                $menu_item['link']['title'] = $whlt[0] . check_plain($menu_item['link']['title']) . $whlt[1];
                $link_options['html'] = TRUE;
            }

            if (!empty($menu_item['link']['has_children']) && !empty($menu_item['below']) && $depth != 0) {
                // Megamenu is still beta, there is a good chance much of this will be changed.
                if (!empty($settings['megamenu_exclude'])) {
                    if (is_array($settings['megamenu_exclude'])) {
                        $megamenu = (in_array($mlid, $settings['megamenu_exclude'])) ? 0 : $megamenu;
                    }
                    else {
                        $megamenu = ($settings['megamenu_exclude'] == $mlid) ? 0 : $megamenu;
                    }
                    // Send the result to the sub-menu.
                    $sfsettings['megamenu'] = $megamenu;
                }
                if ($megamenu == 1) {
                    $megamenu_wrapper = ($menu_item['link']['depth'] == $settings['megamenu_depth']) ? TRUE : FALSE;
                    $megamenu_column = ($menu_item['link']['depth'] == $settings['megamenu_depth'] + 1) ? TRUE : FALSE;
                    $megamenu_content = ($menu_item['link']['depth'] >= $settings['megamenu_depth'] && $menu_item['link']['depth'] <= $settings['megamenu_levels']) ? TRUE : FALSE;
                }
                // Render the sub-menu.
                $var = array(
                  'id' => $id,
                  'menu' => $menu_item['below'],
                  'depth' => $depth, 'trail' => $trail,
                  'sfsettings' => $sfsettings
                );
                $children = theme('superfish_build', $var);
                // Check to see whether it should be displayed.
                $show_children = (($menu_item['link']['depth'] <= $depth || $depth == -1) && $children['content']) ? TRUE : FALSE;
                if ($show_children) {
                    // Add item counter classes.
                    if ($settings['itemcounter']) {
                        $item_class[] = 'sf-total-children-' . $children['total_children'];
                        $item_class[] = 'sf-parent-children-' . $children['parent_children'];
                        $item_class[] = 'sf-single-children-' . $children['single_children'];
                    }
                    // More helper classes.
                    $item_class[] = ($megamenu_column) ? 'sf-megamenu-column' : '';
                    $item_class[] = $link_class[] = 'menuparent';
                }
                $parent_children++;
            }
            else {
                $item_class[] = 'sf-no-children';
                $single_children++;
            }

            $item_class = implode(' ', array_filter($item_class));

            if (isset($menu_item['link']['localized_options']['attributes']['class'])) {
                $link_class_current = $menu_item['link']['localized_options']['attributes']['class'];
                $link_class = array_merge($link_class_current, array_filter($link_class));
            }
            $menu_item['link']['localized_options']['attributes']['class'] = $link_class;

            $link_options['attributes'] = $menu_item['link']['localized_options']['attributes'];

            // Render the menu item.
            $output['content'] .= '
' : '>';
            $output['content'] .= ($megamenu_column) ? '
' : '';
            $output['content'] .= isset($whl[0]) ? $whl[0] : '';
            $output['content'] .= l($menu_item['link']['title'], $menu_item['link']['link_path'], $link_options);
            $output['content'] .= isset($whl[1]) ? $whl[1] : '';
            $output['content'] .= ($megamenu_wrapper) ? '

' : '';
            $output['content'] .= ($show_children) ? (isset($wul[0]) ? $wul[0] : '') : '';
            $output['content'] .= ($show_children) ? (($megamenu_content) ? '
' : '
') : '';
            $output['content'] .= ($show_children) ? $children['content'] : '';
            $output['content'] .= ($show_children) ? (($megamenu_content) ? '
' : '
') : '';
            $output['content'] .= ($show_children) ? (isset($wul[1]) ? $wul[1] : '') : '';
            $output['content'] .= ($megamenu_wrapper) ? '

' : '';
            $output['content'] .= ($megamenu_column) ? '
' : '';
            $output['content'] .= '
';
        }
    }
    $output['total_children'] = $total_children;
    $output['parent_children'] = $parent_children;
    $output['single_children'] = $single_children;
    return $output;
}

/**
 * Overriding theme_site_map_menu_link()
 *
 * @param array $variables
 * @return string
 */
function YOURTHEMENAME_site_map_menu_link($variables) {

    $element = $variables['element'];
    $sub_menu = '';

    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($element['#href'])) {
        return '';
    }

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

/**
 * Returns HTML for a set of links.
 * @see theme_links()
 */
function YOURTHEMENAME_links($variables) {
    $links = $variables['links'];
    $attributes = $variables['attributes'];
    $heading = $variables['heading'];
    global $language_url;
    $output = '';

    if (count($links) > 0) {
        $output = '';

        // Treat the heading first if it is present to prepend it to the
        // list of links.
        if (!empty($heading)) {
            if (is_string($heading)) {
                // Prepare the array that will be used when the passed heading
                // is a string.
                $heading = array(
                  'text' => $heading,
                  // Set the default level of the heading.
                  'level' => 'h2',
                );
            }
            $output .= '<' . $heading['level'];
            if (!empty($heading['class'])) {
                $output .= drupal_attributes(array('class' => $heading['class']));
            }
            $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
        }

        $output .= '
';

        $num_links = count($links);
        $i = 1;

        foreach ($links as $key => $link) {

            /**
             * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
             */
            if (YOURTHEMENAME_link_should_be_hidden($link['href'])) {
                continue;
            }

            $class = array($key);

            // Add first, last and active classes to the list of links to help out themers.
            if ($i == 1) {
                $class[] = 'first';
            }
            if ($i == $num_links) {
                $class[] = 'last';
            }
            if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
                && (empty($link['language']) || $link['language']->language == $language_url->language)) {
                $class[] = 'active';
            }
            $output .= '
 $class)) . '>';

            if (isset($link['href'])) {
                // Pass in $link as $options, they share the same keys.
                $output .= l($link['title'], $link['href'], $link);
            }
            elseif (!empty($link['title'])) {
                // Some links are actually not links, but we wrap these in  for adding title and class attributes.
                if (empty($link['html'])) {
                    $link['title'] = check_plain($link['title']);
                }
                $span_attributes = '';
                if (isset($link['attributes'])) {
                    $span_attributes = drupal_attributes($link['attributes']);
                }
                $output .= '' . $link['title'] . '';
            }

            $i++;
            $output .= "
\n";
        }

        $output .= '
';
    }

    return $output;
}

/**
 * Theming links (theme_link())
 * @see http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_link/7
 *
 */
function YOURTHEMENAME_link($variables) {
    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($variables['path'])) {
        return '';
    }

    return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

Substitute YOURTHEMENAME with your own theme's name.
Substitute the values of $your_paths_to_show_in_menu_only_on_their_own_pathand $link_also_visible_at_paths variables in the previous step with your appropriate values. In the previous example, I hide the "contact" AND node/9 pages' menu link by default, and let them only be visible when we are viewing these pages themselves OR when displaying node/3 or any_other_path paths (so in any other cases, I don't see the link to "contact" or node/9).
Save the file.
Clear the cache!

So the final code should look similar to this: http://pastebin.com/PzQFhykn.

BUT in your exact case, you would like to hide node/425, so your code should look like this: http://pastebin.com/DKi5aSyq

Ask if something isn't quite clear.


Getting the base drupal dir in JavaScript I am writing a module that does ajax calls through the uses of javascript (not the Drupal ajax engine) to its Drupal installation, which in my case is {host}/drupal7.

My Ajax call should call "{host}/drupal7/notifications/get" from any page. Yet when I do my ajax call from javascript it calls "{host}/notifications/get" now this seems like an easy fix. Yet I can't think of a way to compose the right URL in a way that it will work in any installation.

Can anyone point me in the right direction?

You should use Drupal.settings.basePath in your Javascript.


Retain "Last edited by" info I would like to keep info on the user that last edited a node. From a little search I found that you can easily obtain that info from the node_revisions table. But what if you don't want to enable revisions? Is there any other way to get the uid of the user?

I thought of manually adding a field to my content type that will be set to the current's user username. So every time a user hits save that field will store his info. But then I would have to add field permissions to make sure the users don't see or edit this field.

I was hoping for a more out-of-the-box solution. Probably there isn't any otherwise google would have given me the answer. All ideas appreciated.
Thank you

You can do that by implementing hook_node_presave in your custom module, by something like:

function MODULE_node_presave($node) {
  $recent_copy = array_shift(array_values((node_revision_list($node))));
  drupal_set_message('User id of the user who edited latest is '.var_export($recent_copy->uid, TRUE));
  drupal_set_message('Username of the user who edited latest is '.var_export($recent_copy->name, TRUE));
}

You can find a detailed solution see: Get the edited node details without enabling node revision in Drupal.


How to center footer block? Using Drupal 7 with custom zen subtheme.  I created a footer block to hold standard copyright information.  But this block is left aligned, how do I center my footer block?

UPDATE

Below is the HTML for my footer.  What CSS selector should I use to identify my footer block?

 &copy; Copyright 2011 example.com

You could either:

Add {text-align: center} to your footer region or block.
You could specify a width for your block and add {margin: 0 auto}.


path_to_theme() goes to parent theme not subtheme I'm using zen as my parent theme and for some reason path_to_theme() is suddenly printing /sites/all/themes/zen instead of the subtheme /sites/all/themes/<mytheme>. What's even more confusing is that it's only happening when node/12 is being displayed.

Could this code have something to do with it?

<?php
//template.php
if(isset($vars['node'])){
    if($vars['node']->nid == 12) {
        $vars['is_request_quote'] = true;
    }
}
?>

I use the variable $is_request_quote to change the layout in page.tpl.php. I do this through <?php elseif( $is_request_quote ) : ?> -New layout here- <?php endif; ?>.  Could that be the one affecting it?

I had this problem too. Solution here, applied to node instead of page, worked for me: copy node.tpl.php to your custom theme templates directory. Once I did that, path_to_theme() behaved correctly.


Overriding node-view-VIEWNAME.tpl problems Hello i am trying to override a node view without much success. I dont know if its just the syntax for my view thats wrong.

When i go to theme information the Row Style output tpl suggestion is

views-view-row-node--taxonomy-term--page-3.tpl.php

i can override that fine but it suggests it would be better to overide node-view-VIEWNAME.tpl.php

So i have a tpl file named

node-view-taxonomy-term-page-3.tpl.php

but it doesnt seem to want to override. Am i missing maybe a '-' somewhere in the tpl title?

I am using Views 3 and D6. I have the tpl in the same folder as my node.tpl.php

all help appreciated thanks.

The best way to do this is to see what your available theme suggestions are for that node.

In your theme add the following snippet and clear cache, refresh page, etc.

function YOURTHEME_preprocess_node(&$vars) {
   var_dump($vars['template_files']);
   //dsm($vars['template_files']); // if devel module installed
}


Backreference in PHP I have a Content Type Courses  & a User Role Student

In the student I used EntityReference to refer to a number of courses.

Is it possible to get a list of all the students that have a particular course referenced to them, in PHP?

Right now I'm only accustomed in getting a value from a field in a content type like this:

$user_surname = $profile_info['student']->field_surname['und'][0]['value'];

PS I think this has to do with back-reference,which is a module I already installed.

You could do this with views (without PHP), but if you want to use PHP you should check out Entity Field Query

You will have to do something like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('your_field_course', 'target_id', $nid, '=')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.
$result = $query->execute();
if (isset($result['user'])) {
  $uids = array_keys($result['user']);
  $users = entity_load('user', $uids);
}


Change Ubercart's "Order" to "Donation" I am setting up a site for a non-profit organization (using Ubercart to accept donations) and I want to change "order" to "donation".

I started in with the stringoverrides module. I was searching around trying to find all the occurrences of "Order" and putting in a string over ride that changed it to "Donation". I found this to be extremely clunky, time consuming and error prone.

I looked at the source of the string overrides module figuring that I could find how it was actually performing the override and then hack together my own solution to programmatically do some sort of search and replace on it. After looking at that and the source for the t() function I realized it wasn't going to be that easy.

Is there a way to easily pull a list of all the t() calls that include the text "order" in them? I could then pretty easily generate a .po file by doing a bunch of search and replace type operations.
Is there a way to programmatically change all occurrences of 'order' to 'donation'?
Is there some other obvious way that I haven't thought of?

P.S. I am proficient with custom module development in Drupal but don't have much experience in l10n_update or i18n with Drupal.

Have you taken a look at this http://drupal.org/project/uc_donation... Ubercart can actually provide donation functionality. Let me know if this is what you were thinking.


How to display node title using computed field? I have a computed field (text) where I would like to display the node title.

I tried the following thing but nothing worked.

$value = $entity->title;
$entity->title;

I referred

1.
https://blogs.sulross.edu/lwetterauer/computed-fields/

2.
https://stackoverflow.com/questions/14087479/how-do-you-access-the-title-node-module-element-field-in-drupal-7

To get the value:

$value = $entity->title->value;


How can I get the form builder service using dependency injection? How can I change form builder call in class in to dependency injection method?

My current code:

class CustomBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomForm');
    return $form;
  }

}

And I tried:

class CustomBlock extends BlockBase {

  /**
   * formBuilder.   *
   */
  protected $formBuilder;

  /**
   * Class constructor.
   */
  public function __construct($formBuilder) {
    $this->formBuilder = $formBuilder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
        $container->get('form_builder')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = $this->formBuilder->getForm('Drupal\custom_module\Form\CustomForm');
    return $form;
  }

}

But getting following error:

  Fatal error: Call to a member function getForm() on a non-object in H:\wamp\www\myproject\modules\custom\custom_module\src\Plugin\Block\CustomBlock.php on line 44

AJAX form test mock module's AjaxFormBlock.php is quite a nice example for getting both in one, the form builder and the form interface! Look how it implements FormInterface, ContainerFactoryPluginInterface to then provide the form from within the block and injecting the form builder via dependency injection to then be used to get the form in the block's build() method at the same time.
Of course, when you only need the form builder, you don't need to implement the FormInterface! Then you just need the ContainerFactoryPluginInterface.

namespace Drupal\ajax_forms_test\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides an AJAX form block.
 *
 * @Block(
 *   id = "ajax_forms_test_block",
 *   admin_label = @Translation("AJAX test form"),
 *   category = @Translation("Forms")
 * )
 */
class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactoryPluginInterface {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new AjaxFormBlock.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formBuilder = $form_builder;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('form_builder'),
      $container->get('messenger')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return $this->formBuilder->getForm($this);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ajax_forms_test_block';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['test1'] = [
      '#type' => 'select',
      '#title' => $this->t('Test 1'),
      '#required' => TRUE,
      '#options' => [
        'option1' => $this->t('Option 1'),
        'option2' => $this->t('Option 2'),
      ],
      '#ajax' => [
        'callback' => '::updateOptions',
        'wrapper' => 'edit-test1-wrapper',
      ],
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  /**
   * Updates the options of a select list.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The updated form element.
   */
  public function updateOptions(array $form, FormStateInterface $form_state) {
    $form['test1']['#options']['option1'] = $this->t('Option 1!!!');
    $form['test1']['#options'] += [
      'option3' => $this->t('Option 3'),
      'option4' => $this->t('Option 4'),
    ];
    return $form['test1'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->messenger->addStatus('Submission successful.');
  }

}

Another nice example is core's SearchBlock.php.
Also worth checking out the docs on Dependency injection in Plugin (Block).


Only display image field when administrator approves it I'm building an advertising website using Drupal 7, in my case anyone can add an advertisement without any restriction, except that the images should be hidden first until the website admin approves it.

Have a look at File admin .

  File admin extends the File entity module to add administrative
  options to files, including published, promoted, and sticky status.

It has a dependency on File entity, which is a prerequisite when working with files as first class citizens.

Please also look at File admin's issue queue. A lot of extra functionality can be added via a few select patches.


Checkbox left hand navigation drill down Does anyone have an idea on how I can go about creating this navigation? I have a section of a website that has subwords of a top vocabulary word that I would like to show in a left hand menu in order to drill down to the content with checkboxes.

[]Topic 1 ---> if checked show excerpts of all articles with this topic in the content area.
[]Topic 2 ---> if checked show these articles...

[]etc...

The user could check 1 or all of the topics and get the articles.

Sort of like: https://wordpress.stackexchange.com/questions/18484/checkboxes-in-the-category-list

Thanks for any direction, help or the like!

Just to help others out here! This is called Faceted Search. After looking around and around online, I found it. There are a lot of posts about it. Drupal 7 uses Facet API to do this. However, it is still not extremely straight fwd...


render php code in view result What's the proper method to render a field within the views?

In node templates I render php code using

echo render($content['fancy_field']);

But when I want to render php code within a view I was using

echo render($view->result->_field_data['nid']['entity']->fancy_field);

But it didn't works, any ideas?

Best practice is to implement hook_field_formatter_info() and hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display). The examples module shows how to do this in greater detail in the field_example submodule.


Create taxonomy terms i'm new to drupal (just installed v9) and want to add a bunch of content.
like in the question asked years ago (Create taxonomy terms on the fly) i want to add taxonomy terms on the fly while adding new content and not having to add them first in the taxonomy module.
the links provided in the old thread are for v7 and v8 and seem not to work
if the code thats posted there is still a valid solution can one tell me where to add it?
thanks

As always there is more than one way of doing things in Drupal.
I'll guess that one of the popular ways of solving this problem currently is with the Inline Entity Form module.
Once you have it installed you can go to the "Manage form display" of your Content type and choose the Inline entity form Simple or Complex for your Taxonomy ER field (Complex allows you to also add existing entities, not only create new ones on the fly). Adjust the settings to your needs.


Generating URLs with fromUri and the language prefix, base vs internal What is the recommended way to generate non-route URLs that include the language prefix?

Context: In CiviCRM, an open source third-party project that integrates with Drupal, we have a function that generates internal URLs (a wrapper over the CMS-specific function).

Since not all URLs referenced have a proper route, so far fromUri has given the best results (rather than fromRoute).

However, the URLs generated by fromUri do not seem to include the language prefix for multi-lingual configurations when using base as the prefix. The language prefix is included with internal, but if I understand correctly, internal should only be used for user-specified links, such as a link field.

Example on a site that has English and French, with French being the default language:

print \Drupal\Core\Url::fromUri("base:/admin")->toString() . "\n";
print \Drupal\Core\Url::fromUri("internal:/admin")->toString() . "\n";

$ drush scr test.php
/civicrm/dashboard?reset=1
/fr/civicrm/dashboard?reset=1

I also tried passing in the $language object, but the behaviour is the same:

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

print \Drupal\Core\Url::fromUri("base:/admin", [
  'language' => $language,
])->toString() . "\n";

Related question: Generating arbitrary internal URLs

Drupa8 - as a Symfony application - abstracts paths with routes. So paths may change, the route stays.
So the cited "The internal: scheme should be avoided except when processing actual user input that may or may not correspond to a Drupal route." means: If you can, use a route.
If you can not use routes, the right prefix for routed paths is internal:.
In contrast, base: was introduced for use cases like README.txt which is unknown to the symfony router and served directly by the web server.

You can find background in these issues, and help improve the docs:

Remove the base: scheme in favour of user-path:/internal: [#2422995] which concluded that we still need the base scheme
Evaluate and document each use of base: in core [#2417827] which then was started to at least document usages of the base scheme
Url::fromUri DocBlock does not mention base: and internal: custom schemes [#2877023] which is about improving the docs


Views Slideshow gives duplicate row classes I use views_slideshow and I use it's option Items Per Slide and I set it to 2, so it shows two nodes at a time. Problem is now, I cannot give both nodes separate styling, i.e. I want first row to have padding to right and second row to have padding to left, I could do that if it didn't have identical row-number classes:

You could easily achieve what you need with a small workaround using css pseudo classes :first-child and :last-child, apply them to the surrounding div and easily get the paddings for first and last elements. See this and this.


Add tabs on node edit page How can i add a new tab in node tabs ( with edit, view tabs ) and show a page on this new tab ?
i am working on a shopping cart where i need to add a new configuration tabs with nodes and ubercart products.

You need to define a new URL by using hook_menu.

There, 'type' is set as MENU_LOCAL_TASK and URL is like 'node/%node/CUSTOM_CONFIG'.

Code snippet from the hook_menu in node.module:

 $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'node.pages.inc',
  );


What is the recommended method to add an RSS icon to an Open Scholar scholar site? I would like to add a linked RSS icon to the footer of a scholar site using Open Scholar. I know that the URL to an RSS feed will be:
example.com/professorname/feed

However, I'm unsure of how to programmatically get the URL to the scholar site ("example.com/professorname") so I can build the link and insert it into the page.tpl.php for a few scholar sub-themes. Is there a recommended method for this?

If you have a footer menu, you could add the RSS feed to it, and then attach a bit of CSS to your theme.  The exact selectors would depend on what is being output, but you could do something like:

ul#footer-menu li.menu-1234 {
  padding-left: 20px;
  background: url(/path/to/rss.png) left center no-repeat;
}

You may need to adjust other styles to get the whole icon to appear.

There are bunches of sites with royalty free RSS icons.


How do I expose display routes from a specific view as REST API? I have set up some displays in a Categories view, all with their own path. I want to expose all displays from that view with a REST API.
I've already set up a module with a path, but how do I get the paths to the individual displays?
$view = Views::getView('categories'); gives me the view (probably with my desired displays), but I am quite stuck there.
Most of the answers I find online are pretty much outdated.

I actually found a solution which is working for me myself.
$view = Views::getView('categories');

$displays = $view->storage->get('display');

$ret = array();

foreach( $displays as $display){
  array_push($ret, array(
    'title'   => $display['display_title'],
    'path'    => $display['display_options']['path']
  ));
}

return new JsonResponse( $ret );


pass array from module to render in template I have a module name mysite.module in that module I have function named mysite_preprocess_panels_pane. That has an array and I would like to render this array inn panel.tpl.php. My code does not work. Any suggestion please, Thanks.

function mysite_preprocess_panels_pane(&$variables) {
 $ar = array('arg1'=> 'car', 'arg2'=> 'truck');
}

 <?php print  $ar['arg1']>

Place the array into the variables. like.

function mysite_preprocess_panels_pane(&$variables) {
 $variables['ar'] = array('arg1'=> 'car', 'arg2'=> 'truck');
}


How to change background image based on current node? I am trying to change the header background image of my website based on the current node. I have added an image field to my content type, field_hero_image, and, in preprocess function mytheme_preprocess_page(&$variables), I get the image url and try to inject it in the page, as inline css:

function mytheme_preprocess_page(&$variables) {

    $node = $variables['node'];
    if ($node) {
           $path = file_create_url($node->field_hero_image->entity->getFileUri());
            $variables['page']['#attached']['css'] = array(
                'data' => '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
                'type' => 'inline',
            );
    }
}

or

function mytheme_preprocess_page(&$variables) {

    $node = $variables['node'];
    if ($node) {
           $path = file_create_url($node->field_hero_image->entity->getFileUri());
           $variables['#attached']['library'][] = array(
            'data' => '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
            'type' => 'inline',
        );
    }
}

None of this works.

Is there a way to inject css from the preprocess function? I know that I can get the path value, put it in $variables and use it in twig. But this doesn't seem a clean solution to me.

You can make a different templete and use, for example, a class and load the different img by css is one of many possible soluctions, I think that is the best practice

You can read more about Drupal 8 Temple in these threads:

https://www.drupal.org/docs/8/theming

https://www.drupal.org/docs/8/theming/twig

Example aplications

function YOURTHEMENAME_preprocess_node(&$variables) {
  if ($variables['node']) {
    $node = $variables['node'];
    switch ( $node->nid ) {
    case 'nid1':  // Replace nid1 etc with your nid
    case 'nid2':
      break;
    }
  }
}

Template/node/node--full--[nid]

    <div class="img--hero--image">
    </div>

Other solutions it is use a field in the content type and use this field to render in your background.


Does inactive modules can make my drupal site slower? I have some modules that Im not using and they are inactive, if I uninstall and delete those modules could I improve th performance of my site, my site is becoming very very slow, the ajax requests are slow everything is slow....

I don't understand Jance's response.  He says "it won't hurt", but then says these disabled modules are sucking up resources?

Saying inactive modules don't impact performance is not completely accurate... but it certainly is less important than the number of enabled modules.

While the hooks of an inactive module with code left in sites/all/modules aren't loaded when a specific form or page is loaded, all .info files from any code active or inactive are scanned when loading the admin/modules and admin/themes.  Drush also scans all directories for Drush related includes in profiles and sites... regardless of what's active.  Inactive modules aren't going to cause as much of a hit to CPU and memory as an enabled module, but having unused code in sites/all/modules isn't a good thing. Best practice would be to only install modules on a test site.  Never install a module on a live site just to test it.  Even when uninstalled, modules can leave a lot of cruft behind that can impact performance.

Modules that were once installed, but are now inactive could create tables and define variables add to the cruft at the database layer.  Even if you uninstall the module, the uninstall process relies on the developers who wrote the module to clean up after themselves.   Modules that use Features often leave even more cruft behind.  Disabling a Feature "module" does not remove the content types, taxonomies, fields, views, blocks, etc that it created.  Even uninstalling and deleting the code doesn't always clean up after a Feature.

I realize that not everyone can afford the type of dev -> test -> live workflow you get with a Drupal specific host like Acquia or Pantheon or has the technical skill to run a local version of their site, but if you don't have that type of testing environment be prudent about the modules you enable then uninstall.

Alas, hindsite is 20/20... for modules you've already enabled in the past that you've decided not to use, uninstall them and remove the code from sites/all any module.  This won't improve performance as much as reducing the number of modules enabled, but leaving this code certainly won't help performance or your ability to maintain the site.


Javascript added via drupal_add_js() does not get aggregated I have a couple custom modules that I add javascript via drupal_add_js(). I have all the Bandwidth Optimizations options checked in the performance page (/admin/config/development/performance).

Since I have Aggregate JavaScript files checked, should all my javascript files be aggregated into one file? Is this normal behavior?

The reason it wasn't aggregating is that someone had every_page set to FALSE and preprocess set to FALSE(as @thedotwrite was saying in comment above) in a lot of  drupal_add_js() calls.  (Some of them were set like this because they really shouldn't have been on every page but there were some that really could be on every page).

Not sure why I didn't notice that before :)


Search API Solr Autocomplete no results when more than x Nodes indexed I encounter a strange behavior on a site I'm working on.

I use Search API views exposed form for autocomplete.
My nodes reference nodes of another content type. The title of this referenced node's should be returned by autocomplete. This works all fine until more than 22 nodes are indexed. It seems like it does not matter which nodes are indexed, when 22 are exceeded the autocomplete will not return any results anymore.

I also tried to index the field as different types but the outcome is the same.

If i type in the term and click search the results are fine. I also ran the query in Solr's backend which returns the result as well.

Log's of Drupal and Solr show nothing.

Any suggestion on what and how to debug this?

RTFM - Today i finally found this: https://www.drupal.org/node/1999392#hidden-variables

  search_api_solr_autocomplete_max_occurrences
      By default, keywords that occur in more than 90% of results are ignored for
      autocomplete suggestions. This setting lets you modify that behaviour by
      providing your own ratio. Use 1 or greater to use all suggestions. Defaults to 0.9.

This makes perfect sense since 90% of my total 25 nodes is 22.5.
I just set in a custom module:

variable_set('search_api_solr_autocomplete_max_occurrences', 0);

And it works.


How to force image URLs as HTTPS? There are a few places where I am calling ImageStyle::load('style')->buildUrl($uri) to get a physical file path of an image.

After enabling HTTPS and forcing all traffic to use HTTPS, I noticed that this will only return http:// at the start of the url, and not https:// causing mixed mode flag in the browser.

Is there a way to do this and get the correct protocol? Can I not just obtain the relative path to the file instead? I notice that this method has hardcoded 'absolute' => TRUE when building the url to return.

Edit: fields using the normal rendering method i.e. {{ content.field_image }} have the correct protocol and do not cause an issue.

Here is the code I am using to generate the variable:

/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle =='homepage' && $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node->get('field_hero_image')->getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('homepage_hero')->buildUrl($entity->field_image->entity->getFileUri());
    }
  }
}

In the node view mode twig template:

  {% if node.field_hero_image is not empty %}

  {% endif %}

You can use file_url_transform_relative():

/**
 * Transforms an absolute URL of a local file to a relative URL.
 *
 * May be useful to prevent problems on multisite set-ups and prevent mixed
 * content errors when using HTTPS + HTTP.
 *
 * @param string $file_url
 *   A file URL of a local file as generated by file_create_url().
 *
 * @return string
 *   If the file URL indeed pointed to a local file and was indeed absolute,
 *   then the transformed, relative URL to the local file. Otherwise: the
 *   original value of $file_url.
 *
 * @see file_create_url()
 */
function file_url_transform_relative($file_url) {


Drupal use Node or not? And how to use them? I'm on the way to develop a website for a kind of a sport-league where we have every year one season with different teams.
A team can be built out of two Users and they can play against other teams. There will be a kind of different Leagues (depending on how good they are..)

So my question is now, how to implement this? :P (Of course this is nit the main question, but I need some hints for my drupal-start :)

In drupal there is this concept of "Nodes". As I understood, a Node is a Content. And depending on the NodeType it is shown different.

How should I now implement for example a "Game". To the beginning of a season the site will create all the game-records. During the Season the users will enter the results into this game-records. They can write comments and probably rate the game.

For the edit-page I'm going to write my own module (guess this is the right path to go..) same I'll do for the rankings.. this should work! But how can i combine this "Node"-Concept with my "Database"-Concept I've learned before I get known to drupal?

Is it then possible to hide a specific Node-Type from Administration -> Content? I do not want to see there all the Games played during the last 10 Years as this would be quite a big list...

Any help/idea/hint would be very appreciated :)

Nodes are for content, complex data managed by your website are not necessarily content. In Drupal 6 and before, using node for everything was a common practice because only nodes could benefit easily from the CCK, Views and other modules. Drupal 7 introduced the concept of entities. You can create new entity type and for one entity type your can have multiple bundles. Node is an entity type and the content types (or node types) are bundles. Using the Field API, fields are defined by bundle to attach values to entities.

So you don't need, and probably shouldn't, manage everything as nodes but instead defines your own entity types and bundles to store and manage your site data. The Entity API module provides a better API to manage entities and entity types to complete Drupal core's one. The Model Entities project provides a model entity and entity administration interface to kick-start your entity related development. For Field API usage, the Examples for Developers project provides the field_example. You can also use Features to easily export field definitions into code.


User Created Accordion With Fields? When a user is creating a node, is it possible to auto generate an accordion based on a field group or field collection? I want the user to enter the title(clickable to expand and show body) and body of their accordion(s).

I see field_group and bootstrap_field_group, but both require me to add the title for example and then give the body of the accordion based on another field... That is admin specific. I'd like to give the user the flexibility to create their own title for each accordion item.

The best way I have found to do this was to use Paragraphs. You can create an Accordion paragraph type, and an Accordion Item paragraph type. The Accordion holds Accordion Items. The Accordion Item has 2 fields, Title, and Body.

This allows a user to add an Accordion paragraph to a node, then add as many Accordion Items as they want (and be able to sort them in the form). From there, the theming/js is up to you via templates and js, but that part is fairly easy.

Since Paragraphs are based on fields, it's intuitive for the editor who use used to the node edit interface.


Get all fields defined in a bundle for a view mode Is it possible to get all the fields and field groups structures defined in a bundle for a view mode, in Drupal 8?

If I understood your question correctly, you need to use the entity_get_display() function.

It will return the entity view display, associated with the bundle and view mode you wanted. Simplest example:

$display = entity_get_display($entity_type, $bundle, $view_mode);


Commerce equivalent of Signup, Pay Per Node, etc I had previously asked for some information about specific e-commerce functions on D6, and was pointed to UberCart, along with Pay Per Node, Signup, and a few other modules. I've just learned that our hosting company has updated their php install so D7 is now supported.

Are there equivalents to those modules for D7? I know Commerce is the big one, but can it do pay-per-node type stuff (to support a print-on-demand fundraiser)?

Here are a few links that might get you started.  Drupal commerce is a lot more powerful than Ubercart, because everything is fieldable you should be able to make your event signup product include any fields you wish to collect.  I'm not sure what you mean by print-on-demand fundraiser but hopefully this gets you heading in the right direction.

http://vimeo.com/31459435

http://mustardseedmedia.com/podcast/episode51

~Mark


Slow AjaxResponse for node content I am using Drupal 8 so there is very little documentation or benchmarks, but I believe a route I have set up for ajax responses is not as performant as it could be.
This is the route:

next_node.ajax:
  path: '/node/{node}'
  defaults:
    _controller: '\Drupal\next_node\Controller\DefaultController::view'
  requirements:
    _permission: 'access content'
    _format: 'json'
    _access: 'TRUE'

And this is the controller:

class DefaultController extends EntityViewController {
  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    $build = parent::view($node);

    return new AjaxResponse(\Drupal::service('renderer')->renderPlain($build));
  }
}

I request the content through this function:

jQuery.get( "/node/2?_format=json", function( data ) { /* Do stuff */ });

Is it normal that it takes about a second on average to get a response? Where to optimize the code?

There are some different things which could be improved in your code, like using dependency injection, better naming etc, but none of these effect performance.

There are some different things which makes it quite trigger to give a good answer to this. Drupal 8 is still in beta and many performance optimizations are being made. The render cache and page cache should be usable in your case making subsequent requests cached and this a lot faster than the initial request. Being logged in / logged out make a big impact as Drupal has a hard time caching for logged in users, but this is nothing new.

That said, it still sounds a bit slow, but hardware, setup etc also have a lot to say.

So long story short, you can't really performance improve your code.


Showing content in popup in Drupal 7 Like Modal Frame API in Drupal 6, is there a similar solution to load content in popup(without page refresh) in Drupal 7?

Take a look at

Modal Forms (with ctools)
Colorbox
Lightbox2

to name a few.  There are probably more out there, but one of those should do what you want.


Drupal 7: hierarchy disabled setting on taxonomy vocabulary I would like to disable taxonomy hierarchy for a vocabulary.
In older versions of Drupal there used to be a setting on the vocabulary page:

  Hierarchy: disabled

Can do I achieve this with Drupal 7?

I found how to do it. I ended up using hook_form_FORM_ID_alter on the taxonomy form in the admin area, like so:

function hook_form_taxonomy_overview_terms_alter(&$form, &$form_state) {
        $form['#parent_fields'] = FALSE;
}


How to list user flags in node I have a node that people can flag to indicate their attendance/interest in that node's activity. However, I would like to show a list of users who have flagged a given node on that node's page. While I can find a way to show a user's current flag state or a flag count for that node in a view, I can't find a way to do this for the node representation itself.

You can relatively easy do that by adding a views contextual filter for the node id (nid) with the following configuration:

When the filter value is NOT in the URL: Provide default value -> Content ID From URL
When the filter value is IN the URL or a default is provided: Specify validation criteria -> Your CTs list
Filter value format: Node ID
The flag relationship used should be: by any user

Of course you can use that view as a block and place it wherever you like.


How do I integrate a Media library to Image Field? I have a image upload element field in my content type. I need to open a media library when I click on browse. My expectation is to select an image which I have already uploaded before. So I don't have to upload the same image again and again.

I've searched but I couldn't find a module for media library in Drupal 8. They are saying it is in the core of Drupal 8. I couldn't find it too. Is there an easy way to do this? Simply what I wanted is a library like in the image.(this is the media library in wordpress)

You are looking for entity_browser.

Setup isn't that easy, so you may want to use an existing browser like media_entity_browser as a starting point.

The media library as shown in your image can be found at admin/content/media, but it's not that helpful when it comes to reusing images on a node.


Checking if a view has view blocks I created a view page; it displays titles and images from the photoset content type. Some of these nodes have a view block.

How can I highlight items on general page with view blocks?
For me it's enough to add some classes to these items.

Set your views display style to unformatted and add preprocess function into your template.php, smthng like

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if ( in this place add your if statement ) {
      $vars['classes_array'][$id] .= ' added_extra_class';
    }
  }
}

You can check for every row needed condition


Migrate : user update resets user roles Using the Migrate module, I created an import task that creates and updates user info from a csv file. The update is launched using drush.

drush -l http://localhost.atrium.com mi Utilisateur --update

All the users are updated appropriately but the user roles, which are not in the migration mapping, are reset for every user that's updated.

How can I avoid that and keep the user roles for every account that's updated ?

Thanks !

You can add fields to be explicitly ignored by adding addUnmigratedDestinations to your class:

$this->addUnmigratedDestinations(array(
  'roles',
  'role_names',
));


How to link price to the product display? I have a page of product teaser links (image, title, price) and I was able to successfully link all except the price to the content with the module Linked Field.

The price field acts differently. The settings are pulled from the Variation settings, and even when a link is set there, the price display remains as before - no link.

Is there a way in Drupal commerce to link the price to the product display?

You normally don't link all fields to your product display, but you reference the product from your product display using the commerce_product_reference that ships in the Drupal Commerce package.

You can create a content type and a product type. Then on the content type add a product reference field. Now the node and the product are linked and all fields (including price) and other properties are accessible for both entities in Views, Rules, etc.

Optionally you can enhance the experience using Inline Entity Form as a widget for the commerce product field. That allows you to fill all the product properties (such as price) when creating a node.


How to prevent comment posting when it has specific words in it? I´ve searched for all Drupal 7 modules that try to give some SPAM protection, but haven´t found what I need, maybe I´ve overlooked something?

I need to prevent anonymous comment posting when comment has specific -configurable- spammy words. How may I do that?

You can try Spam module.

It runs filters on posted content, for example using regexps.

Another way is to write a Rule that examines posted comments and deny them if certain words are found, but unfortunately this module is only available for Drupal 6.

And also you can write a validate function to the comment form, examine the content on submission and use form_set_error if you detect those words. To do this just implemente the hook_form_alter (or the hook form alter with form id), add your valditation function:

$form['#validate'][] = 'you_custom_validate_function';


Override (shorten) breadcrumbs on Views page I'm using Views 3 and I DON'T want the contextual filter to tack itself onto the end of the breadcrumb. In fact, for the whole view, I want only the static breadcrumb Home » My View Name. That's it. Nothing changed or added no matter what contextual filter I click, as long as I'm inside the view.

I tried doing an array_slice($breadcrumb) inside my view's tpl.php file but it seems to have no effect. However, in the same template, $breadcrumb[] = 'salamanders' gives me the word 'salamanders' as the second to last item in my breadcrumb. It does this regardless of whether I have my contextual filter set to override breadcrumb or not, and also irrespective of what text I've actually entered to override it with, when override enabled.

I've tried overriding the breadcrumb in hook_page_alter() inside a custom module as well. Again, I can add to but not subtract from the breadcrumb.

How do I remove elements from my breadcrumb when Views insists on tacking things on to it?

If you're open for contributed modules, I'd suggest that you try Path breadcrumbs. This module will allow you to set up breadcrumb definitions, depending on the path of the page. There you define all items to appear as breadcrumbs, and thus specify whether you want the last item or not, linked or not.


ubercart invoice generation to allow user to request funds withdrawal I have a site where user purchases some service and once the service is received by the purchased person, i should allow the service provider to raise a invoice order to request funds.

what are the modules that i should use to achieve this

If you are implementing the "service" as part of your site, you can attach the "services" to the user by assigning permissions to the "service" to a role, then create a content type, enable it as product and attach a "feature" to a product to enable the role for a limited amount of time (if this is your business model).

This would use CCK (to define the product) + Ubercart (for setting up the shop and attaching Product + feature to product) as well as Permissions (to your "service") and Roles (to apply to the permissions).

I hope this has been of some help!


PDOException: SQLSTATE[42S02] when changing password using Drupal Commons 7 I'm new in using Drupal Commons 7. I've been trying to register a user in the membership site that I'm making but this comes out whenever the user tries to change his password:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table '[name].oauth_common_consumer' doesn't exist: SELECT c.csid AS csid, c.consumer_key AS consumer_key, c.secret AS secret, c.configuration AS configuration, pc.created AS created, pc.changed AS changed, pc.uid AS uid, pc.name AS name, pc.context AS context, pc.callback_url AS callback_url FROM {oauth_common_consumer} c LEFT OUTER JOIN {oauth_common_provider_consumer} pc ON pc.csid = c.csid WHERE (c.csid = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => ) in DrupalOAuthConsumer::loadById() (line 173 of /home4/[name]/public_html/profiles/commons/modules/contrib/oauth/includes/DrupalOAuthConsumer.inc).

How can this be fixed?

This indicates a database table is missing. Given that the error happens in the oauth module itself, I would assume the error is not caused by incompatible modules working together. I can think of three possible causes:

You need to clear the caches.
Whenever you have a problem like this in Drupal, you should try clearing the caches. This can be done by going to Administer > Site Configuration > Performance on your site.
You need to run some database updates.
When you upgrade modules, they sometime needs to run some update code which can, for instance, add new tables or change table definitions. This can be done by going to /update.php on your site.
There was an error when installing this module.
If neither of the possibilities above work, you might want to try to disable this module, and re-enable it to see if there is any problem during installation.
Warning: this will probably require you to disable other modules, and might cause a loss of data. Try this on a copy of the site.


Right way to translate view Titles? As far as I see the view titles are not translatable. As a quick fix I just created a new views-view.tpl.php file and changed the line 32 from:

<?php print $title; ?>

to

<?php print t($title); ?>

What do you think? Is this a right method?

I find existing answers rather confusing.

Views (as we know) is extremely cool module. It supports localization plugins.
Go to page admin/structure/views/settings/advanced to see for yourself:

Preferred way to translate Views is to use Internationalization Views module which depends on i18n_string (i18n package) module.
How to use? Just enable Internationalization Views and go to translate page for your view.

You also may be interested in i18n_string settings here: admin/config/regional/i18n/strings.
Core localization plugin just do t() for Views titles, headers, footers etc. It's not so flexible and secure, but as a developer you can choose this method in some cases.
How to use? Nothing special here. Your strings will appear in Drupal translate interface after the first request.

You can disable localisation at all or create your own plugin if you need.


How to display vocabulary terms and their descriptions with their tagged content in a view? Say I have two terms in a vocabulary, and I want to display their titles and descriptions, along with a list of nodes which have been tagged. Here's an example:

Page Title: Services

Term Name: Medical
Term Description: We're the best doctors in town!
Content tagged with term: Brain Surgery, Leg Amputation

Term Name: Business
Term Description: We'll make you rich!
Content tagged with term: Accounting, Management, Bookkeeping, Strategy

How could I accomplish this using Views in Drupal 7?

I've tried creating a term view, adding the term name and term description fields, enabling a relationship for 'Content with Term', adding a field for 'Content: Title', and grouping by Term name with 'Use rendered output to group rows' disabled, but I still get a ton of duplicates.

Any way to resolve this?

Debunked Methods:

Use aggregation! - Nope, this results in something like this (not what we're after here):

Term Name: Medical
Term Description: We're the best doctors in town!
Content tagged with term: Brain Surgery

Term Name: Medical
Term Description: We're the best doctors in town!
Content tagged with term: Leg Amputation

Use the Views Distinct module! - Nope, nothing here seems to work either.

Update

Jimmy's Answer works well for my situation. Alternatively, I also believe that creating a custom display for your taxonomy and developing a field that displays related content based on TID could circumvent your need for views at all. If you're desperate and less paranoid about logic-less templates, you could do that heavy lifting in your theme (don't do this).

If you don't mind using some other contrib modules with views, Views Field View can be the best solution.

Create content views

First, create a content views to list the content title which contains the taxonomy term, add field Content: Title and add the taxonomy term field as contextual filter. (e.g. Content: Tags (field_tags) in screenshot)

  Use aggregation is to remove the duplicated content because same term can be attached on one content more then once.

Create taxonomy term views

Second, create a taxonomy term views to list the Taxonomy term: Name and Taxonomy term: Term description under a vocabulary, which is similar to the one you have created.

  BUT, you don't need to add the relationship Content with Term neither the field Content: Title

Field Taxonomy term: Term ID is used as contextual argument, so exclude it from display.

Attach views field view

Add a views field, select the taxonomy term view you created and place [!tid] as the argument of Contextual filters.

Result

All required data is ready now, you may need to override the views template files for modifying the output.

Performance

  This method involves multiple views, the performance may become an issue if there are many contents and terms. You should enable the time-based cache on the content views.


Programmatically creating a node doesn't save custom fields I'm using this code in Rules, after saving a certain type of content, in execute custom PHP code. By now, i'm just trying to create anothe node of that type after the first is created.
The problem is that this code creates a new node indeed, but without any custom fields. It has only language associated to it. Any idea on what's wrong?
I followed the tutorial at http://fooninja.net/2011/04/13/guide-to-programmatic-node-creation-in-drupal-7/

$nodo = new stdClass(); // Create a new node object
$nodo->type = "capitoli"; // Or page, or whatever content type you like
node_object_prepare($nodo); // Set some default values
$nodo->language = 'it'; // Or e.g. 'en' if locale is enabled
$nodo->uid = $node->uid; // UID of the author of the node; or use $nodo->name
$nodo->field_numero_capitolo[$nodo->language][0]['value']="2220";
$nodo->field_link[$nodo->language][0]['value']="aafafsf";
$path = 'node_created_on' . date('YmdHis'); // I prefer using pathauto, which would override the below path
$nodo->path = array('alias' => $path);
if($nodo = node_submit($nodo)) { // Prepare node for saving
    node_save($nodo);
    echo "Node with nid " . $nodo->nid . " saved!\n";
}

If I replace

$nodo->language = 'it';

with

$nodo->language = LANGUAGE_NONE;

this code create another node identical to the first one, not considering the values I used in the code and I can't figure out why.

EDIT:
I tried doing as suggested in comments

$nodo->field_numero_capitolo['und'][0]['value']="2220";
$nodo->field_link['und'][0]['value']="aafafsf";

And it seems to work. What i did was to insert directly 'und'. Generally I think it is not a good idea to write directyl 'und', but these two fields are a link and a number, that should not change depending on language.

If you're using Rules anyway why don't you use the Create new entity action which should take care of everything? You will need to use the Set a data value action multiple times and possibly the Save entity action too.

In answer to your question I think you need to set the language before node_object_prepare so your code would become:

$nodo = new stdClass(); // Create a new node object
$nodo->type = "capitoli"; // Or page, or whatever content type you like
$nodo->language = 'it'; // Or e.g. 'en' if locale is enabled
node_object_prepare($nodo); // Set some default values

Also you don't need the node_submit($nodo) line


How do I display bare, stripped content with no menus, footers, etc? Here's what I am trying to do:

I need to have a way to display only the content in a node without any of the Drupal adornment. All I want is the styles to be inserted, and the content itself.

The reason I am doing this is I am setting up a portfolio web site that contains examples of work. Each clip will be displayed in a lightbox2 popup. A lot of the clips were authored in Drupal.

I don't want the site title, menus, and all of that garbage to show inside the lightbox. Just the content.

I did the following, which seems to be a non core files hacking way of doing things:

I created a new content type, called "barepage". I copied some content into barepage.

I created a new content specific template file for barepage: node-barepage.tpl.php.

Just for testing, here is what is inside this file (I commented out the actual content):

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix">

   <?php if (!$page): ?>
<?php endif; ?>

   <?php /* print $content; */ ?>

  <?php   if (!$page): ?>
<?php endif; ?>

All of the standard Drupal stuff displays: the page header, the primary navigation links, the node title inside the page, and the page footer. But as expected, the content is empty.

of course, if I uncomment $content, the page displays like a standard "Page" content type.

What in the heck do I override to eliminate all of this stuff and just display the content? I'm trying to avoid hacking the template's core files or the Drupal core.

This is with Drupal 6.2, and the Zen theme with the CTI_Flex subtheme.

Main layout of a page is done in the page.tpl.php file. You have to override that templates for your bare pages in order to not output anything you don't want to see on the page. The correct way to override the used templates for a particular situation is to use suggestions.

From the Drupal 6 Template Suggestions, you can see that the suggestions to override this templates are summarized as page-[front|internal/path].tpl.php. So, out of the box, you only have to option to provide a bare template for either the front page of the site or all pages starting with a given path. There is no suggestion that allow you to override the page.tpl.php template for node pages of a specific content type.

But if you look at the page.tpl.php documentation, you see that the template has access to a $node object: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345). Using this information, you can use the template preprocessing in your theme to add an additional page.tpl.php suggestion.

function THEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) {
    $node =& $variables['node'];
    $op = arg(2);
    if (empty($op) || $op == 'view') {
      $variables['template_files'][] =  'page-'. str_replace('_', '-', $node->type);;
    }
  }
}

This should add the page-<content type>.tpl.php template suggestion for node pages. You can then create the page-barepage.tpl.php file with your simplified markup.

Keep in mind that this will not prevent Drupal from processing and rendering any blocks for the page, it will only prevent them from being outputted in the page.