Using jQuery Tools with Drupal 7 I have looked online to see if it is possible to use jQuery Tools 1.2.7 with Drupal 7. I see that there is a defunct project that attempted to use it in Drupal 6 but nothing for Drupal 7. I tried downloading it and including it in the scripts line in the .info file for my module but still not executing. I suspect the issue might be that jQuery Tools expect jQuery 1.7.2 while Drupal 7 uses jQuery 1.5.

The specific feature that I am trying to use is the overlay function. I followed the online documentation but I don't see any overlay. All it does is reloading the same page over again. I was wondering if anyone has used the overlay module with Drupal 7 and has gotten it to work.

You're approaching this correctly in trying to add this in your own info file - not every jQuery library needs its own Drupal module and its often more overhead than its worth to try and set one up. If the jQuery tools module is what you need but its not compatible with the current version of Drupal 7, than use jQuery Update module to upgrade your version of jQuery.

If all you need is the overlay and you're not tied to the jQuery Tools implementation, you have a couple of customized Drupal options that should be easy to implement:

The built-in overlay functionality in Drupal 7.x core (see https://drupal.org/node/1087026 for guidance on how to implement)
Use one of the specialized overlay libraries - best one I've found is Colorbox, which has a Drupal module with easy to implement solutions (i.e. no hand-coding javascript)


Why are my $messages delayed one page refresh? I have a page with a very simple template:

<!DOCTYPE html>

<title>TEST REGISTRATION PAGE</title>

    <?php
        print drupal_get_form('user_register');
        print $messages;
        print $closure;
        print $main_content;
    ?>

Basically, it displays the registration form and nothing else.

I enter some bad data on the form — an already used username (admin), and no email address.
I click "create new account".
The page seems to submit and reload, but nothing has happened — no error messages are displaying.
I refresh the page (F5).
Firefox displays "to display this page, Firefox must send information that will repeat any action that was performed earlier" — so I know that my POST went through previously.
I click "resend" in that dialog window.
My error messages appear — "e-mail address field is required", "the name admin is already taken".

This occurs for all of the forms I've tested so far, not just the registration form.

Why is this happening? What can I do to fix it so that the error messages display the first time?

I'm happy to do whatever I need to do debug this, but I need some direction to start looking in. :)

Most likely the problem is that you are calling the form when the messages already have been created, which is why they don't appear. You need to call the form, earlier in the process of the page being built or get the messages, with drupal_get_messages.

What you really should do it is to create this functionality in a module and theme the page instead, of doing this in your theme. You could potentially run into many more problems like this.


How do I display self-hosted video content What I am trying to do is embed a self-hosted video on a webpage. I have the video uploaded onto the web hosting in mp4, ogv and webm formats; converted where necessary using Miro Video Converter (if that helps?).

The code I have in place on the webpage is:

<video width="90%" controls>
<source src="/system/files/HBA_ONLINE.mp4.mp4" type="video/mp4">
<source src="/system/files/HBA_ONLINE.webm" type="video/webm">
<source src="/system/files/HBA_ONLINE.ogv" type="video/ogg">
Your browser does not support this video tag - Try viewing directly  here </video>

The only format that seems to work is mp4 on Google Chrome; other browsers simply won't play the video in any format.

The silly question is; do I need to use a dedicated Drupal 7 module???

A learning process for anyone who makes the same mistake.

I found that the files had be uploaded with role based content access as part of our file repository. That meant anonymous users would get a 403 error.


Drupal Commerce cart page to enter items I have a website I am working on, and I want to have a shopping cart page that is basically like a purchase order entry form, where a customer can enter the products he wants and then save it or post it, etc. In other words, so you don't have to go through the whole site selecting the products you want like a shopping cart, but rather just enter the item codes like you were writing out a purchase order. The website is for a producer basically and the customers are distributors.

I need to be able to enter products by item code or UPC (need both), and it would be a bonus if each user account could have a list attached to it where the customer could enter their own item codes for our products.

I hope this makes sense, can someone point me in the right direction?

Check out the module Commerce Add to Cart Extras. This got me started. Also, the module Views Field View I used to show the quantity that was ordered last time.


Views to Recognize my Custom Entity's One-to-Many Reference I have a drupal 8 custom entity and have it referencing another custom entity of a different type. It is a one-to-many relationship like a department with assets. It won't recognize the assets relationship (but it will recognize the one-to-ones). How do I make that bridge in my EntityViewsData extended class so that I can use assets in the Relationships section of the Views UI? I have scoured the docs and core entities and cannot find the answer.

More info: The department has a base table 'department' and another table 'department__assets' that the reference created. 'department_assets' has a field 'entity_id' that connects the table to the department and a field 'asset_target_id' that connects the asset table. The assets base table is  'asset'.

That's currently a gap in the automatic entity views data integration, it can only do multi-value configurable fields.

Work is going on to improve this, not sure if it will make it into 8.1 now, probably it will have to wait for 8.2, but you could already use the patch: https://www.drupal.org/node/2477899


Add state for Germany and drop-down menu How do you change the default fields in the addressfield Module for a given country?

For Germany you have , while for USA you get , including a nice drop down menu with all 51 states.

I want to change the Germany default to have

only one address field (only Address 1)
a field with a drop down menu, showing the states of Germany.

I read on drupal.stackexchange that it should be possible with hook_form_alter or with ctools module, but within 4 hours of browsing and trying, I could not figure out how?

I'm using drupal for 5 months, so I would appreciate a detailed answer, but also any short link, that helps me to solve that issue, is highly appreciated.

Address Field module uses a plugin system for building the address fields. You should create an address field plugin in your custom module.

hook_form_alter() wouldn't help much in this case.

To create a plugin for Address Field, you should first implement hook_ctools_plugin_directory() in your module to tell you have an addressfield plugin and where they live:

function YOURMODULE_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield' && $plugin == 'format') {
    return 'plugins/format';
  }
}

Then, create the folders plugins/format in your module. The folder names are up to you. Under this folder create an .inc file, and give it a relating name, like german-states.inc.

In this file, you should define a $plugin array, which holds the information about your plugin, including the callback function name. Then define a function which can add new form elements, edit existing form elements etc.

$plugin = array(
  'title' => t('German States'),
  'format callback' => 'YOURMODULE_format_german_states_generate',
  'type' => 'name',
  'weight' => 0,
);

function YOURMODULE_format_german_states_generate(&$format, $address) {
  // Add new form element for German states
  if ($address['country'] == 'DE') {
    $format['locality_block']['administrative_area'] = array(
      '#title' => t('State'),
      '#required' => TRUE, // Set this FALSE if you don't want it to be required.
      '#attributes' => array(
        'class' => array('state'),
        'x-autocompletetype' => 'region',
        'autocomplete' => 'region',
      ),
      '#options' => array(
        '' => t('--'),
        'BW' => t('Baden-Württemberg'),
        'BY' => t('Bavaria'),
        'BE' => t('Berlin'),
        'BB' => t('Brandenburg'),
        'HB' => t('Bremen'),
        'HH' => t('Hamburg'),
        'HE' => t('Hesse'),
        'NI' => t('Lower Saxony'),
        'MV' => t('Mecklenburg-Vorpommern'),
        'NRW' => t('North Rhine-Westphalia'),
        'RP' => t('Rhineland-Palantine'),
        'SL' => t('Saarland'),
        'SN' => t('Saxony'),
        'ST' => t('Saxony-Anhalt'),
        'SH' => t('Schleswig-Holstein'),
        'TH' => t('Thuringia'),
      ),
    );
  }
}


Set default to empty result with views exposed filters I am using Views (7.x-3.0-beta3) and I have created a exposed text filter to a view, which work fine.

The problem is the default result value: when the field is empty, is displaying all possible results. But I want to display the empty result by default. If you have a solution please shear it.

You can use a views preprocessor to achieve this. The 'empty' element behaves similarly to the "No Results Behavior" option in the Views UI. Place this code in template.php and clear the cache:

function mytheme_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view_name') {
    if (empty($vars['view']->exposed_input)) {
      $vars['rows'] = array();
      $vars['empty'] = '';
    }
  }
}

Tested using Views 7.x-3.0-rc1.


Migration from csv problem (Incorrect string value: '\xAB Nove...') In my drupal 8 project, I'm trying to import data of a content type from a csv file, everything is well, but when I'm trying to execute the migration command drush mim my_migration I got the following error:

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xAB Nove...' for column 'sourceid1' at row 1 in                   [error]
/Users/brahim/Sites/news8/core/lib/Drupal/Core/Database/Statement.php:59

It seems like a problem of database encoding.. but I don't know what is it really, any idea about the solution?

maybe related to the source file encoding format (try with UTF-8). Check also for string issues (special characters) on the source file.


How to render html tags in field collection items? How is it possible to render also the html tags of a field collection item?
If i do something like this in a textfield (Full html) of an item:

TEST

I also get this in frontend, with no rendered html tags.

Node Theme:

{% for details in node.field_cv %}

{{ details.getFieldCollectionItem().field_cv_title.value }}

{{ details.getFieldCollectionItem().field_cv_details.value }}

{% endfor %}

Thanks for helping!

When you use Field Collection you get nested templates. So start with the outer div container in the node template:

  {{ content.field_cv }}

This produces a new set of templates, which you can see when you switch on Twig Debug. The next level is the field template:

field--field-cv.html.twig

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

and inside you'll find the field collection templates:

field.collection.html.twig

{%
  set classes = [
    'field-collection-item',
    'field-collection-item--name-' ~ field_collection_item.name|clean_class,
    'field-collection-item--view-mode-' ~ field_collection_item.view_mode|clean_class,
  ]
%}

    {{ content }}

Which you all can use for the custom html markup.


Is there a way to include jQuery-1.10.2 for specific php functions? I need to include jquery-1.10.2 for a module I am building in Drupal 7.  The problem is, if I include the file with drupal_add_js in the module's .inc file, it causes the admin menu to display strange (there is no space reserved for it on the screen, so it is usually covered)  I've gotten around this by calling drupal_add_js right inside the page callback function for the pages that need jquery.  When I do this, the admin menu works fine, but if you click on any items shown in the overlay, the first time you click, there is a javascript error saying:

  Uncaught TypeError: Cannot read property 'msie' of undefined

If you click the same button a second time, the overlay will load, but I need to fix this so that there aren't any bugs.  I've done some research and it looks like this is because $.browser is depreciated as of 1.9.

So I was wondering if there is a way to include jS but to only have it applied to a specific function or maybe only to the 'content' div of the page?  I did find hook_init which supposedly runs whatever commands are inside the function as the pages for that specific module are loaded, however it still seems to apply the include to all pages of my Drupal install.

The issue is that the admin is trying to load two different versions of jQuery and causing conflicts.  The latest version of jQuery Update 7.x-2.4 allows you to control the back and front end versions of jQuery.  This may still cause problems with using the overlay but for the most part seems to fix the issue.  If you are still having issues you will need to look into a solution on loading two different versions of jQuery, outlined here or disabling the overlay module.


Views Auto-Refresh giving ajax error after some time After creating views and implementing the views auto refresh on that it works fine for 8-10 minutes but after that giving error in alert "An AJAX HTTP request terminated abnormally.Debugging information follows.Path: /?q=views/ajaxStatusText: errorResponseText:ReadyState: 0" and stop refreshing then. why it is happening and how to resolve it?

It happened to me when views auto refresh ajax had not finished loading and I clicked on a link.

Here is a link to the drupal forum talking about this. https://www.drupal.org/node/1232416

I personally used the sandbox module in comment #183 to solve my problem.


Is it possible to implement an express checkout with Drupal commerce? I'd like to setup a product, where it's just a one page form customers fill out, and a button labelled 'Pay now'.

I don't want a list of products or add to cart functionality or anything like that. Just a simple form and a button. A confirmation page and email is fine.

Is it possible to do this with Drupal Commerce?

Here is a nice tutorial on how to set up an EXPRESS CHECKOUT using Rules
to bypass the add to cart stage.

I noticed there is a Commerce Express Checkout module, but I personally rather use rules to do it.

To display this on your home page, using the views module you'll need to create a block view  of your product and put it in your home page.


8.4.4 CKEditor Link & Unlink Buttons suddenly missing In Drupal 8.4.4 the CKEditor is suddenly missing the Link and Unlink buttons for all content types, for the Basic Editor and the Full HTML Editor as well.  My users and I can no longer add links to anything, and if I edit articles any link html disappears in the editor altogether (I noticed the issue after editing and saving an article and then noticing the links that were there moments before were suddenly gone).

I went to admin/config/content/formats to configure the editors to add the buttons back, but when I click the Configure button for Basic HTML I get the dreaded "The website encountered an unexpected error. Please try again later." message.  Drupal error log shows the following:

  TypeError: Argument 1 passed to Drupal\Core\Render\Element::children()
  must be of the type array, null given, called in
  /core/modules/ckeditor/src/Plugin/Editor/CKEditor.php on line 177 in
  Drupal\Core\Render\Element::children() (line 71 of
  core/lib/Drupal/Core/Render/Element.php).

  Drupal\Core\Render\Element::children(NULL) (Line: 177)
  Drupal\ckeditor\Plugin\Editor\CKEditor->settingsForm(Array, Object,
  Object) (Line: 64)
  Drupal\editor\Plugin\EditorBase->buildConfigurationForm(Array, Object)
  (Line: 175) editor_form_filter_format_form_alter(Array, Object,
  'filter_format_edit_form') (Line: 501)
  Drupal\Core\Extension\ModuleHandler->alter('form', Array, Object,
  'filter_format_edit_form') (Line: 830)
  Drupal\Core\Form\FormBuilder->prepareForm('filter_format_edit_form',
  Array, Object) (Line: 272)
  Drupal\Core\Form\FormBuilder->buildForm('filter_format_edit_form',
  Object) (Line: 74)
  Drupal\Core\Controller\FormController->getContentResult(Object,
  Object) call_user_func_array(Array, Array) (Line: 123)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  (Line: 582)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
  (Line: 124)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array,
  Array) (Line: 97)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  call_user_func_array(Object, Array) (Line: 153)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line:
  68) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
  (Line: 57) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
  (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object,
  1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line:
  78) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
  (Line: 50) Drupal\ban\BanMiddleware->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1,
  1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1,
  1) (Line: 23) Stack\StackedHttpKernel->handle(Object, 1, 1) (Line:
  657) Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

I don't know if this is related to recently updating Drupal to 8.4.4, but I was not encountering this issue before as I've made many articles in the past month with links that still work.  I have no idea how to debug or fix this issue, or if it's a known bug, please any help is appreciated.

I figured out the issue.  Apparently something changed in the Drupal 8.4.4 update that caused the scripts related to the link/unlink buttons to work longer than usual, which was causing a PHP timeout exception (when checking the browser console it gave an HTTP Result Code: 200 error, which apparently happens regularly with Drupal).  So in my settings.php file I increased the timeout by adding the line:

ini_set('MAX_EXECUTION_TIME', 7200);

You can also configure this in your host settings.


why does hook_menu produce a menu that belongs to the system module? In my project we implement a little menu that provides information about the module.  This snippet lives in drutexml.module.

function drutexml_menu() {
  $items['drutexml'] = array(
    'title' => 'LaTeX filter implemented via LaTeXML',
    'page callback' => 'drutexml_information',
    'access callback' => TRUE,
  );
  return $items;
}

Actually this is a bit silly, and I want to turn it back off inside the installation profile.  But as it turns out...

SELECT link_path, module FROM menu_links WHERE link_path = "drutexml";

+-----------+--------+
| link_path | module |
+-----------+--------+
| drutexml  | system |
+-----------+--------+

and then in menu.inc, where menu_link_delete is implemented, we see this  bit of logic on line 2997:

if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) { ...

In other words, I can only delete non-"system" links.  That's fine with me!  Or it would be, if my link was stored with the name of the module where hook_menu is implemented in the first place.

What's going on here?  Why is this said to be a "system" link?

The only way to remove a menu item defined from a module in hook_menu() is, apart from removing its definition from the module's hook_menu(), removing it with hook_menu_alter().

function mymodule_menu_alter(&$items) {
  unset($items['drutexml']);
}

Menu items that are part of a menu, including the ones defined with hook_menu(), are saved in the menu_links table. Those defined in hook_menu() are saved setting the "module" field to "system" to distinguish them from other links directly added from a module.


How to translate custom date formats? I created a custom date format j F Y at Configuration » Regional and language » Date and time » Formats. I'm pleased with the overall look, but I'd like the months to be written in Dutch instead of the default English. The month names should be translated everywhere they occur and it would be perfect if the days should be translated too (maybe I'll need them in the future).

How can I do this?

This is a lot harder to do than I first thought.  Formatted dates, including strings for the month (and day) names are produced by format_date().  This function is not themable, and there is no hook to override it.

That means that (AFAIK) there is no right way to change how this function behaves (the wrong way is to hack it - i.e. hack core - which is not an option in my book).

What we can do is to make a tiny custom module with a version of this function that outputs months and days in Dutch, no matter what the default language for the site is.  This function will do this:

function MYMODULE_format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
  return format_date($timestamp, $type, $format, $timezone, 'nl');
}

(Where MYMODULE is the name of your custom module.)

Now, if you set the default language of your site to English, but keep the Dutch translation available, one of the following calls:

MYMODULE_format_date($timestamp, $type);
MYMODULE_format_date($timestamp, 'custom', 'j F Y');

(where $timestamp is the timestamp to print and $type is the format to use) will output names of months and days in Dutch, but everything else will be in your site's default language.  The first will do this for any valid format (Long, Medium, Short, etc.), the second for the custom format 'j F Y'.

This will give you Dutch month names if you call this custom function instead of the standard one when outputting formatted dates.

However, it will not change the output in existing code which of course uses the standard version of the function.  This may not be a problem for you, since you want to use it with a custom date format (which obviously is not in use in legacy code), but I still want to make that clear.

If you want to change how months and days are spelled everywhere, you need to override the templates node.tpl.php and comment.tpl.php (and possibly other templates that uses format_date). In the override, just replace any calls to format_date with calls to MYMODULE_format_date.


How to edit order summary field labels on paypal page My company sells online services and I have been able to limit my customers to buy one service at a time with the help of rules. However, when my users are directed to paypal, following information is presented to them on the paypal site:

Is there a way I can edit paypal label ‘item price’, as can be seen in the above shot, to something else such as ‘service charges’. Also can I remove the quantity field all together, as my users are unable to purchase more than one service at a time. No point to show the quantity to them.

I am using following code to remove quantity field, but it still appears on paypal. Also, I am unable to find the field label: item price in this hook.

function checkout_forms_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
unset($data['on0_1']);  //to remove options
unset($data['os0_1']);  // to remove quantity field
}

The Paypal WPS API can be used to hold multiple individual items, but it can also just be used to handle a single order. It effectively does this by making the Drupal order the only product on the PayPal order.

If you are wanting to customize checkout further, you'll need to find another processor that gives you that ability. PayPal PayFlow Pro or some other option might work.


Preventing webform saving in database Is there a way to prevent a webform submission to be saved in the database?

I have added a custom submit handler to my webform but I don't want to save in the DB but send it to an external webservice.

function MY_MODULE_form_alter(&$form, $form_state, $form_id)  {

    if ($form_id == "MY_WEBFORM_ID")  {
        $form['#submit'][] = "_MY_MODULE_webform_handler";
    }

}

function _MY_MODULE_webform_handler($form, &$form_state) {
    // How do I stop data being saved in DB?
}

How do I do that? Thanks!

There is a module that's compatible with the 7.x-3.x branch that gives you the option to do just that:

  This module adds the ability to choose whether a webform should be saved to database or not. Within settings of each webform you can choose the option.

There is also a related issue in Webform's queue that is tracking the progress of getting the functionality into the webform module.

If you don't want to use the sandbox module, I'm sure you could check out the source and see what they're doing differently from what you have posted above.


How to let users register with their Facebook accounts? I would like to let visitors choose between signing up by using Drupal's core sign-up system, or to register using their Facebook account.

I looked at a few Facebook related modules but that was a little confusing, and I couldn't make up my mind on which one to use (I don't use Facebook myself so I guess that doesn't help).

What are the differences between regular registered users and those who signed up using their Facebook account?
Will Drupal have access to their emails?

Drupal for FaceBook is the one you need.

You can configure application settings and which information you want to get from users, such as email address.

Unlike other suggestions, this module does not rely on third party providers and registrations other than Facebook.


How to implement hook_field_widget_form() for multiple fields? In a module I'm going to implement some Field types using Field API.
this is how hook_field_info() looks like in my module.

function myModule_field_info()
{
  return array(
    'type1' => array(
      'label' => t('Custom type 1'),
      'description' => t('Just for test'),
      'default_widget' => 'type1_textbox',
      'default_formatter' => 'type1_rawview',
    ),
    'type2' => array(
      'label' => t('Custom type 2'),
      'description' => t('Just for test'),
      'default_widget' => 'type2_textbox',
      'default_formatter' => 'type2_rawview',
    ),
  );
}

and the hook_field_widget_info() implementation is :

function myModule_field_widget_info()
{
  return array(
    'type1_textbox' => array(
      'label' => t('Text field'),
      'field types' => array('type1'),
    ),
    'type2_textbox' => array(
      'label' => t('Text field'),
      'field types' => array('type2'),
    ),
  );
}

off-course this is just an example and each widget has its especial form . now consider that each of my field types has more than one element .

Field type 1

first name
last name

Field type 2

phone number
address
email

now the question is how should I implement widget form for a multiple field type like this?

I tried this code but no chance :

function myModule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
{
  if($field['cardinality'] == 1){
    $element['#type'] = 'fieldset';
  }
  switch ($instance['widget']['type']) {
    case 'type1_textbox' :
      $type1 = array();
      $type1['firstName'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('First Name : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['firstName']) ? $items[$delta]['firstName'] : '',
      );
      $type1['lastName'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('Last Name : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['lastName']) ? $items[$delta]['lastName'] : '',
      );
      $element += $type1;
      break;
    case 'type2_textbox' :
      $type2 = array();
      $type2['phoneNumber'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('Phone Number : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['phoneNumber']) ? $items[$delta]['phoneNumber'] : '',
      );
      $type2['address'] = array(
        '#type' => 'textarea',
        '#field_prefix' => t('Address : '),
        '#size' => 60,
        '#default_value' => isset($items[$delta]['address']) ? $items[$delta]['address'] : '',
      );
      $type2['email'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('Email : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['email']) ? $items[$delta]['type2']['email'] : '',
      );
      $element += $type2;
      break;
  return $element;
}

The code was edited and now no widget is shown in node-edit form and when I went to field management section this error is appearing

the name of the form in   myModule_field_widget_form must be the same column in your  .install file  make sure it matches the same  column


Is the "size" field in file_managed used for anything? I'm having to import videos and video thumbnails manually to the file_managed table since there is no migrate support for it yet.

I'm wondering if the size is really used for anything?

It's used in a few places:

theme_file_link() where it's used to add microformat data to a file link (per http://microformats.org/wiki/file-format-examples).
file_space_used() where it's used to "determine total disk space used by a single user or the whole filesystem".
file_validate_size() where it's used to "check that the file's size is below certain limits".

It's probably a good idea to fill this field in if you're able, or at least run a small script to do so after you've manually entered the records. Something like this maybe:

// The filesize column defaults to 0 so it's an easy check.
$fids = db_query('SELECT fid FROM {file_managed} WHERE filesize = 0')->fetchCol();

// Loop through the files and update the file size field.
foreach (file_load_multiple($fids) as $file) {
  $file->filesize = filesize($file->uri);
  file_save($file);
}


Disabled item in menu in menu_tree_all_data I want to fetch all menu item list from specified menu list, I can fetch all of them with menu_tree_all_data, It return all item of menu and when I looked in in result I don't see enabled property
my sample code

  $menuItems=menu_tree_all_data('menu-footer-menu');
  dpm($menuItems);

(after that I put this in foreach statement and print them, but I want exclude disabled menu items)

My question is how can I find out that the menu item is disabled ?

'hidden' key in the array returned, will tell you if the menu links is enabled or disabled. For all disabled menu links hidden will be '1'.


Can you filter views user list result based on the current users role Is it possible to have the result of a views user list only contain users with a specific role that the current user also has?

I'm not familiar with Views, but it seems to fit the bill for making a better looking and more usable user list than the one that comes standard with Drupal. However, I need to have the user list filtered.

I setup multiple user groups that are identified by a specific role (like groupmember - group A). Admin users of that group have an additional admin role (like group manager), but they should only see users in their own group when using the view.

Can something like this be done? I'm writing modules so I could use the api if that is the way to go. I'm using Drupal 7.

As I understand, you want to create a view which list users which lists only those users who has a specific role or roles that the current user also has. The below approach can be a solution :

Add a field 'User: Uid' in your view (Let the view is of type 'Users').
Make the field as 'Exclude from display'.
Add a 'global php' field and add some code as below under 'VALUE CODE' :

$user_load = user_load($data->uid);
$data->user_role = $user_load->roles;
return ($data->user_role);

Here, we are getting the roles of each user being rendered.

Here used '$data->uid' instead of '$row->uid' to avoide issue of returning NID with $row in D7. Although in this case '$row->uid' returns correct information.
Make the field as 'Exclude from display' as well.
Under Filter Criteria add a 'global php' field and add the below codes :

i) Under 'Setup Code' :

 global $user;
 $roles = array();
 $view->roles = $user->roles;

Here we are getting all the roles of the current user.

ii) User 'Filter Code' :

 // Suppose you have five roles in the instance with the 'rid's as saved in
 // 'role' table as : 1 (anonymous user), 2(authenticated user), 3(administrator), 4(hr), 5(web admin)
 // Suppose ROLE you want be matched has RID = 4
 if (isset($view->roles[4])) {// Checking if the current user has the role that you want to be matched with
   if (!isset($data->user_role[4])) {// If the user getting rendered doesn't have that role
     return TRUE;// If TRUE is returned, then that row is NOT shown
   }
 }

Note : Considering, 'views_php' module is installed.

Note : If the current user doesn't have the role that you want be filtered for, then the view will list the default list of users based on other conditions.

Note : Instead of writing the 'rid' in the filter code directly, we can provide an admin menu which will render a custom form with a text field and, admin or user with required access permission, can set any role(s) through that form and save it in a drupal variable, and we can render the role information we want be matched from the variable inside our filter code.

Hope it helps


Why don't {{ product.body }} and {{ product.field_specifications }} return values in custom commerce-product.html.twig file I am using Commerce 2.0 on Drupal 8.4.

I have sub-themed Bartik and placed a commerce-product.html.twig file in the sub-theme's /templates folder to experiment with theming a Commerce2 product page.

My product-type has a custom field called 'specifications'.
The Manage-display for the product-type places both 'body' and 'specifications' in the Content portion (not disabled).

An example product of this product type was given the following values.

title = "Product 1 title"
body = "Product 1 body"
specifications = "Product 1 specifications"

The product-display page for Product 1 displays the following for the corresponding twig commands:

{{ product.title }} displays "Product 1 title"
{{ product.body }} displays nothing
{{ product.field_specifications }} displays nothing

{{ product_entity.title.value }} displays "Product 1 title"
{{ product_entity.body.value }} displays "
Product 1 body
"
{{ product_entity.field_specifications.value }} displays "
Product 1 specifications
"

Seeing that

{{ product.title }} and {{ product_entity.title.value }} agree.

why does

{{ product.body }} display nothing while {{ product_entity.body.value }} displays something.

and

{{ product.field_specifications }} display nothing while {{ product_entity.field_specifications.value }} displays something.

(An informative discussion of the field variables available in commerce-product.html.twig is here)

why does
{{ product.body }} display nothing while {{ product_entity.body.value
}} displays something.

This is because {{ product.body }} returns an array not a single value. Body has other properties such as summary so you need to specify what you want from that field.

why does
{{ product.field_specifications }} display nothing while {{
product_entity.field_specifications.value }} displays something.

I'm not sure what field type you set field_specifications to, but I'm guessing you set it to a formatted text field. If that's the case it would return an array just like Body would. If field_specifications was simply a textfield, {{product.field_specifications}} would have worked.


Warning: Permission Denied, While clearing the cache When I clear the cache of the site, I get lot of warnings with

  "Permission denied in drupal_unlink() (line 2199 of home/public_html/sitename/includes/file.inc)."

And I am unable to upload any default image to the site with the warning

  "File Could not be uploaded"

Check your temp folder under "admin > config > media > file system": It should be writeable.


Accessing properties of attached file I have a custom content type which allows one file to be attached to it. In the teaser of the node I want to fine-print the date of the file's (rather than node's) last modification and its size. How can I access those properties in a suggestion template file or in the field-based View that generates the list of teasers?

I am using Drupal 7, and version 7.x-3 of the Views module.

Partial answer, but in the views settings page, you add a relationship to the field that holds the file.  Then, when you add a field, you should see an option for File: Size in the list.  Other fields for file into appear, but mtime isn't one of them.

A hackish way to get mtime is to use stat in your view template, but I would do that as a last resort if you can't find a module to add this as a view field.


Duplicated results using fields from relation File Usage: file I have a content type with a field image and a field file. I made a simple view to get all items of that content. I included in my view a relation ¨File Usage: File¨ to get some data like file size, upload date and uri of file field and for using VBO to download all files.

Now Im getting duplicate results, all data (file size, upload date, vbo) for image field and the same for file field when I just want to get the information for the file field, the image is just a thumbnail. Any ideas of how to get real results over duplicates?

You need to add a File relationship for a specific field, not a File Usage relationship.

In the options for 'Add relationships' select the 'File' filter and you should see an option for each field e.g. 'File: Content using My Field'. Use this and it will give you the same data (file size etc.) but just for files attached to that field.


Drupal multilingual menu I have created one menu for all languages and set the items as neutral and added the language translations. But when I add translations, only the title field is working and it's not working with others field.

Install Internationalization module and enable Menu translation sub module. Now it allows users to select a translation mode for each menu.


How do I mark translation strings as non-customized? Drupal 8 distinguishes between "customized" and "non-customized" translations.

A customized translation is a translation that has been imported from a module and then changed at /admin/config/regional/translate.

So, if I edit a translation that has been imported, it becomes customized.

What if I edited many translations, but then changed my mind and wanted to restore them to the default?

How can I revert a customized string into the original non-customized one?  (And is it possible to do this to strings in batches?)

Based on 4k4's suggestion, I was able to do this with SQL:

drush sqlq < "UPDATE mydb.locales_target SET customized = 0 WHERE customized = 1;"

Warning: This will unset the customized flag for all strings on your site, but leave the customized translations in place.  This is what I wanted, but make sure it's what you want too before running the command.  Always make a backup, etc.


How can I have editors select which blocks to be displayed in what order per page? I have taken on a site that has hard coded page urls in it's page.html.twig for loading specific sidebar blocks based on the url for related content.
eg:

  {% if 'frozen' in url|render|render %}
              {# shows these blocks and in this order #}
              <aside id="sidebar">
                  {{ block_chooserecipes }}
                  {{ block_healthbenefits }}
              </aside>

Is there a way to create a content type field that will load the sidebar blocks that the editor wishes to include with their main content?

You can have a checkbox field for sidebar block in your content type. Once user selects a set of block to be visible, check those checkbox values in your page.html.twig. Print only those blocks which are checked by user.


How can I use jQuery 1.7 without having issues in the admin pages? Is anybody successfully running jQuery 1.7?
I'm using a jQuery component on my pages which requires jQuery 1.7 or later. This version causes some unwanted side effects in the admin UI, such as checked checkboxes that don't reveal additional controls when available, or field widget not being active.

I was wondering if there's a solution that could let me easily work with jQuery 1.7.

I saw this answer before asking. As far as I understand, there are 2 separate issues: updating src of the jQuery to 1.7.x, and updating the javascript used by admin. I tried to use the latest jquery_update development snapshot, and apply a patch, but it does not solve the above-mentioned problems with UI.

I would look at Clive's advice on doing it manually here:

How do I update jQuery to the latest version I can download?

and add some more intelligence into the script to not do it on admin pages, eg:

if (arg(0)=='admin') {
  return;
}

You would also have to do that on node/#/add and node/#/edit pages etc so as to not disrupt anything "core" there, or, if you want, dive into drupal core and bring everything else up to 1.7 as well.

Depending on what version of Drupal you are running, this might also work:

function YOURTHEME_preprocess_page(&$vars) {
  if (YOUR CONDITION HERE) {
    $scripts = drupal_add_js('PATH TO YOUR JQUERY FILE');
    unset($scripts['core']['PATH TO DRUPAL JQUERY FILE']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

where you could set "YOUR CONDITION HERE" to be whatever pages you want the new jquery on, eg, arg(0)!='admin' etc.


How to select a particular user role which could be flagged There are two Roles:

Authenticated
Artist

I have created a flag with flag type "USER".
The flag is used so that the Authenticated Users can follow the Artists.

As the flag is type of user, an authenticated user can even follow another authenticated user.

How do I restrict the flagging to be applied only to the Artist? i.e the authenticated user can only follow an Artist and no user of any other role.

You can achieve your requirement by following below steps.

Create a view of type User.

Add a relationship to Flag.

Now add Flags: Flag link field + extra field you want to display
Finally add a FILTER CRITERIA i.e. User: Roles and select Artist user role.


Different page appear when testing What I want to do is checking whether a link is exist on frontpage.

I've set up a content with with node id 5 as my frontpage.

But when testing it, and see the verbose message (http://screencast.com/t/ldWSBwJNcO)
different page appear. The default drupal frontpage appear instead of the content that I've set up.

My test code:

class MyUserManagementTestCase extends DrupalWebTestCase {

  // Some says this improve tests performance
  protected $profile = 'test';

  public static function getInfo() {
    return array(
      'name' => 'My User Management Test Case',
      'description' => 'Ensure that the My functionality for user management works.',
      'group' => 'My',
    );
  }

  public function setUp() {
    parent::setUp();
  }

  public function testFrontpage() {
    $this->drupalGet('');
    $this->assertResponse(200, t('Frontpage page is accessible'));
    $this->assertLinkByHref('user/register');
    $this->assertLinkByHref('user/login');
  }
}

In Simpletest each time the test is run. New Drupal install will occur. You are testing the Simpletest Database right now. There is a possibility to run simpletest on "live" db. To do so add $this->originalPrefix = $GLOBALS['db_prefix'] to your setUp()


Acquia stack / Wamp slow on response I am developing a site on my localhost. I used WAMP but it takes too long to load pages from time to time. Something like 20 seconds execution time according to devel. Not on every page, not every time, but happens often enough to disrupt any kind of work I am trying to do.
After no much success in debugging the problem I decided to try "DAMP" the Acquia stack for Drupal.

The difference is enormous- execution time is less than 1000 ms, which although much is something workable for dev. stage; Memory used peaks at 12 MB instead of 50 in wamp.

Still there is this problem of pages not loading fully. When I click on a link the browser shows that it is "connecting" and it will stay like that indefinitely (takes more than 2 minutes to time out), but if I interrupt and refresh the page loads instantly (100-300 ms)
This again would be acceptable if it didn't interfere with my work. I can't add or delete content because of this. It just stays on "connecting" and on refresh it hasn't made the action.

So my question is what makes acquia stack not finishing the page loads and wamp server to be so damn slow?

I am talking about drupal 7, hardware shouldn't be an issue (Core 2 duo at 3.1 Ghz, and 3 GB RAM, somewhat old, but still kicking)

The WAMP issue sounds like CRON was not configured properly on a low traffic development site.  All of your scheduled tasks were likely backing up and running only when you loaded your site manually.

As for DAMP, do all php pages never complete or only Drupal?  Also, do static pages complete or time out?


Stuck with Drush on OS X with AMPPS and Homebrew I am setting up a new development environment on a local machine and am using AMPPS. I have installed Drush using Homebrew and am running a Mac (OS X 10.12.5 Sierra).

I have successfully installed a fresh Drupal site in my development environment. When I attempt to run a drush command, I get the Drush status along with the classic bootstrap/jailed shell message:

Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal[error]
environment to run this command.
The drush command 'pm-list' could not be executed.                                                                 [error]
Drush was not able to start (bootstrap) the Drupal database.                                                       [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select
another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a
jailed shell. See http://drupal.org/node/1428638 for details.

Here is the output of drush status:

Drush was attempting to connect to:
 Drupal version         :  7.54
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  myuser
 Database name          :  drupal
 PHP executable         :  /Applications/AMPPS/php-5.6/bin/php
 PHP configuration      :  /Applications/AMPPS/php-5.6/etc/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/Cellar/drush/8.1.15/libexec/drush.php
 Drush version          :  8.1.15
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/AMPPS/www/drupal/docroot
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

Please note:

I have tried changing localhost to 127.0.0.1 in sites/default/settings.php and restarting the server
I added the path to drush to php via export DRUSH_PHP=/Applications/AMPPS/php-5.6/bin/php
I am executing the command within the docroot of the drupal installation
I do not have a ~/.my.cnf file
symlink in /usr/local/bin for PHP goes to Homebrew's instead of AMPPS's but it's for version 7.1.10 and I'm using PHP 5.6

There are a lot of posts on this with slightly different details or environments and I'm having no luck deriving a solution from those so I thought I would post my issue with the specific scenario.

I mostly used these instructions:
https://www.drupal.org/node/954766

Even though I did export the Drush PHP path, I had not added the link to AMPPS' mysql bin in .bash_profile. That solved my issue.

nano ~/.bash_profile
export PATH=$PATH:/Applications/AMPPS/mysql/bin
source ~/.bash_profile


Speed up drupal 6 solr indexing We have 90,000 nodes and it and we run cron every 10 minutes and do 200 documents per cron run. At this rate it will take just over 3 days to index all the content. It is also indexing older content first.

Is there a way to index newer content first
Is there a way to index more than 200 per cron run?

You can change the settings at admin/settings/apachesolr.

If your server has enough capacity, I'd run the cron more often and increase the limit.

Check also this thread and be sure to disable core search indexing.

Not sure though about indexing newer nodes first.


Jump Menu Style Dropdown To External Links I'm attempting to create a jump menu of links to external websites, and I would like to be able to order the links within this menu differently depending on the organic group of the current user attempting to access it. So far I've tried to accomplish this using views with nodequeue, and have come somewhat close, but its beginning to feel like a dead end..
 Does any module(or combination of modules exist) which would allow me to accomplish this without having to write my own?
Ideally each will be able to reorder the links according to their personal preference and override the default ordering of links. but that is not essential at this point

you could create a node type link and a Views jump menu that loads said node types.


Which of the two approaches to routing a module settings page is the best practice? There seems to be two ways to link a route to a settings form for a module. I'm curious as to whether one is considered a better practice, and why.

_controller: '\Drupal\mymodule\Controller\MyController::myMethod'

or

_form: '\Drupal\mymodule\Form\mySettingsFormFile

Without knowing what is in the controller this would be the second one. The extra custom controller class only makes sense if you do something in myMethod() the form controller invoked by _form is not able to do.

See https://www.drupal.org/node/2117411#fapi-in-route

This integrates the form in a request so that it can receive route parameters and the request itself as well as returning a response if necessary.


Drush stuck in "Killed" loop I recently installed Drush 8.1.2 from the tarball distribution available on Github and composer install-ed it (this is after trying to use the .phar to very similar ends).

Oddly, whenever I try to run drush from my shell (with or without subcommands), I get no output for a while, then drush just keeps printing Killed over and over, every few seconds.

Running ps aux | grep drush reveals dozens of spawned drush processes; simply sending an interrupt via ^C doesn't make the Killed stop. Because the processes spawn about as quickly as I can kill them, don't respond to killall, and cause surprisingly large amounts of when inputting commands, I have to reboot the system to kill the processes.

The same thing happens with the .phar version. This is not an issue with drush available via apt, but that's drush 5, which is horribly outdated. The same thing happens with drush-8.1.1, the previous release. This also occurs when installing globally via:

$ composer global require drush/drush:dev-master

According to my host's monitoring tools, this also sends my CPU usage skyrocketing up to about 70% until reboot, as well.

I'm on an otherwise brand-new Ubuntu 16.04 VM, with Drupal 8 installed.

Update: I've now tried the snippet at drush.org (below) on my laptop (running OS X 10.11, 8GB RAM) as well as on a much larger cloud instance with similar CPU and RAM specs, running Ubuntu. The out-of-memory error persists on this new box, but the installation succeeds without issues and produces a working drush on my laptop.

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

I suspect that drush requiring more than 8GB of RAM for normal operation isn't expected behaviour; it's probably pointless to spawn boxes with higher-performance CPU and RAM configurations at this point.

Notes:

I've allowed PHP to allocate 384M of RAM in my php.ini -- the process still respawns and prints Killed, all while making my system lag intensely.
as much as I'd like to bring out strace, the lag on my system is a major impediment. Keystrokes take a second or two to register as long as the processes are spawning.
This particular box has PHP 5.6, but the issue is also present on a box running PHP 7.0.

I haven't found a solution to the "Killed" loop issue (even after scaling up to the largest instance offered by my host, which has 64GB of RAM), but I've managed to get drush itself to work by pulling the .phar from Github and making it executable.

Using the install script still doesn't work (still leads to the Killed loop) despite making sure that everything that should be executable is executable, and installing from the tarballs or via composer likewise fails in a similar way.


Problem with image file names containing utf-8 characters I have a problem image file names containing utf-8 characters in my drupal website.
When drupal has to display a thumbnail (image style) that contains utf-8 characters on it's image file, it fails. All other images/image file names, work ok.

For example there's this image:

http://example.com/sites/default/files/styles/thumbnail/public/%CE%B8%CF%81%CE%B7%CF%83%CE%BA%CE%B5%CF%85%CF%84%CE%B9%CE%BA%CF%8C%CF%82%20_%CE%B3%CE%AC%CE%BC%CE%BF%CF%82.jpg

The actual image file really exists in default/files/styles/thumbnail/public/ directory, but it cannot be displayed in website.

Visiting the above image url, I can see the following message:

Error generating image.

but I should be able to see the actual image, because it exists on server directory, I can download it using FTP, and it's a normal thumbnail image file.

Why is this happening and what can I do to fix it?

UPDATE-----

htaccess.txt

sample image

Use https://www.drupal.org/project/transliteration to automatically rename the files and avoiding problems like this. No need to train your editors. :-)


FlexSlider, Media Galleries, & Nodes (entity reference) If this has been asked before I apologize.

I'm somewhat new to Drupal but I know enough to dig myself a hole trying to find a solution to an idea.

I would like to use entity reference to display a media gallery and have the gallery formatted as a FlexSlider with thumbnail navigation.

I have tried both Flexslider Fields and FlexSlider Entity Reference but I can't seem to get either to work properly with Media Galleries.

Any suggestions?

I need it to be a simple interface a non-tech content creator can use without issue.

I can recommend the ”Entity Reference Views Formatter" module.

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

You then have full flexibility of views to output your Entity reference fields!

Here is a good thread on how to use the Entity reference views formatter module, setting up the correct Relationship and Argument can be a bit tricky.
https://www.drupal.org/node/1889358


How to change the format of Last seen: in author pane in advanced forum? I have installed Advanced forum and Author pane module. Now, I did found the option of date format for Joined:__________, But not able to find the date format for Last Seen:________, The Last seen option shown very granular details like, Last Seen: 1 min 20 sec ago, I just want like,

Last Seen: 1 min ago

Last Seen: 2 hr ago

Last Seen: 1 day ago

Last Seen: dd/mm/yyyy

Here's what you need to use:

function YOUR_THEME_preprocess_author_pane(&$variables) {
  // Get the number of seconds since last login.
  $time_since_last_login = REQUEST_TIME - $variables['account']->access;
  // Custom override of the "last_active" variable.
  //
  // This is just an example; add your rules here.
  if ($time_since_last_login < 120 * 60) {
    // Show 2hr ago for any interval within last 2 hours.
    $variables['last_active'] = t('2 hours ago');
  }
  else {
    $variables['last_active'] = format_date('short', $variables['account']->access);
  }
}

Just add your custom time formatting rules.


When an image shows up in "page not found" in Watchdog, how to find the content containing the image link? I disabled the countryicons_shiny module on my site, and now I'm getting some errors in Watchdog showing that the images weren't found:

Details
Type    page not found
Date    April 3, 2016
User    Anonymous
Location    https://www.example.com/sites/all/modules/contrib/countryicons_shiny/images/tw.png
Referrer
Message sites/all/modules/contrib/countryicons_shiny/images/tw.png
Severity    warning
Hostname    1.1.1.1
Operations

I'm pretty sure this is a misconfigured view, but I have a ton of views and content types on my site, so I was hoping to find a way to identify the content (view, page, etc.) that is trying to display the icon.

I have all my views in features and I tried using grep countryicons * but no results are returned.

How can I find what content is linking to the image when I only have the watchdog log "page not found entry?

This is not the ultimate solution, but in this specific case, since I moved the icons into another module, to fix this particular error I just symlinked the folders:

mkdir countryicons_shiny
cd countryicons_shiny
ln -s ../mycustommodule/countryiconsdirectory images


Strange behavior with title field I have a strange behavior (or at least this is what I think) I have two form elements. Both are required, in the first (First Name) I want to have a required field so I use '#required' => TRUE and '#required' => TRUE in the second I don't use this properties to says that the field is required, I just add this line to the title '*'. The problem is that the output of the first element is "First name " (with space at the end) and in the second element the output is "Last name" (without space at the end). See the code and the picture with the output code.

Is this a normal behavior or I missing something here?

  $form['general']['group-1']['prenom'] = array(
    '#prefix' => '
',
    '#title' => t('First name'),
    '#id' => 'cf-1',
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' => array('required' => 'required'),
    '#suffix' => '
',
  );

  $form['general']['group-1']['nom'] = array(
    '#prefix' => '
',
    '#title' => t('Last name') . '*',
    '#id' => 'cf-2',
    '#type' => 'textfield',
    '#suffix' => '
',
  );

The HTML code:

Works as designed imho.

The markup of the first is generated by the form element/Drupal. By default Drupal has a space between the field title and the asterisk. That's just how it was designed.

The second time you tell the form what to add - exactly what to add. Drupal wont add a space for you, as you may not always want a space between your custom wrapper and the title. (In most cases you probably don't.)

If it is important to remove the space you can overwrite theme_form_element() in your theme. Check the mid to late replies (starting with kkatusic) in this thread: How to remove asterisks from required fields?

Is there a reason why you would want to mark a field required if it isn't a required field?


Sum of Columns for View I have a view with the following results:

           penalty    attorney_fees   other
client1    100,000    100,000         0

client2    50,000     75,000          10,000

client3    25,000     50,000          25,000

           total?     total?          total?

How do I get the sum of the column "total" for penalty, attorney_fees, and other?

You can use the Views Calc module for that. Here is an excerpt about it from the module's project page:

... adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).


Mini Calendar As Views Exposed Filter I would like to have a calendar be displayed as a filter for a view. When a user clicks on a date on the calendar the views result on this page are updated (preferably via Ajax) to show the chosen dates event. Such as the design below. The calendar should not be a popup calendar.

I am aware of the date popup calendar in views exposed filter options but that only displays the calendar as a popup calendar as expected.

I have tried to look into the calendar module as well, however the default behavior of the mini calendar block does not fit my needs as when the user clicks on a date on the mini calendar it will redirect the user to that specific dates calendar page instead of updating the views listing.

Any suggestions or direction on how to implement such a feature would be greatly appreciated!

You can achieve this with calendar module and Date API. The default mini calendar is redirecting to a new page, but you can override it in your template file. I would suggest to use ajax link api module to load your content in a div you would like. You can do something like the following

/**
 * Alters link url in calendar events block in order to filter events at /events
 *
 * @see template_preprocess_calendar_datebox()
 */
function <themeName>_preprocess_calendar_datebox(&$vars) {
  $date = $vars['date'];
  $view = $vars['view'];
  $day_path = calendar_granularity_path($view, 'day');

 //$vars['url'] = 'exhibitions/calendar/' . $date;
  $vars['link'] = !empty($day_path) ? l_ajax($vars['day'], $vars['url'], '#block-system-main') : $vars['day'];
}

l_ajax function is used to load contents via ajax. Let me know if you need any help.


Devel query log not showing module enabling queries? I enabled "display query log" in Devel. However, I've noticed not all queries are logged, for instance when enabling/disabling a module there is no "update system set status = 1.." query shown. Why is that? Thanks.

I found the answer: enable/disable module calls are ajax requests and the devel display query log doesn't show queries from the ajax request.

BTW, if you want to use hook_exit() you will notice it is not fired for ajax calls that use exit() and not drupal_exit(). However, if you need something to be run at runtime end, you can use PHP register_shutdown_function() in your module (in your hook_init() for instance).


Ordering archive block I've upgraded an installation from Drupal 5 to Drupal 6, and now I can't get the archive to be displayed in the right order. I've set the sort criteria of the block to be descending and in the preview I can see it correctly: on top I get the last entry, followed by the one after that, etc. The block displayed in the left-hand column never changes, even after cleaning the cache. I know this is the right block because if I remove it, the archive view on the left column will go away too.

Do you have any suggestions?

It must have been some sort of caching issue, because the link above just worked.


How can I findout where a custom variable is being created? In a current Drupal 7 install i realize that all our CSS files are being declared in html.tpl.php using a variable $styles instead of through the templates .info file. I tried using Xdebug but all i managed to get is the info the variable holds. The same is also being done to javascript files which should really be at the footer instead of the header.

I have checked my themes template.php but i have not found a declaration of it anywhere.

$styles is set in the $variables array during template_process_html. It is a result of calling drupal_get_css, and you can add to, remove, or change the order of this array by implementing drupal_add_css, adding a css file to your theme info file, or using hook_css_alter. The reason you do not see it in your theme's template.php is because it is a higher level function that Drupal does, the page is assembled using a majority of the application, core and contrib modules informing or responding to requests.

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_get_css/7.x

As you can see, drupal_get_css allows for altering, which is where you would implement hook_css_alter to adjust anything in the array of CSS files before they are added to the page.

See: hook_css_alter

The same applies for the $scripts variable. You can add javascript with drupal_add_js, library hooks, or by adding it to your theme info file.

For example, if you want to change every JS file in drupal to load in the footer, instead of the head, you can do this with hook_js_alter:

/**
 * Implements hook_js_alter().
 * @param $items
 */
function mytheme_js_alter(&$items) {
  foreach ($items as $key => $script) {
    $items[$key]['scope'] = 'footer';
  }
}

Lets say on certain node types, you also want to remove scripts from loading to the page because they are not necessary for the page to function:

/**
 * Implements hook_js_alter().
 * @param $items
 */
function mytheme_js_alter(&$items) {
  foreach ($items as $key => $script) {
    $items[$key]['scope'] = 'footer';
  }

  if ($node = menu_get_object('node')) {
    if ($node->type == 'campaign') {
      // unset all the JS we won't need to reduce page weight
      unset($items['sites/all/themes/mytheme/js/jquery.waypoints.min.js']);
      unset($items['sites/all/themes/mytheme/js/jquery.fitvids.js']);
      unset($items['sites/all/themes/mytheme/js/isotope.min.js']);
      unset($items['sites/all/themes/mytheme/js/imagesloaded.min.js']);
      unset($items['sites/all/libraries/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js']);
      unset($items['sites/all/modules/contrib/wysiwyg_codesnippet/wysiwyg_codesnippet.js']);
      unset($items['sites/all/modules/contrib/addthis/addthis.js']);
      unset($items['http://s7.addthis.com/js/300/addthis_widget.js']);
    }

    // we only need addthis to load on an article
    if ($node->type != 'article') {
      unset($items['sites/all/modules/contrib/addthis/addthis.js']);
      unset($items['http://s7.addthis.com/js/300/addthis_widget.js']);
    }
  }
}

See hook_js_alter


Block not showing on a matching path (menu item duplicate) I have a strange situation and would like to verify it with you.

I have a menu block of main manu level 2+ links.

Corporate     [<--block title, level 1 of Main Menu]
  About Us    [corporate/about-us]
  Services    [corporate/services]
  Contact Us  [corporate/contact-us]

It is configured to appear only for pages with addresses matching the pattern corporate/*. So far so good. But in order to better communicate the Contact Us page, I created manually a duplicate of the Contact Us (with the same [corporate/contact-us] alias) at level 1 of the Main Menu. Once that duplicate is there, the block disappears from the Contact Us page.

Is there a Drupal culprit I bumped into? Is there a workaround for this?

Perhaps on the Contact Us page, the block is trying to display child menu entries for the new level 1 "Contact Us" item, and there are none? The block won't get rendered if there's no content.


How to open modal form on page load I'm using modal form in drupal7.26 with WEBFORM module and is working fine when I click  a link the form opens in new modal.

What I want is to open the same WEBFORM with out clicking any link instead it should be open on page/body load event.

I'm using modal form with CTOOLS and WEBFORM modules.

Any help would be appreciated.

Cheers
-Zafar

I'm not sure why you would want to automatically load a modal when the page is loaded, IMO that's a bad user experience. But if you must, you can use a bit of jQuery in the theme to make it happen. Maybe something like the following:

  /**
   * Open Modal window on page load.
   */
   Drupal.behaviors.openModalOnPageLoad = {
    attach: function(context, settings) {
      // Just create some kind of ID or class for the modal link, add whatever extra
      // classes you need to be more specific if necessary.
      $(".page-node-number #myModalLink").click();
    }
  };


Email without body being sent to newly added users In "admin>config>people>account-settings" for "Who can register accounts?" settings I have selected:

Visitors, but administrator approval is required.
Require e-mail verification when a visitor creates an account.

I have even enabled notifications for sending emails to newly added users from the options available at the bottom of the same page and I am using the default subject and body for the mail.

I have got an very unusual problem that my newly added user receives a mail from my site without any body. Though the subject of the mail is same but the body of the mail doesn't shows up; all I can see in email's body are just three dots (...). Please help.

Do you have any module that alters mail before being sent? If so, can you check if they are causing the problem.

Can you check for other mails as well, sent by Drupal. Do they generate the same issue?

Apart from that, please check the mail headers once, that might give you some hint.

If you get anything, Post it here, I will be happy to help ....


How to add programmatically region's class when region had block in D8? I have one row three column region. How can I add custom class on each region when one of region is not work?

When three regiosn work, classes will be below

|------------|-------------|--------------|
|            |             |              |
|  region 1  |   region 2  |    region 3  |
|            |             |              |
|------------|-------------|--------------|
  col-sm-4      col-sm-4       col-sm-4

When two regions work, classes will be below

|-------------------|---------------------|
|                   |                     |
|  region 1         |     region 2        |
|                   |                     |
|-------------------|---------------------|
      col-sm-6             col-sm6

When only one region work, class will be below

|-----------------------------------------|
|                                         |
|               region 1                  |
|                                         |
|-----------------------------------------|
               col-sm-12

I use in page.html.twig like below. It worked for me but not good code for more column.

{% if page.region_1 and page.region_2 %}

 {{ page.region_1 }}

 {{ page.region_2 }}

{% endif %}

{% if not page.region_1 and page.region_2 %}

 {{ page.region_2 }}

{% endif %}

{% if not page.region_2 and page.region_1 %}

 {{ page.region_1 }}

{% endif %}

I'm try using hook_preprocess_region() like below. Can I check regions condition in hook_preprocess_region?

function MYTHEME_preprocess_region(&$variables) {

  // Add class in header region.
  $region = $variables['elements']['#region'];
  $region_header = array(
    'region_1',
    'region_2',
    'region_3'
  );

  if (in_array($region, $region_header)) {
    $variables['attributes']['class'][] = 'col-sm-12';
  }

}

Check Block Class module for this

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!


How can I import a local database remotely without having a local database copy? I am working on database security and with using Drupal we have daily backups from a cloud server which we access remotely. What I normally do is grab a daily DB copy from the cloud server, move the file over unto my local machine, and create a local copy that I can freely work on (to mess up or fix) how I choose.

However as the company grows and more people start to work on this project, having every individual have a local copy of a DB on their machine when it contains proprietary data is a huge security risk.

Is there a way for me to import a local copy of the DB to use, without actually having a physical copy on my machine? Or would this be inevitable?

Edit: For whoever down voted this, can you at least list why so I could fix it? I am trying to get genuine answers. Not have this post deleted because you think it didn't fit the right format.

Well, there are two things that can be done with this.

1) Database sanitisation

You can write custom Drush sql-sanitize scripts that will sanitize the database, for example changing all usernames and passwords, as well as any other custom alterations required.

Drush SQL Sanitize scripts can be set up as webhooks, to ensure the sanitization happens automatically.

2) With D8, you mostly shouldn't need to give anyone the database at all. Functionality is migrated through configuration and the configuration API. Developers can work on code, then export their configuration, and push both the code changes as well as the exported configuration to the remote server. The configuration is then imported into the remote environment's active configuration in the database, providing the new functionality on the remote server.

I wrote a blog series on the Configuration API to help understand it better: https://www.morpht.com/blog/drupal-8-configuration-part-1-configuration-api


Display a field 'Category' on the home page How do I display a field 'category' (so as 'tags') in the node.tpl.php?

Every field that is associated to a node is shown in the node view page, if the field is not set to be hidden.
You don't need to change the template file used for nodes, as it shows all the node fields by default. If you are not seeing a field is probably because that field settings are set to not show that field.

As you are referring to the home page (a.k.a. the front page), which normally shows the teaser of nodes promoted to front page, check the field settings for the teaser view mode.


What does "Use aggregation" option under Other in the Views UI do? It looks like it might be a function that can reduce duplicates rather than using the Distinct option.

Technical what it does it allows you to add "GROUP BY field" and "count(field)" to the sql query. This might be able to reduce duplicates but in general if you have duplicates it's most often a problem by design/your choosen view type(node, user, terms etc.)


How to include a field's suffix when using its Token? My user accounts have an integer field Visits with the suffix visit|visits. It is very handy to let Drupal automatically decide which suffix is appropriate. I would now like to use this field in a status message with the simple Rules action Show a message on the site. Unfortunately, when I set the message to You currently have [site:current-user:field-visits]., the suffix is not included, only the integer appears.

Is there a way to solve this? I would like to prevent a cumbersome Rule with an extra check on the value of Visits and an according adaptation of the message.

AFAIK, field metadata isn't available in tokens. However, Rules to the rescue!

Create a rule set component which takes the field value as an integer parameter and two additional string parameters and provides a string value in return.
In your rule set, add a rule which checks to see if the value is one. If it is, set the provided string value with the integer value and the first string parameter.
Then, add another rule which does the same thing if the value is > 1.
Now you have a string which is pluralized!

Here is an export:

{ "rules_pluralize" : {
    "LABEL" : "Pluralize",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "integer" : { "label" : "Integer", "type" : "integer" },
      "string_one" : { "label" : "One", "type" : "text" },
      "string_many" : { "label" : "Many", "type" : "text" },
      "pluralized_version" : { "label" : "Pluralized version", "type" : "text", "parameter" : false }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [ { "data_is" : { "data" : [ "integer" ], "value" : "1" } } ],
          "DO" : [
            { "data_set" : {
                "data" : [ "pluralized-version" ],
                "value" : "[integer:value] [string-one:value]"
              }
            }
          ],
          "LABEL" : "Set string for one item."
        }
      },
      { "RULE" : {
          "IF" : [
            { "data_is" : { "data" : [ "integer" ], "op" : "\u003E", "value" : "1" } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "pluralized-version" ],
                "value" : "[integer:value] [string-many:value]"
              }
            }
          ],
          "LABEL" : "Set string for multiple items."
        }
      }
    ],
    "PROVIDES VARIABLES" : [ "pluralized_version" ]
  }
}


How to change field value of a node I have a field in a node where users entered data in an inconsistent format.  I need to parse that data (it's HTML) and re-format it so it looks correct.  Where is the best place to do this?

1) Use EntityFieldQuery to load a list of entity ID's.

2) Load the full entity using entity_load.

3) Optionally wrap the entity using entity_metadata_wrapper.

4) For each entity, manipulate the field to your desire then save the entity. If you have it in a wrapper use $entity_wrapper_object->save() or if using the entity it's entity_save.

If you want to do this quickly and easily, install the devel module and use the PHP execute page @ example.com/devel/php. Go through each step and ensure you have the correct data to work with at each stage.

Optionally you could use something like VBO to create a view and manipulate the data using a PHP field. This might be easier depending on your experience level.

How to use EFQ


How do I make a link to a flagging edit page? I'm using Drupal 8 with Flag 4.0-beta1.
On my flag, I have several fields. I want users to be able to edit these fields after making the flag.
How can I make a link to edit the flagging?
I tried various things in Views (making a view of flaggings; making a view of nodes with flaggings as a relationship), but I can't find a way to get an edit link to the flagging (to edit the fields on the flag itself).
NOTE: This question is about flaggings (an instance of a flag).  Here's the same question about flags.

Digging into the flag module a little, I can see this entry in flag.routing.yml that appears to be for your Flagging edit screen.
flag.field_entry.edit:
  path: '/flag/details/edit/{flag}/{entity_id}'
  defaults:
    _controller: '\Drupal\flag\Controller\FieldEntryFormController::edit'
    _title_callback: '\Drupal\flag\Controller\FieldEntryFormController::editTitle'
  requirements:
    _flag_access: 'entity:flag{flag}'

You can build out the link to the flagging manually, e.g.
Edit My Flagging

Or if you're working with twig, e.g. rewriting a view's field, make sure you're also including the flag's id and flagging's id in the view then rewrite doing something like:
{{ "Edit Flagging"|t }}

Or you can use PHP to build the url directly from the route. It's recommended to use one of the following methods if you're working in PHP.
To get just the url text or object in PHP, use Url::fromRoute():
use \Drupal\Core\Url;

$my_flagging_url_object = Url::fromRoute('flag.field_entry.edit', [
  'flag' => FLAG_ID,
  'entity_id' => FLAGGING_ID,
]);
// $my_flagging_url_string returns something like "/flag/details/edit/123/1234"
$my_flagging_url_string = $my_flagging_url_object->toString();

To build the whole link in PHP, use Link::createFromRoute():
use \Drupal\core\Link;

$my_flagging_edit_link = Link::createFromRoute('MY FLAGGING EDIT TEXT', 'flag.field_entry.edit', [
  'flag' => FLAG_ID,
  'entity_id' => FLAGGING_ID,
]);


Bootstrap Accordion Adapting I'm adapting my bootstrap html theme to Drupal 7 and want to use some of the features of Bootstrap 3 theme.

In Bootstrap theme, there is a code for accordion menu like this:

/**
 * Implements theme_bootstrap_bare().
 */
function bootstrap_bootstrap_accordion($variables) {
  $elements = $variables['elements'];

  if (empty($variables['id'])) {
    $accordion_id = 'accordion-' . md5($elements);
  }
  else {
    $accordion_id = check_plain($variables['id']);
  }
  $output = '
';
  foreach ($elements as $id => $item) {
    $output .= '

';
    $output .= '' . check_plain($item['header']) . '
';
    $output .= '

';
    $output .= render($item['content']);
    $output .= '

';
  }
  $output .= '
';
  return $output;
}

My problem is, how can i use this code in my theme for all menus in sidebar region?

Download Views Bootstrap and create a view for the menu you want to display as accordion. For your view format choose Bootstrap Accordion


Associate multiple Profile2 profiles with vocabulary and expose the vocabulary's terms in a views' filter I have 2 profiles that have two different taxonomy term fields that point to the same vocabulary (the reason that I created 2 different fields instead of one is that I want the users that handle the two profiles to be able to select different amount of vocabulary terms). If I try to create an exposed filter (select list) in views 3 I can only create 2 different exposed filters: one for profileA and one for profileB. I want to be able to merge them into one.

The "Global Combine Fields" option does not work since I want to expose a select list and not an input field. All the relationships that I tried to create are specific to one field or another (and not to the targeting vocabulary for example).

My question is: can I create an exposed filter based on the vocabulary (instead of the fields) that will filter the profiles based on whether the specific term(s) that were selected are in either the profileA's field and profileB's field?

I would like to know whether this is possible directly in views 3 with a method that I'm missing or if I could create a custom exposed filter programmatically. If the answer is the latter, I would really appreciate if you could point me to an article that shows how you can create such an exposed filter (or a similar) since I do not have any experience at all in the specific field.

This probably doesn't answer your specific question, but this poses an alternate solution.

If you created two fields to allow the user to select a different number of terms, you could potentially do this with one field and a form_alter hook or validation.

The idea is that the form alter would change the number of allowed values based on some custom logic. Ideally this would make downstream functionality like views simpler because you're dealing with a single field.

The answer on this question may help give you ideas.
How do I set the fixed amount of values to 11?


Use multifield values to create new nodes I have a multifield field_staff_required of unlimited cardinality containing two subfields: field_staff_category and field_staff_quantity.

Example: I have an event node containing the staff_required multifield to which I add the following values:

Category: Manager / Qty: 1

Category: Steward / Qty: 5

Category: Security / Qty: 3

On saving the node I would like it to automatically generate new 'staff booking' nodes for each of the staff required. The staff booking node will contain a 'Staff_category' field which would be auto populated with the category from the multifield, and an entity reference field to refer each staff booking node back to the event node.

So the result in the example above is that I end up with 9 new nodes created, one with category set to Manager, five set to Steward, and three set to Security, all referring back to the event node.

Can the above be achieved using Rules? The multifield subfields don't seem to be accessible to Rules. I assume it will be necessary to write a custom module to achieve this. Any suggestions gratefully received!

I managed to solve this by swapping the Multifield for a Double Field which does play nicely with Rules.

I was then able to use Rules Action: generate a list from an integer to loop through the quantity for each category and create a new node for each, populating the required fields.

The only downside is that Double Field does not allow to populate a select list from a taxonomy vocabulary, and I could not get the Field Remove Item or Multiple Fields Remove Button modules to work with it.


"[warning] Invalid argument supplied for foreach() Migration.php:641" Why does this error appear when I use the drush ms command?

[warning] Invalid argument supplied for foreach() Migration.php:641

Usually this comes from having incorrectly coded a hard value in your migration yml script. As noted in the following example:
process:
  type:
    plugin: default_value
    default_value: 'profile'
  status: 1
  uid:
    -
      plugin: skip_on_value
      source: user_id
      method: row
      value: 1
    -
      plugin: migration_lookup
      no_stub: true
      migration: tabs_users
      source: user_id

  is_default: '1'
  created: created
  changed: user_lastvisit

Here I show a few different approaches, but one is wrong. Specifically, the status: line is trying to set a value of 1 but the migrate module is assuming it is a variable and since it is not set previously in the source section of the yml script, drupal is barfing. To fix this, do what is done in either the type line OR the is_default line; explicitly set the value via the default_value plugin OR encapsulate your value in quotes. This is identified in the documentation but can be easily overlooked when quickly coding up a solution.


Actions - What are objects and context Can somebody explain to me what the difference is between an object and context within the advanced action setup please.

I understand what an object is but am failing to understand what context is.

Thanks.

If you are talking about the $context variable (and I think you do), then the official description is: an associative array containing extra information about what triggered the action call, with $context['hook'] giving the name of the hook that resulted in this call to actions_do() (from here:  http://api.drupal.org/api/drupal/includes!actions.inc/function/actions_do/7)

But if you want to understand it better, this page is very useful: http://www.sysarchitects.com/node/47


Alter field inside fieldset I have created form using Drupal 8 Webform.I have created fieldset and fields.But i couldn't add or alter fields inside fieldset using hook_form_alter.I can add fields outside of fieldset using form alter.How can i alter fields inside fieldset?

Finally i got the answer. In order to alter Drupal 8 webform we can use code like this

$form['elements']['field_name']['#title'] = t('Your Name');

I think same method can follow to alter other field attribute.


wysiwyg upload image as background I learn how to upload images by using IMCE Wysiwyg bridge module.

How about upload images and treat it as background picture?

the module ImageCache Actions suit your need. one of the effects that it provide is :

  Watermarking - a much requested addition that enables you to place any
  image anywhere over a source picture, with alpha transparency


How to access Field-settings in the widget formatter I am writing a cck-widget/field and formatter. My field-settings contains a "base_url" setting. If I draw that out:

http://example.com/ [_some/path/to/a/file.avi________]

http://example.com is the base_url. some/path/to/a/file.avi is what user provides and gets stored in database.

The formatter should append that base_url to the user-supplied values:

function theme_video_url_formatter_embed($element) {
   return "$element['base_url']/$element['#item']['safe']";
}

How can I pass the variable from field-setting $base_url along, so it ends up in that formatter-theme-function?

You can take number.module from the CCK package as an example; it allows prefix and suffix values in the field settings that are rendered in the formatter.

In theme_number_formatter_generic() the field settings are retrieved using $field = content_fields($element['#field_name'], $element['#type_name']);. The values are then taken from the $field array, sanitized and added to the output.


Disable menu cache for hook_menu() implementation There is a way to disable the menu cache ?

Context

Drupal 7

I have a custom module that implements hook_menu(). The link is showing up only if a view have results. It's working.

The problem is that I have to clear the drupal cache each time the view changes the number of results because the condition is not triggered anymore.

function gal_custom_menu() {

  $items['exhibitions'] = array(
    'title' => t('Current exhibition'),
    'page callback' => 'gal_exhibition_callback',
    'access arguments' => array('access content'),
  );

  return $items;
}

function gal_exhibition_callback() {

  $x = views_get_view_result('exhibition', 'page');

  if(count($x)) {
  $path = drupal_get_path_alias('node/' . $x[0]->nid);
  drupal_goto($path);
  } else {
  return FALSE;
  }

}

Do you have any idea how can I disable the menu cache ? Or is it the Views cache ?

Thanks

Good conversation about other things in this code sample, but to make a page loaded through a menu callback skip cache, you can try drupal_page_is_cacheable(FALSE). See: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_page_is_cacheable/7.x


Can't get the authenticated user cookie session to be used when creating a new node via Services 3 endpoint My application is sending this header to Service 3 endpoint when creating a new node:

{
  'Cookie': 'SESS255f42d9a87a0df5bf8959d25909fe8c=St8o29NI9Hx84kPo8NuZbpdHWuRgNSS9qy9cQ-QM4rA; expires=Sun, 15-Jun-2014 00:39:27 GMT; path=/; domain=.mydomain.local; HttpOnly',
  'Content-type': 'application/json'
}

Nonetheless, the newly created node user is set to anonymous.

Is there anything wrong with the header I am sending?

Solved it.

I should've had checked Session authentication at admin/structure/services/list/MYENDPOINT/edit


Media Title appearing in View when HTML is stripped I've run into an issue with media in a view. I have a view using bootstrap grid to display body field content. The view field content being displayed is setup to strip out HTML, but the word "Image" is inserted where a media entity was. Not sure if the word "Image" is a leftover from media or the entity embed module.

example:

Any ideas on how to get rid of this unnecessary word?

This ended up being a media field label and not the media type name, like I originally thought it to be.

This was happening due to the media label being set to "Visually Hidden" instead of "Hidden"

This setting can be found at
Administration > Structure > Media types > [your media type] > Manage Display

Now that it's set to "Hidden" it no longer shows in the label in the view or the WYSIWYG


View Taxonomy Term List with Exposed Has taxonomy terms (with depth) filter I have view list of terms of a vocabulary. The terms of it have an entity reference field of another vocabulary (with hierarchically organized terms).
I would like to filter the terms by that entity reference like I am used to do with nodes with a "Has taxonomy terms (with depth)" filter.
Does a depth filter really only work with nodes?
Kind regards and thank you for your support.

There is a issue as you ask the question.
The current answer is that Drupal 8 does not yet support this feature besides node content type.
I'm also following this issue.
more details at:
https://www.drupal.org/project/drupal/issues/2915933
https://www.drupal.org/project/drupal/issues/1040786


Using Commerce Feeds module, commerce file names are being changed when importing I have an e-commerce site that sells albums. This product variation type of album has a field of type commerce file. It’s configured to have multiple files (mp3’s) attached, or bundled to it. I’m using the Feeds & Commerce Feeds module. Feeds uses csv files to create these products.

The Feeds importer works but the file names are being changed. It’s appending a ‘_0’ to the file name.

for example:
songname.mp3 -> songname_0.mp3 (see attached)

I’ve tried numerous different settings within the file sources option of the product variation type. I’ve checked and unchecked ‘File attach from server directory’ option

note - I have File Field Path module installed because the dirs. need to be different (dynamic) for each product. For example:

private://artists/artist_name/album_name/song_name.mp3

Utlimately what I want to do is create the dirs. and add the files to server myself and then have the Feeds importer simply reference files that are already there. I don’t want to copy or upload.

Any insight or help would be hugely appreciated!

Go to structure/feeds importer
Select yourproductimporter - go to mapping/.
Go to Files:URI (commerce_file:uri)
Click on the button below text "Rename if file exists."
Change to "Replace" and save the importer.  That worked for me.

That will eliminate the _0 or _1.mp3 and keep the same file name as your database.


Lingotek Translation showing interim status for every translation I am working with lingotek module in Drupal 8 and I am following all the procedures but still facing some issues on local setup.
The automatic translation is taking place and it is displaying interim status every time after the translation is done, which is a state where incomplete translations can be published.

So, the translation part is not fully completed. I have followed the steps on fresh installation but still getting nowhere.

That happens when the translation is not complete.
This could happen because you have a pending review phase in your workflow.
What happens if you use the "Check target status" operation?

PS: As @user73757 said, it's easier to get support in the Lingotek module issue queue.


EFQ propertyCondition Doesn't work in Simpletest This Entity Field Query works as expected outside of simpletest:

$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_exhibition_window_start', 'value', $date, '<=')
  ->fieldCondition('field_exhibition_window_end', 'value', $date, '>=')
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->propertyCondition('status', '0');

Inside of a simpletest, after the creation of an unpublished node within specified parameters, it unexpectedly returns zero results.

However, if I comment out this line:

  ->propertyCondition('status', '0');

(and put a semicolon on the line above) then the query works as expected and returns a node ID. I've even done a node_load() on the node ID returned and inspected the node to be sure that it is, in fact, at that exact moment in time, unpublished.

My simpletest has a user with node access bypass permissions, and I'm using DANGEROUS_ACCESS_CHECK_OPT_OUT, so it doesn't seem like a permissions issue.

Does Simpletest do something weird with EFQs? Why isn't it finding my unpublished node?

It turns out that the status of my node was, in fact, being set to '1' immediately prior to this query running, but that despite the fact that the node_save() that was called immediately after node_publish_action() should have cleared the cache, node_load() was in fact calling a cached version of the node.

I got around this by adding the TRUE parameter to node_load().

NOTE: You can't skip the middle parameter, á la node_load($nid, TRUE). This is annoying, because it will fail silently and it will just return a boolean FALSE. To get a node without caching, and also without specifying a VID, you must use node_load($nid, NULL, TRUE).

In a simpletest, you can also use a TRUE parameter like so:  drupalWebTestCase::drupalGetNodeByTitle($nid, TRUE).


Migrating from Postgresql 9.1 (non drupal) to Percona Server 5.5 We decided to go from a perl website to Drupal 7 (PHP 5.5.23).

My big question is how do i migrate the DB which is PSQL 9.1 to mySQL. I've heard of the Migrate module, Drush, MySQL Workbench.

Can someone direct me on which steps to take after converting my postgresql schema to  mysql?

I end up using the feeds importers modules. You may have to change (rewrite/delete) your tables.

dump my table in a csv file (*.csv) make sure to add the headers.
create a content type with the name of my table and have all the columns of my tables
create a feed importer make sure to map the sources (postgreql) and target (drupal mysql) columns
got the import link (homepage/import) to upload the file. this may take a few minutes depending on how big you DB is.
when you go to content you should see all the newly added rows

Hope it helps.