Drupal 7 Theme [Business] not pulling in to non-front pages I am programming five custom modules for a client in Drupal 7.  Tey have, well, HAD, a company in India doing their front-end work.  Something went wrong and the India company stopped responding and developing the front end, so I have been tasked with finishing the pages and of course still complete the modules.  Didn't think this would be a real big deal, but here is the rub--

The company created the front page template.  I went in created a few pages, [ie about, connect, meet the authors, etc].  When I looked at the pages, they looked awful, no formatting at all, except for the top navbar/header which is actually pulling from the subtheme.  I have enough css skills to realize these new pages are not calling the base theme, in this case, they are using the drupal business theme located here [https://www.drupal.org/project/business].

The former company created a subtheme, of sorts, off the "Drupal Business" theme and have the page--front and page.tpl.php along with css and js related folders and files.

i turned on devel_themer and see the front/home page is calling the new front-page template. When I look and click on the body/node of my new pages below the top nav/header, the function call reference "theme-field", not the base theme or the subtheme that is in /sites/all/themes....

Since I am more a programmer and hence the reason I love Drupal, don't have to worry about all the theming stuff.  I just need the new pages to apply the base theme's css and reference the settings correctly.

Could any of the theming pro's give me some insight, assistance please?  It seems like there is a setting to apply the theme to the pages you want, but I can't figure that out.

If you want page specific theme'ing, look at themekey module:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.


Put social Icons next to body field ($content['body']) I want to align my social icons vertically next to the body field, in my node.tpl.php file the body is included in the $content with everything else. The social icons sit a few lines above and look like this in my node.tpl.php file:

<div class="main-node-social-share">
  <?php print render($main_node_social_share);?>
</div>

How can i get $main_node_social_share to render right before the $content['body'] field?

// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);

Try some thing like this in custom module and see it helps.

function modulename_page_alter(&$page) {
  $social=array(
    '#markup'=>'

',
  );
  array_unshift($page['content']['system_main']['nodes'][1],$social);

}


For Drupal 7 sub-domain installation is sites.php the same as 6's use of symbolic link folder? I have a working Drupal 6 using a shared Drupal install on a shared Linux server. I've just installed D7. I'm not sure if sites.php is set up correctly (see below). And I can't find good information on this sites.php file to be sure I set it up correctly. This Drupal.org page describes the correct installation situation, but sadly does not mention sites.php (>_<) This Drupal forum poster has the same "Server Not Found" error, but shows completely wrong sites.php example--the set up is not clear.

Is sites.php do the same thing that a symbolic link folder did in Drupal 6. Can I ignore this file?

My sites.php file,

 $sites['mondo7'] = 'mondo7.mydomain.com';

and I tried it the other way,

 $sites['mondo7.mydomain.com'] = 'mondo7';

Both show up "Server Not Found".

sites.php exists so you can fake out the normal multi-site operation, like mapping 'localhost' to 'foo.mysiteroolz.com'. Ideally you wouldn't use it in a production server.

In a live-to-the-internet site, you don't want to have sites.php (unless you specifically know why you do), and you want your subdomain to resolve to the same IP and directory as the domain. Then just have a subdirectory in /sites. So:

drupal/sites/default/ will have settings.php and files for mydomain.com

drupal/sites/mondo7.mydomain.com/ will have settings.php and files for mondo7.mydomain.com.

Then in your dev setup, you'd have a sites.php file that says something like 'localhost' => 'mondo7.mydomain.com' This tells Drupal which site directory gets the attention when a request comes for localhost.

HTH.


Apply percentage coupon to entire order (Commerce) I am using Drupal Commerce and Commerce Coupon Percentage. It works great for most products. However, I have a product priced at $0 and the price is then altered through rules which changes the line item total for that order.

Because the product is priced at $0, the percentage does not apply. Therefore, I am wondering if there is a way to apply the percentage coupon to the entire order rather than the product price. Any thoughts on how to approach this?

Price calculation in Drupal Commerce always happens at a line item level. There are order level coupons for knocking a set amount off an order total, but we treat percentage coupons as these line item level price calculations. You should be able to adjust the weight of your product pricing rules so your rule that updates the price gets evaluated prior to the rule that applies the percentage coupon to the item. Give that a shot and leave me a comment if it doesn't work.


How do I change the structure of node's $content variable? I create a Content Type and I add to it a field (Embedded Media Field) that has thumbnails of Youtube videos.

Now the thumbnails use each a row on its own. I want to make them show in three columns, like in a grid. I understand i have to create a node-MyContentType.tpl.php . But in this file there is a $content variable that holds the html structure of the content and i can't find a way to change that (i want to remove some divs). Can anyone guide what to search for?

Creating a template (node-MyContentType.tpl.php) for your content type is certainly helpful to manipulate the display of the entire node, but it sounds like what you're looking for is how to modify individual fields, and these are rendered in a different template.

Drupal uses template files and theme_xxx() functions to display elements on the site, and there is generally one template or theme function for each object (page, node, block, field, etc.). In order to override them, you use a feature called Template Suggestions. These are an alternate template (.tpl.php) file that you have created to override the base or original template file. Read more about these for Drupal 6 or Drupal 7.

The best way to create your own version of a template file is find the original one, copy it into your theme folder (don't modify the original!), and rename it using the "template suggestions" convention mentioned in the links above. In Drupal 6, you have to have both the base template (e.g. node.tpl.php) as well as the renamed one (e.g. node-mytype.tpl.php). In Drupal 7, having the base template in the same folder is not necessary.

In Drupal 6, fields are a part of the CCK module. Here's information on overriding CCK Field templates. The original template content-field.tpl.php is located in the CCK module under cck/theme.

In Drupal 7, fields are a part of the Drupal core code. The original template field.tpl.php is located in modules/field/theme.


$form_state for an autocomplete callback I'm trying to get the value of $form_state for my autocomplete textfield.

Basically, I have a search textfield and checkboxes to restrict the autocomplete.  What would be the best way of passing the checkbox values to the autocomplete?

The autocomplete callback just gets the string that needs to be auto-completed.
In your case, the only solution I can think of is that the checkboxes use an AJAX callback that is used to set a value the autocomplete function can then access.


Which table stores info about hook_update_N? I want to re run same hook_update again. For example hook_update_8005. I am not sure where Drupal put info to track.

The schema version for the update hook is stored in the key_value table.

You can set it with the global function drupal_set_installed_schema_version($module, $version).

For example:

drupal_set_installed_schema_version('my_module', 8005);

If you want the check the schema version number:

$schema_version = drupal_get_installed_schema_version('my_module');


How to redefine / override the default breakpoints in a Bootstrap sub-theme I have a Drupal 7 subtheme based on the Drupal Bootstrap theme CDN starterkit. I'm trying to change the default breakpoints, which I thought would be a simple, routine task, but I can't find anything that works.

I've read this issue which shows that the theme supports the Breakpoints module. I've installed the Breakpoints module, followed the steps given, got confirmation in Drush and the Breakpoints module UI that my new breakpoints have been read from my .info file - but the columns in my Bootstrap subtheme ignore these and carry on using the built-in ones. I've cleared all browser and Drupal caches.

I can only assume that the "Breakpoints module support" means that it allows other modules (like Navbar etc) to listen to the custom breakpoints, whereas Bootstrap itself continues getting Bootstrap CSS files according to its built-in defaults.

I've also been through the Drupal Bootstrap documentation and can't find anything about breakpoints at all. I only confirmed what the default Bootstrap breakpoints were through a comment in the above linked issue.

All I can think of is, to compile a version of the Bootstrap CSS with the breakpoints I want, upload it and use it instead of CDN as per "Using own Bootstrap 3 files in Bootstrap Drupal 7 theme". I'm wary of this however because it seems like the theme PHP would expect different breakpoints to those defined in the theme CSS which sounds like a recipe for strange bugs further down the line. I'd prefer to override some setting or, failing that, function in the theme so that it gets the configuration I want from the CDN and isn't expecting a different configuation.

[UPDATE] I've tried this and it does seem to work, although at first I thought it hadn't because I'd misread how the Bootstrap compiler used minimum and maximum values. It feels like a very "against the grain" bodge though, and I won't be surprised if it causes problems later, which is why I'm not posting it as an answer.

How can I customise the pixel values for the xs, sm, md and lg Bootstrap breakpoints in a Drupal 7 Breakpoints based subtheme in a clean way that is consistent between front end and back end?

There doesn't currently seem to be anything in the Bootstrap theme that supports this directly, and the theme doesn't appear to listen to anything in the Breakpoints module. The bootstrap breakpoints are hard-baked into the JS and CSS.

If you're not using LESS, this means the only realistic option is to override the CSS and JS with custom local files. I had a bit of trouble with this at first but it seems to be fine and doesn't seem to conflict with anything in the server-side theme code.

Create a customised version of Bootstrap with your breakpoints and other preferences, from http://getbootstrap.com/customize/
Install the module Bootstrap Library
Upload the custom bootstrap files to sites/all/libraries/bootstrap
Disable everything to do with CDN in your theme settings page


How to add icons for Drupal 6 menus? I have created some menus with menu block module and placed it in my Drupal 6 site's left sidebar, also used menu icons module to put icon for each menu. But the end result is not satisfying. It demands more padding and text resizing to make it attractive. Can anyone suggest some other technique to add icons for menus in Drupal 6.

Try the css way

li.menu-mlid-600 > a {
    background-image: url('../images/my_icon.png');
    height: 150px;
    width: 200px;
    text-indent: -9999px;
    display: block;
}

But there are other ways. Google it. Here is another way:

How to use images for menu items in Drupal with a simple preprocessing function


Advantage of including file in .info file and also in hook_theme() While studying the code in the Elements module, I noticed that the file elements.theme.inc is listed in elements.info, but is also listed for each theme implementation in elements_theme().

elements.info

name = Elements
description = Provides a library of Form API elements.
core = 7.x
files[] = elements.module
files[] = elements.theme.inc

elements.module -> elements_theme()

function elements_theme() {
  return array(
    'emailfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'searchfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'telfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'urlfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'numberfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'rangefield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
  );
}

The Question

is there any advantage or performance improvement from listing the elements.theme.inc file in both places? Is there another reason why this might be necessary?

As always, I appreciate all responses.

The Elements module is using that slightly incorrectly; files[] is used to inform Drupal's autoloader of files that contain classes, so that they can be used without manually including the file they're declared in.

As elements.theme.inc doesn't contain any classes, listing it in files[] actually does nothing at all. Though it doesn't cause any problems, such is the nature of autoloading.

So to directly answer the question, there can't really be an advantage of using one method over another, as they're used for different things. If elements.theme.inc contained a class as well as the theme functions, it would be perfectly valid to have both declarations.

As an aside, I've seen this plenty of times before - there was a bit of confusion when D7 first came out as to what files[] was for, and quite a few people chose to list all of, or the 'main' files of, their module.


Get URL path or node.id in views fields replacement pattern I need to rewrite my view fields like:

     {{ title }}

But if I click on Add field (in my view), nid, or path are not available? I have to construct my  link attribute like above markup. But how do I render the URL path to the node?

But if I click on Add field (in my view), nid, or path are not
  available?

Did you create a view of Show: Content ? (re-using pic from other answer, look in view settings)

You probably selected something else, hence why those fields are not available.

So you could add a relationship of node content or create a brand new view again and this time make sure you select Show: content.


How to bulk update (delete) Product Variations I want to bulk select product variations for deletion, just like we can do with content and products in admin.

I tried to duplicate the products admin view, and also creating my own, both throw various error pages. It seems there is a security system in place to prevent variation deletion outside of the product pages?

Is there any way to accomplish this?

This is error I get if I add and use a bulk update field (the view is getting "product variations")

    The website encountered an unexpected error. Please try again later.
Error: Call to a member function getPlugin() on null in Drupal\views\Plugin\views\field\BulkForm->viewsFormSubmit() (line 372 of core/modules/views/src/Plugin/views/field/BulkForm.php).

Seems now you know the answer :)

https://www.drupal.org/project/commerce_bulk/issues/3023651

BTW, thank you for your contribution to the module!


Prevent rule from triggering on Entity Reference Fields I am trying to add a rule that does something when the user views my content type "contacts", so I used the "Content is viewed of type" event to trigger the rule.

Contacts can also be added to other nodes via the Entity Reference Field. Eg. for the content type "events" you can add the contact in charge of it.

Problem is now that this rule also triggers for content type "events", cause of the "contacts" reference.

How can I prevent that?

It shouldn't fire because of an entity reference field..

Have you added a Content is of type  condition to the rule?

Data selector: node
Value: Contacts.

Edit:

It could be that the display mode of the referenced entities is counting as a view.

Add a condition, data comparison for site:current-page:url and node:url

This will force rules to check the page url which will return FALSE for every page except the nodes's pages.


Is Display Suite compatible with Panels? -Drupal 7.37 & Omega4-Subtheme

-Windows7 HP & Toshiba Laptop

-Acquia-DevDesktop WAMP-Stack

Just a Simple question.  Is [DS] Display-Suite-Module compatible with [panels] and [panelizer]?

By that I mean do they implement conflicting Drupal-Code strategies for accomplishing the same objective.  Do they have any name-space-collisions?

I am well aware that they "purpose-wise" cover basically the same territory.

I would like to try using one on certain website-projects and the other on other website-projects. I might then leave one unenabled.  When I am familiar with both, I might attempt to use both on the same project.
Thank you for taking the time to read this.

They are compatible in the sense that you can use Panel layouts on DS. (See picture below)

You can use DS for one content type and Panels for another content type. Not sure who would win if I enabled both for the same content type, but why would anyone do that?

Where it's not compatible is with mini panels, unfortunately you can't insert mini panels into a custom DS dynamic field.


jQuery UI is missing in all pages I am having the errors in console for jQuery UI. The jQuery Update module (7.x-2.4) is being used in my theme, and I have no idea why it is not including the jQuery UI. The following is the screenshot of the errors I get. In the view source I don't find jqueryui.js.

It happens in all the browsers. I also tried using the files from the jQuery CDN, but it didn't work at all. These errors are creating many troubles in the admin area. Many things aren't working: The Views interface is broken and the MD Slider is broken.

jQuery UI is not included on every request by default. Drupal only adds it when it is requested.  You can ask Drupal to include the libraries you want on some or all pages with a custom module inside a hook_init or hook_preprocess_page.  Something like this would work:

function MYMODULE_init() {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.widget');
  ...
}

For a full list of all system libraries see the API documentation here.

Also, new versions of jQuery do not play nice with many system forms (views as you noted but also rules & panels can have issues).  Newer versions of the jquery_update module have the option of setting a different version of jQuery for administration pages. You will probably want to set that to 1.5 (the version D7 ships with), or add the jquery.migrate script to your theme to allow older jQuery to run on newer versions.


Import latitude and longitude from XML to Location field for GMap, for Views display From my XML data which I have imported into nodes, I have CCK fields for Latitude and Longitude. I want to import those values into Node Location so that I can have two Gmap integrations:

Show a GMap on each node to show where it is located
Show all matched locations on a Views page with an exposed form

Is there something I have to do with mapping the fields correctly inside of Migrate, and if so, how would I define the Location fields as destination fields? I also found this on Migrate Extras that seems to have integrated it with Location, but that was for D7.

Then, how do I integrate the GMap with my Views page and get items to filter correctly?

What I did was I just made two CCK fields for latitude and longitude. I used the function gmap_simple_map to create a map in my nodes, code placed in the node tempalte file.

Then, in Views, I made a block attachment that was a GMap and chose those CCK fields (which must be defined under fields) as my latitude and longitude.


ckeditor showing blank text area I have been using ckeditor, with ckeditor drupal module with ckeditor 4.4.3 full edition. Previously, it was working fine and suddenly it was not working and it was showing blank text area in the body field as shown below.

I tried to re-install ckeditor module and library fields, but no change in the result. It appears empty, I couldn't trace the reason. How can I get to work with ckeditor.
Previously, my ckeditor was inserting span elements with a line-height of 1.6em in my paragraphs of text and I have no idea why.
The bottom shows body > p > span span span.  Spans with 1.6em line heights.
How can I resolve the issue??

I suggest to clear cache, use jQuery update module to update the version of jQuery. This worked for me.

Wish it might help!!


Change Aegir Log Level? The log messages for tasks seems pretty uninformative when you have an error. Is it possible to change the log level for task logs in Aegir? If so, how?

Thanks!

Navigate to Hosting » Settings » Task Logs to Display and you can check/uncheck the boxes for the different types of log messages.

As Add proper UX to the selector for choosing logs types to show is fairly new (see that issue for background), it hasn't made it into a release yet so you'll probably still see the text area.


can I implement select_or_other just with core form API? Select (or other) works great but I want know can I implement its functionality with invisible key available for #states attribute described in form API

Yes you can do that with FAPI & #states.

You would do something like this:

$form['options'] = array(
  '#type' => 'select',
  '#title' => t('Select'),
  '#options' => array(
    'one' => t('One'),
    'two' => t('Two'),
    'three' => t('Three'),
    'other' => t('Other'),
  ),
);
$form['other'] = array(
  '#type' => 'textfield',
  '#title' => t('Other'),
  '#states' => array(
    'visible' => array(
     ':input[name="options"]' => array('value' => 'other'),
    ),
  ),
);

This would make the "other" field visible when the value of the "options" field is "other".

For more info on states see the docs for drupal_process_states()


Field widget value not able to save via ajax I am trying to create a custom field type widget with a ajax submit handler to save the value of the field to the database without saving the whole node.

Here is my code hook_field_field_info().

function mymodule_field_info() {
  return array(
   'time_logger_time' => array(
   'label' => t('Time loger'),
   'description' => t('Custom Poutine Field'),
   'default_widget' => 'time_logger_time_widget',
   'default_formatter' => 'time_logger_default_formatter',
   ),
  );
 }

Than this is my  hook_field_widget_info()

function mymodule_field_widget_info() {
   return array(
   'time_logger_time_widget' => array(
   'label' => t('Default'),
   'field types' => array('time_logger_time'),
  ),
 );
}

And finally my hook_field_widget_form() looks like

function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    $value = isset($items[$delta]['id']) ? $items[$delta]['id'] : '';
     $element['id'] = array(
       '#type' => 'textfield',
       '#size' => 6,
       '#default_value' => $value
      );

     $element[submit] = array(
      '#type' => 'button',
      '#value'=>'Save',
      '#name' =>  'submit-'. $delta,
      '#ajax' => array(
        'callback' => 'mymodule_ajax_handler',
        'effect' => 'fade',
       ),
   );
   return $element;
 }

Idea is when I click the save button in my widget form it will call my ajax callback load the node, set the value of my field and save the node as follows-

function mymodule_ajax_handler( $form, &$form_state){
     $node = node_load(22);
     dsm( $node);
     $node_wrapper = entity_metadata_wrapper('node', $node);
     $node_wrapper->field_log->set(1);
     $node->save();
 }

But when I click button I am getting some error saying  "Notice: Undefined index: field_log in EntityStructureWrapper->getPropertyInfo() (line 334 of /var/www/html/mysite/sites/all/modules/contrib/entity/includes/entity.wrapper.inc)."

If I change my field in the ajax callback to some other field in my content type its saving fine. Like below-

function mymodule_ajax_handler( $form, &$form_state){
 $node = node_load(22);
 $node_wrapper = entity_metadata_wrapper('node', $node);
 $node_wrapper->some_other_field_from_my_content_type->set(1); //This works fine
 $node->save();
}

Is there anything wrong in my widget form.

Here is my field scheme if someone want to refer-

function mymodule_field_schema($field) {
$schema = array();
$schema['columns']['id'] = array(
    'type' => 'varchar',
    'length' => 50,
    'not null' => FALSE
);
  return $schema;
}

There might be a few issues, but it hard to tell.

First make sure the field is actually on the node. (Source https://www.drupal.org/documentation/entity-metadata-wrappers):

function _wrapper_debug($w) {
  $values = array();
  foreach ($w->getPropertyInfo() as $key => $val) {
    $values[$key] = $w->$key->value();
  }
  return $values;
}

dpm(_wrapper_debug($some_wrapped_object));

If it is there, perhaps you made the field a multi value field (it can hold more then 1 value), in this case you need to assign it like this:

 $node_wrapper->field_log[]->set(1); // Note the extra []

If this does not solve the problem, have a look at the above metadata wrapper page. It comes with a lot of examples en explanations.


Search and display node by scanning a barcode image I am developing a new tracking system for my fashion store to have a good relationship with my returning back customers using drupal 7.
THE SCENARIO:
1) When a customer come into my store and buy some products, he/she will be given a plastic card with a barcode on it, and ask him to present this card to the cashier every time he/she visits our store.
2) When the customer will come back later and present his/her card, the cashier will scan their plastic card using a barcode scanner device attached to the computer where the drupal website is always loaded in the browser.
3) Upon scanning of the plastic card, the website will perform a quick search based on the barcode input data and return two possible actions:
First Action:(If the card was not found on the system)
Information message: This card in not registered into the system.
Second Action: (If the card was found on the system)
Display a page contain information related to the scanned card like first name, last name, last purchased items, phone number....
MY WAY OF APPROACH:
1) I created one content type VIP Customer and added to it the below fields:
Barcode field (using the barcode module)
First Name
Last Name
Phone Number
Last purchased items
....
2) Create a webform with one text field to scan the barcode . (Using webform or entityform module)
3) In order to not let the cutomers wait for the cashier to prepare the plastic card and printed out and...
All plastic cards will have to be prepared earlier and in order to do that i decided:

Create around 500 nodes of type VIP customer where the field barcode is the only field which is filled by some data.

The data filled inside each barcode field is a arbitrary mix of text and numbers just to create a barcode image for each node.

Take all of the barcode images and give them to a library in order to print the barcode images on plastic cards.

Now, I have around 500 plastic cards with barcodes printed on them and each related to a node on my drupal website and ready to be used directly.

4) When a customer will come, the cashier will take a new plastic card and scan it using a scanner reader and here the magic will happen:

The cashier will open the webform and scan the barcode on the plastic card.

The barcode scanner will input the code behind the barcode image into the text field.

Automatically when this text field is filled up with some data, a quick search will take place and find the only node which related to the scanned barcode image.

The node will be displayed to the cashier and here the cashier can edit the node to add information about the customer.

When finish, the cashier will save the node and give the card to the customer.

5) When the customer will come back later, the cashier will take the card from the customer and scan it.

The node should automatically open on the screen and the cashier can read all the information related to that customer.

PROBLEMS:

How to transfer the code from the barcode image to the text field on the webform upon scanning ?

and what is the best approach for performing the search among all nodes and pull out/display only the node related to the card being scanned.

If the above is possible with drupal I prefer to use the drupal core and contributed modules without any written custom codes.
(I am good with drupal but not good in php coding)
Thank you for your time and support.

How to transfer the code from the barcode image to the text field on the webform upon scanning?

AFAIK most of the scanners place value into focused form element (the one with the cursor in it). So make sure that field is focused when you load the page and that should cover your first question. You can probably use contrib modules (eg. https://www.drupal.org/project/focus) to achieve it without any custom Javascript.

  and what is the best approach for performing the search among all nodes and pull out/display only the node related to the card being scanned.

I think the easiest approach is to create a View with exposed filter (barcode). Then after scanning the barcode on the plastic card, you'll be one click away from a node for an existing card.


Question about the templates I create a module and implement hook_menu():

function mymodule_menu(){
  $items['mymodule/list']=array(/*...*/);
  return $items;
}

then I create a theme and create page.tpl.php and page--mymodule-list.tpl.php at the same directory.

now I can access http://localhost/?q=mymodule/list, but it use page.tpl.php to render the page, instead of page--mymodule-list.tpl.php.

How should I do to make it render the page with page--mymodule-list.tpl.php?

The 'rules' for the page.tpl.php template suggestions state you need to substitue each / in the page for 2 dashes, so your template file needs to be called:

  page--mymodule--list.tpl.php

Remember to the clear the cache again once you've made the change


simplesamlphp_auth installation fails on Centos 8-server I am trying to install simplesamlphp_auth to Centos 8/Drupal 8 server according the instructions on:

https://www.drupal.org/docs/8/modules/apigee-developer-portal-kickstart/integrate-simplesamlphp-
authentication

When I run the given command I get the following output:

composer require drupal/simplesamlphp_auth:3.x-dev drupal/simplesamlphp_custom_attributes --prefer-dist
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Using version ^1.0 for drupal/simplesamlphp_custom_attributes
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - don't install drupal/simplesamlphp_auth 3.x-dev|install drupal/simplesamlphp_auth dev-3.x
    - Installation request for drupal/simplesamlphp_auth 3.x-dev -> satisfiable by drupal/simplesamlphp_auth[3.x-dev].
    - Conclusion: remove simplesamlphp/simplesamlphp v1.17.7
    - Conclusion: don't install simplesamlphp/simplesamlphp v1.17.7
    - drupal/simplesamlphp_auth dev-3.x requires simplesamlphp/simplesamlphp ^1.18.2 -> satisfiable by simplesamlphp/simplesamlphp[v1.18.2, v1.18.3, v1.18.4].
    - Can only install one of: simplesamlphp/simplesamlphp[v1.18.2, v1.17.7].
    - Can only install one of: simplesamlphp/simplesamlphp[v1.18.3, v1.17.7].
    - Can only install one of: simplesamlphp/simplesamlphp[v1.18.4, v1.17.7].
    - Installation request for simplesamlphp/simplesamlphp (locked at v1.17.7) -> satisfiable by simplesamlphp/simplesamlphp[v1.17.7].

Installation failed, reverting ./composer.json to its original content.

So it seems, that for some reason the new enough simplesamlphp-package is not installable.

I have tried (in vain, though) to harvest the web about this problem, which should not be totally uncommon IMHO.

Any hints how to tackle the problem?

wbr

Hank

Sorry for the trouble. The problem was caused because I had somewhere in the past installed those modules to this (test) site of my own and forgotten it totally. After removing the old simplesamlphp_auth things seemed to go OK.


Add Glyphicon to titles? I am attempting to add glyphicon options to titles. Is there a way I can add a field to a content type in order to render the html showing the glyphicon? I am trying to add it to just the basic page content type and the page it shows on title click.

I tried adding a select list with the  inside as options for example, but it would not render the html.

EDIT:::

I tried the title html module, but it only allows a few elements. I would ideally like to add a select list to my content type that contains all the glyphicons i'd like to use on the page and i could just select which one to show before the title from that select list. It would then show the glyphicon before the title on save.

I think you're on the right track with adding a second custom field to allow the user to choose the glyph.

Once the user has set the title, selected the glyph and saved,  you can merge the two using a template file.

https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7

The one you'd want I think would be named something like this:  field--title--basic-page.tpl.php

In there, you can stick the value of the glyph next to the title.  Does that make sense?


How can I programmatically create a select input whose values come from a foreign key using Form API? I have Table A who has a foreign key referring to Table B. I want my form associated with Table A to have a select field whose values will come from Table B. I want the select field to have options with key-value pairs coming from Table B.

Both Table A and Table B contain entities of different types.

I'm currently looking for programmatic solutions that use Entity Reference, but without having to go through adding a new field from Administration > Structure > <entity type>.

I went with this solution that uses entity_load then adding the loaded entities as options to the select field for now:

$foreign_entity_items = entity_load('foreign_entity');
$foreign_entity_options = array();
foreach ($foreign_entity_items as $foreign_entity_item) {
    $foreign_entity_options[$foreign_entity_item->some_field] = $foreign_entity_item->some_other_field;
}

$form['some_form_element'] = array(
    '#title' => t('Some title'),
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => $foreign_entity_options
);


How do I find out a blocks ID? $block = module_invoke('menu_block', 'block', 'view', 26);
print $block['content'];

I am trying to use this code to print out a block, but I do not know how to get the ID for the last parameter.

You just need to look for the hook_block() implementation done from the module for which you are invoking module_invoke(). The last argument in the function call you reported is the $delta parameter that is used from Drupal to identify the block within the module.

For example, looking at the code of forum_block(), the part of the code that implement the "list" operation, 0 is the delta parameter for the "Active forum topics" block, and 1 is the delta parameter for "New forum topics" block.

The code you wrote in your question is invoking the implementation of hook_block made from a module whose short name is menu_block (which means the function implementing the hook is menu_block_block()). If you meant to invoke the implementation of hook_block() made from menu.module, then the code should be the following one:

$block = module_invoke('menu', 'block', 'view', 26);
print $block['content'];

The function implementing hook_block() is menu_block(). The values used as $delta from that function are the values of the "menu_name" field used in the "menu_custom" table.


hook_block visibility I have a custom module defining a block which needs some complex page visibility rules that I'll write later. In building out the basic hook_block code the visibility and pages settings don't seem to be working when returning FALSE.

function popup_footer_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Popup Footer'),
      'visibility' => 2,
      'pages' => popup_footer_block_visibility(),
    );

    return $blocks;
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        $block = array('content' => 'foo bar');
        break;
    }

    return $block;
  }
}

function popup_footer_block_visibility() {
  return FALSE;
}

When the block visibility is set to 2, $block[0]['pages'] needs to be a string that can be passed to drupal_eval() as first argument. In fact, the code which handles the block visibility is the following one.

  // Match path if necessary
  if ($block->pages) {
    if ($block->visibility < 2) {
      $path = drupal_get_path_alias($_GET['q']);
      // Compare with the internal and path alias (if any).
      $page_match = drupal_match_path($path, $block->pages);
      if ($path != $_GET['q']) {
        $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages);
      }
      // When $block->visibility has a value of 0, the block is displayed on
      // all pages except those listed in $block->pages. When set to 1, it
      // is displayed only on those pages listed in $block->pages.
      $page_match = !($block->visibility xor $page_match);
    }
    else {
      $page_match = drupal_eval($block->pages);
    }
  }


Boost not caching subdomains I have a website with subdomains set up, the naked domain without any subdomain gets cached by boost and there is the message by boost in the footer. But any subdomain does not get cached. We are using the sites module http://drupal.org/project/sites, to split the subdomains into different drupal sites.

We have this error  on the status  report page - Boost crawler did not get a 200 response; 302 returned instead.

my boost settings

  ### BOOST START ###
  AddDefaultCharset utf-8
  FileETag None
  <FilesMatch "(\.html)$">
    <IfModule mod_headers.c>
      Header set Expires "Sun, 19 Nov 1978 05:00:00 GMT"
      Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
    </IfModule>
  </FilesMatch>
  <IfModule mod_mime.c>
    AddCharset utf-8 .html
    AddCharset utf-8 .css
    AddCharset utf-8 .js
  </IfModule>
  <FilesMatch "(\.html)$">
    ForceType text/html
  </FilesMatch>
  <FilesMatch "(\.js)$">
    ForceType text/javascript
  </FilesMatch>
  <FilesMatch "(\.css)$">
    ForceType text/css
  </FilesMatch>

  # NORMAL - Cached css & js files
  RewriteCond %{DOCUMENT_ROOT}/cache/perm/%{SERVER_NAME}%{REQUEST_URI}_\.css -s
  RewriteRule .* cache/perm/%{SERVER_NAME}%{REQUEST_URI}_\.css [L,QSA,T=text/css]
  RewriteCond %{DOCUMENT_ROOT}/cache/perm/%{SERVER_NAME}%{REQUEST_URI}_\.js -s
  RewriteRule .* cache/perm/%{SERVER_NAME}%{REQUEST_URI}_\.js [L,QSA,T=text/javascript]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add))|(/(comment/reply|edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{HTTP:Pragma} no-cache [OR]
  RewriteCond %{HTTP:Cache-Control} no-cache [OR]
  RewriteCond %{HTTPS} on
  RewriteRule .* - [S=1]

  # NORMAL
  RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/normal/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

  ### BOOST END ###

I applied this patch and now it works

http://drupal.org/node/1508994


Grouping a View by Custom Field Hi there i hope you can help. Drupal info below.

Core module :   6.22
Installed modules: CCK, Views, Image, SEO.

I have a custom field called field_type which i need to group by.

After searching in vain on the internet for a long time I'm unable to find an answer that works.

Could anyone give me step by step instructions how to create a view like the sketch below.
Basically each item has a type assigned to it, and i need to group the results of the view by type. Preferably with a title above the group to say which type it is.

Type 1 -

Item 1, Item 2, Item 3, Item 4

Type 2 -

Item 5, Item 6, Item 7, Item 8

Type 3 -

Item 9, Item 10, Item 11, Item 12

Thanks!

In a nutshell....

Create a view, with a filter of the node type that contains this field_type and if it's published etc.

Add all the fields you want to display, including the field_type.

In Advanced Settings, turn grouping on.

In Style Settings, click on the Unformatted Settings (the round dodad next to Unformatted :) and in there you will now see a grouping field...so select field_type.

Save and preview.  It should do what you want data wise, so just add whatever CSS is needed to make it look pretty.


theme_table() isn't respecting sortable fieldname I generate some data in one of my modules and generate a table using theme_table(). I want the fields in that table to be sortable, but the table is being rendered with the wrong value in the links.

I'm getting ?sort=asc&order=Birth Date instead of ?sort=asc&order=field_birthdate.

Here is the code I'm using to generate my table:

$headerColumns = array(
    array('data'=>'Name', 'field'=>'title'),
    array('data'=>'Edit'),
    array('data'=>'Birth Date', 'field'=>'field_birthdate'),
    array('data'=>'Sex', 'field'=>'field_sex'),
    array('data'=>'Stars', 'field'=>'field_stars')
);

return theme_table(array(
    'header' => $headerColumns,
    'rows' => $rows,
    'attributes' => array(),
    'caption' => '',
    'colgroups' => array(),
    'sticky' => true,
    'empty' => 'You ain\'t got none.',
));

I believe I'm generating that array according to the instructions on the theme_table() api docs, but it's not working.

How do I get the sort link url to properly use the fieldname I'm giving it in the render array?

EDIT: As requested, here is the code I use to generate my query:

$query = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('uid', $user->uid)
            ->orderBy('type')
            ;

$direction = 'asc';
if (array_key_exists('sort', $_REQUEST) && $_REQUEST['sort'] == 'desc') {
    $direction = 'desc';
}

if (array_key_exists('order', $_REQUEST) ) {
    $fieldname = strtolower($_REQUEST['order']);

    $field_info = field_info_field('field_'.$fieldname);
    if ($field_info !== null) {
        $table_name = _field_sql_storage_tablename($field_info);
        $query->innerJoin($table_name, 'f', 'f.entity_id = n.nid');

        $query->orderBy(sprintf('f.field_%s_value', $fieldname), $direction);
    }

}

$query->orderBy('title', 'asc');

if ($entityType !== null) {
    $query->condition('type', $entityType);
}

$records = $query->execute();

You're doing too much work.

For sorting:

$query = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('uid', $user->uid);

$sort_query = $query->extend("TableSort")->orderByHeader($headerColumns);
$records = $sort_query->execute();

Using the TableSort extension will simplify things immensely.


How can I load a File entity? I want to find out whether a physical file is managed by Drupal and if it is, then load it.

I'm having trouble with the documentation which keeps displaying "File not found" at crucial moments, but it seemed that this ought to work:

$query = \Drupal::entityQuery('file');
$query->condition('uri', $file_uri);
$entity_ids = $query->execute();
if (count($entity_ids) == 1) {
    $file = \Drupal::entityLoad($entity_ids[0]);
}

However, I get this message: PHP Fatal error:  Call to undefined method Drupal::entityLoad()

There is no such method as \Drupal::entityLoad(). Use the static method on the entity type. Assuming "File", you should use:

$file = \Drupal\file\Entity\File::load(reset($entity_ids));

Berdir pointed out in a comment that QueryInterface::execute() returns an array keyed by entity ID or revision ID so reset() is the thing to use to get the first element.


How to load the immediate parent link in a preprocess function? I am using menu block to show a section of the navigation. I have a requirement to show the parent link at the top, but that would not gel with the menu configuration.

Therefore, I should be able to solve this by taking the first link in the list, and loading the parent. Then, I want to add that as a variable, and render it in my twig file above the loop that would output the entire link tree. However, I am coming up short on how to do this effectively.

So far, I have:

function mytheme_preprocess_block__menu_block(&$variables) {
  if ($variables['elements']['#id'] == 'left_navigation' && !empty($variables['elements']['content']['#items'])) {
    $children = $variables['elements']['content']['#items'];
    $top_child = key($children);

    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $menu_link_parents = $menu_link_manager->getParentIds($top_child);

    // the one we want should be the second one. the first one is the one in the main navigation across the top.
    $parent = end($menu_link_parents);
    $parent = str_replace('menu_link_content:', '' , $parent);
    $menu_content = current(\Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('uuid' => $parent)));

    $variables['top_parent'] = [
      'title' => $menu_content->getTitle(),
      'url' => $menu_content->getUrlObject()
    ];
  }
}

I am lost at the point I retrieve the parent. Is there a way to get the UUID instead of the dirty str_replace? Also, how can I take that UUID, and create an object similar to menu items that would be rendered?

I think you can do it with the 'plugin.manager.menu.link' service:

$link = $this->menuActiveTrail->getActiveLink();

if(!empty($link->getParent())) {
  $parent_link = Drupal::service('plugin.manager.menu.link')->createInstance($link->getParent());
  $menu_item = MenuLinkContent::load($parent_link->getMetaData()['entity_id']);
}

This way you don't have to replace the prefix.


How to get User Profile form? How do I get the user Profile form?
I tried the following:

$form = \Drupal::formBuilder()->getForm(ProfileForm::class);

but this results in :

  Fatal error: Call to a member function getEntityTypeId() on null in
  /www/project/docroot/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

You need to use it's namespace, like

use Drupal\user\ProfileForm;

 ..

$form = \Drupal::formBuilder()->getForm(ProfileForm::class);

Or prefix the class, like

$form = \Drupal::formBuilder()->getForm(Drupal\user\ProfileForm::class);

Or get it by 'name', like

 $form = \Drupal::formBuilder()->getForm('Drupal\user\ProfileForm');

  To fix your error, you need to pass a user object there, like this
  (for the current user)

Drupal::formBuilder()->getForm(ProfileForm::class, Drupal::currentUser());


Using to user_profile_form being used on a page thats not /user/#/edit I've found the post How to display one of Drupal's default forms which talks specifically about this issue. however I wanted to post comments on it to get more info, It didn't seem to let me. Mabey I missed a button somewhere.

Anyway, I have section of my Drupal 7 site for all account and user stuff. /my/ This is a portal so to speak, /my/account is a menu handler that originally called drupal_get_form('user_profile_form', $user); Everything works, except when trying to upload, My profile is customised with a field to upload a file and field to upload an image.

Neither field works, it just returns errors. after the ajax kicks in.

Using the method found in the above linked post my entire form refuses to save and gives me validation errors. Thew above link mentions that custom callbacks and/or validators may have to be added due to referencing issue so i was hoping that someone could point me in the direction of what those custom things are.

Thanks.

You're likely using module_load_include() to include modules/user/user.pages.inc.

However, you need to use form_load_include() whenever you attempt to load, build, process, and render a form that is defined and constructed in an entirely different include file.

form_load_include() requires to pass the $form_state in order to record the file to include (and automatically load it later, if needed). This needs to happen before the form structure is cached (which happens directly after invoking the constructor).

In order to do that, you can resemble what drupal_get_form() does, and inject the needed form_load_include() prior to building the form, like this:

$form_id = 'user_profile_form';
$form_state = array();
$form_state['build_info']['args'] = array($user);

// Load user.pages.inc and ensure it is automatically reloaded if
// this form is rebuilt via AJAX or other means.
form_load_include($form_state, 'inc', 'user', 'user.pages');

$form = drupal_build_form($form_id, $form_state);

More details:

Normally, Form API automatically takes over the include file to load (if any) from the menu router item definition in hook_menu().

In your case, your custom 'my/account' menu router item is not directly related to user.module, nor user.pages.inc, so the system does not know that this include file is required to build the form, especially when the form is submitted and rebuilt via AJAX — which happens on yet another system path/menu router item, namely 'system/ajax' (which, by default, would only know about an include file of your 'my/account' menu router item, if any).

In turn, Form API gets a request to rebuild user_profile_form, but the form constructor function user_profile_form() is not defined, because user.pages.inc was not loaded, since the cached $form_state does not contain a pointer that the file needs to be loaded.


How does Drupal.org's packaging script works? Is Drupal.org's packaging script publicly accessible? How does it works? What tools does it use to fetch a module and package it as a tarball? What are the best practices in building a nightly builds for Drupal modules?

The projects on drupal.org are managed by the Project project, which also contains the scripts for this. Some drupal.org specific code (for example the zip. and tar.gz packaging implementations) are also in the Drupal.org customizations project.


How do I take out the caching and bandwidth optimizations sections out of the performance window for a user? How do I take out caching and bandwidth optimizations sections out of the performance window for a user?

You can use the #access property to do this.  You would just need to wrap things up in your own logic.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  if (user_cant_access_this_stuff()) {
    $form['caching']['#access'] = FALSE;
    $form['bandwidth_optimization']['#access'] = FALSE;
  }
}

I am not 100% sure on those $form elements (this was taken from something similar I have on a site), so you may need to dpm() the $form.


#limit_validation_errors submit problem I have a problem using #limit_validation_errors for a submit button on which I dont want all the validations to run. Here's my custom submit button :

$form['actions']['draft'] = array(
     '#type' => 'submit',
     '#value' => 'Save as draft',
     '#submit' => array(''),
     '#limit_validation_errors' => array(
       array('title'), // Validate $form_state['values']['title'].
     ),
);

It works perfectly in the sense that it checks the validation on the title field only, but the weird thing is, it does not submit any other field's values when submitted. I wrote a custom submit handler to check that. However, the values are present in $form_state['input'] but not in $form_state['values'].

What I want simply is, this form will submit with just the values given and overlook the validations when this custom submit button is clicked.

FYI : I can get $form_state['values'] perfectly in my custom validate function.

Any ideas? What am I doing wrong here?

It works as expected - in $form_state['values'] you have validated values, and in $form_state['input'] you have raw values. If you will limit validation to title field only - only this field will be transferred into "values" array.


Multipage Registration form, Confirmation Page Security Issues? I have a multipage registration form working on a site, but the confirmation page is supposed to show some of the information (account name and other data) after the account has been submitted/created. I can treat this confirmation page as the last page of the multipage form, but I'm concerned that the user can then press the back button on the browser, the session data will still be there, and they can then re-submit the same data again.

Another approach would be to end the session and display the data on a redirect page, but I could not find how Drupal 7 would pass this form data to the redirect page. There would be too much data to put it in the URL.

Does anyone have a suggested Drupal 7 method to achieve a confirmation page showing session data, but not allow the user to press back on the browser and re-submit the form again?

After further investigation, it appears that one option is to make a confirmation page that is called after the form does it's final submission. Essentially, somewhere in the form alter or form functions near the end (after database operations), add a variable to PHP's $_SESSION array that contains the Drupal form ID (a long string of random characters), and add to this array another sub-array that contains all the information you want shown on the confirmation page.

Then, in the confirmation function (or page if you want to do the .tpl.php version), pass the form ID as a variable in the url. Then use this form ID to get the array from the $_SESSION array and retrieve the information.

As an example, see the drupal_set_message() function since it too uses the PHP $_SESSION variable to pass information back to the user on the next page load.

To keep the user from using the browser-back button and resubmitting the same information again, check the $_SESSION variable for the same form-id before committing user changes to the database and stop the attempt if the form-id's match. In some cases (e.g., registering for a new user account), Drupal will complain anyway if one tries to submit duplicate information to the database (e.g., username exists already).


Field template in theme based on Garland I have problem with template for field "field_is_new" in Drupal 7.
My_Theme is a modification of the Garland theme. (I don't know if it's important.)

I have created a template for this field in my theme folder ("My_Theme/templates/field--field-is-new.tpl.php").

In template.php, I added:

function My_Theme_preprocess_field(&$variables, $hook) {
  // Add specific suggestions that can override the default implementation.
  array_unshift($variables['theme_hook_suggestions'], 'field__' . $variables['element']['#field_name']);
}

I cleared the cache, and rebuilt the theme.

I was thinking it's good way to do this, but it's not working.
What's wrong?

Your preprocess function is not necessary in this situation because Drupal's default behavior is using this sort of files. Try print_r($variables['theme_hook_suggestions']); and see all relevant suggestions.

Your problem is the wrong filename; try field--field_is_new.tpl.php instead.

The general recommendation is using theme functions:

function theme_field__field_taxonomy($vars) {
  $output = '';

  foreach ($vars['items'] as $delta => $item) {
    $array = explode(';',$item['#markup']);

    if (count($array)) {
      $output = '
';
      foreach ($array as $value) {
          $output .= '
' . trim($value) . '
';
      }
      $output .= '
';
    };
  }

  return $output;
}


How can I use the unapproved comments list as a block? The unapproved comments list (available at /admin/content/comment/approval) allows me to perform bulk operations on comments such as deletion (which also gives me the option of reporting to Mollom) and publishing. I'd really like to have this on the dashboard itself — is there a way to replicate this admin page as a block so I can do so?

This is under Drupal 7.12.

I would just use Views to list unpublished comments. That wouldn't provide batch operations, but it doesn't seem like there would be a simple way to do exactly what you're asking.


Respect parent's node access level (Book) I was wondering if there is a way (using some hooks for example) so the child pages in a book respect their parents access level, meaning if user doesn't have the access to view the parent node, he won't be able to view the child nodes as well?

I use Drupal 6

I had a similar issue where I wanted the book main page's author (aka owner) to be able to edit all the lower level book page's even if they did not create the pages.

My solution was to create a custom module called 'Book author access' (http://drupal.org/sandbox/jrockowitz/1396474), which use the 'ACL' module (http://drupal.org/project/acl) to control a book's pages  access levels.

The 'Book author access' module does propagate the view, update, and delete permissions of the main book page to all to lower level pages, so it is possible that if you use the 'Content Access' module (http://drupal.org/project/content_access) and limited the view access to the book's main page it would solve your problem.

If you are not a developer then my answer might not be that useful...sorry.

As noted in my comment, I think the Book access module probably better addresses your requirements, just look at the below screenshot.


Show taxonomy term for administrators only in node creation form I have a content type Topic. The topic has the taxonomy terms -health -fitness and -news. I only want certain roles like administrators to be able to see and use the taxonomy term - news when creating topics. I need all other users to only see and use the other two.

How do I go about this? Would hook form alter be the right direction?

If you like to hide the whole field, you probably are looking for the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you like to hide certain terms only, you could use Views as reference method and filter your terms accordingly:

Create a new view for your taxonomy terms.
Create a Filter criteria "Term ID" to filter out all terms that shouldn't be available to non-privileged users, add a "Entity reference" display to that view and configure its Term name in the format settings.
Implement hook_views_query_alter() in a custom module and remove the filter criteria, if the users have the elevated roles:

mymodule.module:

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() != 'my_taxonomy_reference_view') {
    return;
  }

  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();

  if (in_array('USER_ROLE', $roles)) {
    unset($query->where[1]['conditions']['key_of_condition']);
  }
}

Head to your taxonomy term field settings and choose your view as reference type.

You might have to fiddle a little with the conditions, as the above example is just an outline for how you could do it. I actually didn't try it myself. But it should get you going.


File viewer with search filter by category and sub categories Drupal 7 I want to create a site running locally(localhost) which views files that are uploaded by authorized user. Using search filter by category and sub categories, all ebooks that are included in that sub categories will be shown. How to create this kind of search? Is there any module that will do exactly this one?

Ex, IT books---->programming books--->. Then it will display all programming books that are already been uploaded. When click to one of the programming books, it will display all the pages, like those in adobe reader. The concept is like that. how could i achieve this one? I'm having way too much problems searching for file viewer modules that will perfectly work. Hope you can help me.

A vocabulary of taxonomy terms could be set up to reflect the hierarchy of books.
Then you could attach this vocabulary to your node content type. After uploading a file to a node, you can tag the node with the appropriate term.
Views allows you to filter by taxonomy term of any depth.

This would organize your data, but you'll need to use some plugin/other means to display the book in adobe reader in the browser.


Why does drush say "command not found" when I try to execute remote commands? When I use a drush command to do something on a remote machine, I get the following message:

  bash: drush: command not found

What's the problem?

This message is from the remote machine complaining that it didn't understand where to find the drush executable, not Drush complaining that it can't find the (sub)command you may be trying to give it, even though the punctuation suggests the latter. (If bash: means Bash is  passing you a message, then drush: should mean the same thing--if there's any consistency. But actually it is intended to mean drush: is the subject of the message, not the source of the message passed through bash: to you.  It would be clearer if the second : were removed.)

Drush logs into your remote machine over ssh, but it's not a normal interactive login, so it doesn't source the .bash_profile.  It does, however, source the .bashrc file.

Add the drush path (not including drush itself, just including the directory containing drush) to the PATH variable in your remote .bashrc and all should be well.  For instance, that may look like this:

PATH=$PATH:/usr/local/zend/bin


How to know a user can access node/{nid} and node/{nid}/latest in fastest way I have a view displaying list of latest node revisions.

The view has title field.

The website gives users permissions to access node/{nid}(shows latest revision if published default revision doesn't exist) and node/{nid}/latest (shows latest revision if defaut revision and latest revision is different) depending moderation state and user groups.

I want to override the view's title field according to the rules below:

if current user can access node/{nid}/latest the title links to the page
else if current user can access node/{nid} the title links to the page
else show only title text

Dozens or hundreds of people may simultaneously access the view so I want to keep it fast to display. What is the fastest way to check those?

edit:
I searched about hook_node_grants but it only supports view/update/delete operations so I think it can't hold data for node/{nid}/latest.
Should I store every pattern in table just like node_access table does and look up on it when view is updated?

If you know the route name you can check access in PHP. For the second link you can use this route:

\Drupal::service('access_manager')->checkNamedRoute('entity.node.canonical', ['node' => '1'])).

You can find the first one with the help of the Devel module when you click on Current Route Info while displaying the content and look for [_route].

I would put the nid into the title field and override the field content in a preprocess hook. Display the link for each route if the access check returns true. Caching is no problem because caching is by default permission based.


What is cache_menu in Drupal 7 DB? Safe to empty? What exactly is doing this cache_menu table in MySQL Database of my Drupal 7?

It is the hugest table of all = currently 308 mb.... (and I have disabled search term indexing, so this is absolutely the biggest now...)

Is it necessaru so huge?!
I assume it is so huge, because I it includes a few of my Book - menus as well, but still...

If it is just a Cache - would it be safe to empty / disable somehow?

What exactly is doing this cache_menu table in MySQL Database of my Drupal 7?

Not to sound too glib, but it does exactly what it says - it stores cache for the menu system.

  Is it necessaru so huge?!

It's as big as it needs to be - if you have a lot of menu structure, it will be large. But 300mb isn't exactly a lot of data in this day and age.

  If it is just a Cache - would it be safe to empty / disable somehow?

Depends how you define "safe". Yes, your site will still work, but rebuilding the menus from scratch on every page load is likely to make your page requests take quite a bit longer.

You can safely truncate that cache bin and let it rebuild; maybe there is stale data in there that won't be re-added when the menus are built up again.


user_save does not save data if a user changes his email address, I want him to lose a specific role (if he had that role in the first place). To make matters more complicated, we have the "email confirm" module enabled and this bitchy little module uses user_presave() in a way that leaves no traces of an email change when it is called during the edit of a profile. So I wrote a module and gave it weight -1 to make sure it gets a chance to compare $edit->mail to the users current mail before "email confirm" begins to work.

My code looks like this (version with a lot of debug statements that will be removed in the live environment):

function xyz_user_presave(&$edit, $account, $category) {
  if (!empty($edit['mail']) && (!empty($account->mail) && $account->mail != $edit['mail']) && !user_access('administer users') && !drupal_installation_attempted()) {
    // remove xyz role if the users changes his email address
    $user = user_load_by_mail($account->mail);
    $role = user_role_load_by_name('xyz');
    if (array_key_exists($role->rid, $user->roles)){
      drupal_set_message('In if-clause.');
      $return1 = print_r($user->roles, TRUE);
      drupal_set_message($return1);
      $user2 = user_save($user, array('roles' => array_filter($user->roles, function($item) use ($role) {return $item != $role->name;})));
      $user3 = user_load_by_mail($account->mail);
      $return2 = print_r($user3->roles, TRUE);
      drupal_set_message($return2);
      if (!$user2){
        drupal_set_message('User_save() failed.');
      }
    }
  }
}

If I log in with a test user that has role xyz and change his email address at the "edit profile" site, i receive these status messages:

In if-clause.
Array ( [2] => authenticated user [5] => abc [8]
=> xyz )
Array ( [2] => authenticated user [5] => abc )

The debug messages tell me that:

It has been found out, that the user has the role xy and therefor the if-clause was entered.
Before the call to user_save(), the user had the role xyz
After the call to user_save(), the user was freshly loaded and he did not have the role xyz anymore

Yet despite all this, the user does not lose the role, no matter how often I change the email address or flush the cache.

My question now is: What the hell?

Using user_save() in the user_presave() function seems to be odd, but when I put the $roles array in $edit without the xyz-role, I receive pdo exception that states, that the roles are already set for this user.

This did the trick.

function xyz_user_presave(&$edit, $account, $category) {
  if (!empty($edit['mail']) && (!empty($account->mail) && $account->mail != $edit['mail']) && !user_access('administer users') && !drupal_installation_attempted()) {
    $role_position = array_search('xyz', $account->roles);
    // Use !== or === here since $role_position may be zero or FALSE
    if ($role_position !== FALSE) {
      unset($account->roles[$role_position]);
      $edit['roles'] = $account->roles;
    }
  }
}

I still do not know what's wrong with the code in the initial post, but whatever...


Webform submission values with PHP I am using webform 2 pdf module, where I am trying to set up a custom content to the pdf file.

I would like to acces the webform submission data, but I have no idea how to do it. Basically I would like to access them and use them as tokens.

I am on a basic level with both drupal and php, which means I have limits.

//simple first section

Registration

1. Registered Data:

[submission:values:personal_info:key]

2.  Declaration:

// there comes the non-working php part

<?php
    $var=($fields["institutuonal info"]);
    if ($var == "spec_inst") {
      echo "some juristic stuff";
    }
    ?>

So I am trying to export webform submission results to PDF, but the result depends on the submission content.

So I partly was able to access webform values. I still have a problem, that I cannot access to one single submission, altough I tried $sid = GET[sid] method. So here is my partly good code:

    //simple first section

Registration

1. Registered Data:

[submission:values:personal_info:key]

2.  Declaration:

<?php
$submissions = webform_get_submissions(array('nid'=>1));
foreach ($submissions as $submission){
foreach ($submission->data as $row=>$data){
        if ($row == 4){
              if (in_array("0", $data)) {
                    print("long boring text content");
}}}}
?>

So still not what I wanted but that is another question.


Clean URLs caused site to break? I'm installing a new Drupal site using Red Hat... Getting Clean URLs to work was a pain in the you-know-what. I followed all the steps in the official drupal.org helpguide, but ended up needing extra help for a guide specific to RHEL users here: https://www.tecmint.com/install-drupal-in-centos-rhel-fedora/

I went into my httpd.conf file and made AllowOveride All as shown here: https://www.tecmint.com/wp-content/uploads/2013/07/Enable-Clean-URL-in-Drupal.png

I then fixed all of my directory issues in .htaccess (because my .htaccess file is in sites/web), and then all my admin links work perfectly. So Clean URLs is definitely enabled, but the issue now is the site is broken.

This was probably caused by enabling Clean URLs through the httpd.conf issue, but I'm not sure. I ran drush cr and it did nothing. Help?

As leymannx and Kevin mention it is probably a misconfigured tmp/files directory

Uncheck aggregate css is something that you would not want on your live site as the performance will suffer.

Check in Reports > status report (/admin/reports/status) and try to fix or report on the errors that you see.

Also go into configuration > media > file system (/admin/config/media/file-system) and correct any file system problems reported when saving the settings.

The most probable cause of what you are seeing is wrong permissions.

There is a lot of guides on the net about setting those permissions.
You can start from the official guide on the subject or on one support thread that started as a drupal 7 thread but has Drupal 8 answers.


Alter comment links in blog teaser in drupal 7 I would like to alter the comment links in the teaser view of the blog page. The code I have in node--blog.tpl.php at the moment is:

<?php if ($display_submitted): ?>

<?php $date = date("d F Y", $node->created); ?>
<?php print $date; ?>

 <?php $user = user_load($node->uid); ?>
        <?php $username=$user->name; ?>
<?php print t("By"); ?>
<a href="blogs/<?php print $username ?>"><?php print $username ?>

 <?php print ($comment_count); ?> <?php print render($content['links']['comment']); ?>

>

with css: .submitted ul li span {
        color: #fff;
        background: url("../images/blue-bubble.png") 0px 2px no-repeat;
        background-size: 100% 96%;
        padding: 0px 5px 5px 5px;
}

which produces:

but I want to make:

Any suggestions on this would be great!

Thanks

If I were you I'd hide the span content in CSS and add a tag for my background image like this:

Template:

    <?php print ($comment_count); ?>

    <?php print render($content['links']['comment']); ?>

CSS:

.submitted ul li span.comment-count {
  width: 16px; // or whatever
  height: 16px;
  background: url("../images/blue-bubble.png") 0px 2px no-repeat;
  background-size: 100% 96%;
  padding: 0px 5px 5px 5px;
}

.submitted ul li span.comment-hidden {
  display: none;
}


Whats the difference between "Content Type" and "Content Types" on a block configuration form? Whats the difference between these two tabs? There is no help text here. One has "negate" the condition but the other does not.

"Content type" comes from CTools and "Content types" comes from core.

Simplified summary

"Content types" comes from core and is the preferred condition to use. The "negate" option is also present in core, but it is suppressed by the block module (source). In contrast to core CTools provides this condition not just for nodes but for any entity type (taxonomy terms, custom entities etc.). That's the reason why in case of nodes there is a duplicate set of entity bundle conditions.

Issues on drupal.org

Now there's this core issue Duplicate node type setting in block visibility which was closed as "works as designed". The problem shall be fixed by CTools (as in remove the duplicate entry).

This leads us to this CTools issue Duplicate node type visibility condition in block settings which was put on hold until core itself replaces CTools functionality to provide block visibility settings for any entity type (not just for nodes) including the "negate" option.

Which finally brings us to this core issue Add entity bundles condition plugin for entities with bundles where the progress to move CTools functionality to core to replace the current node type core condition is being tracked.


How do I get the server time using REST GET HTTP? Is it possible to get the time from Drupal 8 with GET HTTP and REST?

I get the date format from /entity/date_format/long, which returns a value similar to the following one.

{
"uuid": "76e070cb-a783-47bf-89cc-db9f393a7d59",
"langcode": "en",
"status": true,
"dependencies": [],
"id": "long",
"label": "Default long date",
"locked": false,
"pattern": "l, F j, Y - H:i"

}

It is not what I need. I need to get the server time, so I can after synchronize some dates.

/entity/date_format/long is just giving information on the date format

The easiest and cleanest way to do this is probably to create a simple custom REST resource in a custom module and within the resource you can return the server time using php functions

$message = [
    'time' => date("Y-m-d H:i:s"),
    'timezone' => date_default_timezone_get(),
];

You also have to implement CacheableResponseInterface in order to get the current time on every call to the service otherwise you are going to get a cached response.

Here is a working REST API time service module for this which I did just for the sake of this exercise


Contextual Filters not working I have a view which is a clone of the Product view (created for the Drupal commerce module).

In the view I set a contextual filter. But it just doesn't work as required.

It is very rare since the view is pretty simple.

Please take a look at the capture I've made:
 http://screencast.com/t/tgRPQQCm

The "Categoria" field is a Term Reference field type.

If I use other field as a Contextual Filter it works fine. Look: http://screencast.com/t/yspxMFxjA0k

Then there is something wrong with the field??

I do not have sound so not sure if I was following properly, but could it be that you are using a contextual filter rather than a regular filter?


How to programmatically create new user with custom fields? I want to create user with some custom fields. I have created extra fields through config > people > site information > manage fields and fields like first name, last name, city etc. I want to create user with this custom fields.

How can I create user programmatically?

Using user_save Drupal function you can create new users like so:

$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'john.doe@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
  //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);


What is the order of preprocess functions? I have started learning Drupal for few months. Now I'm doing some theming.

I would like to know the execution order of preprocess functions.

The order in which the preprocess functions are called in Drupal 7 is

template_preprocess
template_preprocess_HOOK
MODULE_preprocess
MODULE_preprocess_HOOK
ENGINE_engine_preprocess
ENGINE_engine_preprocess_HOOK
THEME_preprocess
THEME_preprocess_HOOK
template_process
template_process_HOOK
MODULE_process
MODULE_process_HOOK
ENGINE_engine_process
ENGINE_engine_process_HOOK
THEME_process
THEME_process_HOOK

Source : https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7


Fatal error: Maximum execution time of 240 seconds exceeded in sites/all/modules/memcache/memcache.inc on line 353 I am using multidomain site .
After adding a new domain record,
I was asked as follows: Content access permission needs to be rebuilt on this page.

When I clicked on Rebuild Permissions button,
the progress bar started the batch operation of rebuilding but in the midway it stopped and gave an error given below

  Rebuilding Content Access Permissions

  An error has occurred. Please continue to the error page An HTTP error
  0 occurred. /index.php?q=batch&id=433&op=do

I then searched an found an issue similar to the above in the link given below

https://www.drupal.org/node/399572

I found many solutions from above like :

Run rebuild permission via cron (did not try)
change theme  and move to older jquery version   (did not try as its live site)
I checked the settings for jquery update and had "minified" instead of "none", once set to the correct setting, it worked within seconds.

I was using jQuery update module with jQuery 1.4. This causes the batch to not update.

(did not try) To fix it, you have to prevent newer jQuery from loading when the URI contains "batch".

<?php
function node_access_rebuild($batch_mode = FALSE) {
  db_query("DELETE FROM {node_access}");
  // Only recalculate if the site is using a node_access module.
  if (count(module_implements('node_grants'))) {
//      if ($batch_mode) {
      if (FALSE) {
      $batch = array(
        'title' => t('Rebuilding content access permissions'),
        'operations' => array(
          array('_node_access_rebuild_batch_operation', array()),
        ),
        'finished' => '_node_access_rebuild_batch_finished'
      );
      batch_set($batch);
    }
?>

Not sure why this is happening to me, but I've found that I can just force node_access_rebuild() to not use batch mode by changing line 2314 of node.module from:
In node.module this piece of code, is setting time limit to 240 secs which might be still low than ur php.ini. You can try increasing set_time_limit arg to 1000 and then changing it back to 240 to keep code consistent.

 if (!ini_get('safe_mode')) {
        set_time_limit(240);
      }
      $result = db_query("SELECT nid FROM {node}");
      while ($node = db_fetch_object($result)) {
        $loaded_node = node_load($node->nid, NULL, TRUE);
        // To preserve database integrity, only aquire grants if the node
        // loads successfully.
        if (!empty($loaded_node)) {
          node_access_acquire_grants($loaded_node);
        }
      }
    }
  }

What I tried was increased the max_execution_time from 30 to 1000?
But still it did not solve the problem
Then finally I tried rebuilding permissions via drush

using drush command

drush php-eval 'node_access_rebuild();'

But that gave me the following error as shown below

PHP Fatal error:  Maximum execution time of 240 seconds exceeded in
sites/all/modules/me                                                                                mcache/memcache.inc on line 353

Does the above error means this is something to with memcache and will it be worth trying to disable the memcache and then perform rebuilding node access?

http://example.com/index.php?q=admin/content/node-settings/rebuild

Set max_execution_time = 0 in php.ini to allow unlimited execution times, and disable the set_time_limit() PHP function (also via php.ini) to prevent Drupal from self-limiting its execution time back to 240 s. Otherwise, you would have to find all the places where Drupal calls set_time_limit() and increase the values there or set them to zero.

(In Drupal 7, this got simpler through the new drupal_set_time_limit() wrapper function, which will not call set_time_limit() at all if the current time limit is 0 (unlimited). To be exact, this works since Drupal 7.40, and before was prevented by issue #2233929.)


How do I not cache dynamic content but cache everything else (or similar workaround)? I have a production site with page caching enabled (this is not negotiable). One very popular feature requires dynamic content to be queried from an external socket and displayed; this content is required to be fresh at all times and cannot be cached. Current implementation has a vanilla, non-Drupal .php script polling the socket, whose output is either pulled into the page via javascript, or put in an iframe if no js. The vanilla .php is not cached by Drupal, but the rest of the page (menus etc.) is cached. It's fast.

Due to new requirements, the hard-coded config in the vanilla .php must instead be configurable through the Drupal UI. I have a working admin implementation, and have brought the socket-polling code inside the Drupal module. It's slow.

Putting the dynamic content in a block with DRUPAL_NO_CACHE doesn't help, because the whole page is being cached, ignoring block-level settings. Excluding the whole page (including menus etc.) from the cache will not meet performance requirements. I don't think I can use the javascript/iframe trick again, unless there's a way to get Drupal to render a minimal uncached page without building any of the rest of the site. Using 'print $my_html;' in the hook_block_view rather than 'return $my_html;' renders a page with just the dynamic content, but it performs slowly enough that I think Drupal is doing a lot of unnecessary work. Is there a better way of rendering a very-minimal page while still having access to e.g. variable_get()?

Is there a better way to approach this? Being able to set block caching independently of its parent page caching would be nice...

(Using local dev servers, a fully uncached page takes about 1000ms to render. The 'minimal print-don't-return' page takes about 400ms. The actual module code for getting the dynamic content takes 6ms of this. A fully cached page renders in 20ms.)

"unless there's a way to get Drupal to render a minimal uncached page without building any of the rest of the site"

There's the clue - yes, there is. This is what AJAX callbacks do, after all. In your menu callback you print the desired output instead of returning it, and return NULL. IIRC, the result won't be subject to page caching either, but if it is, you can use the cache exclude module to ensure it is not cached.


Get site_name without html I've got a custom module that is sending some emails and I want to put the site name in the subject line, but whenever I look up the site_name in code, it is wrapped in html.

This is the code I use to generate the subject line:

$variables = array(
    '%site_name' => variable_get('site_name'),
    '%tags' => $params['tags'],
);

$subject = t('%site_name: Verify your Subscription', $variables);
error_log("subject=$subject");

In the email I received and in the error log, this is what $subject is:

liberalgeek.com: Verify your Subscription

Why is the site_name wrapped in html?

How can I either strip the html or lookup the site_name in a different way so that it doesn't have the html to start?

The problem is that you are using bad modifier for the t() function.

$variables = array(
    '@site_name' => variable_get('site_name'),
    '@tags' => $params['tags'],
);

$subject = t('@site_name: Verify your Subscription', $variables);
error_log("subject=$subject");

Note the @site_name change.
If you use

@site_name --  it will be run through check_plain and returns without any theming.
%site_name -- check_plain with theme_placeholder.
!site_name -- Allows all HTML.

Also note that this is not limited to site name. Whenever you use t() function, you should use above placeholder pattern to ensure CSRF-safe variable display.
Do not use t() function for use-entered variables. For an example, t($form_state['values']['name']); is bad!. Real use of t() function is when you use it with your own text and optionally user-entered data.

Good luck!


How to make rendered product variations show in a grid rather than a list? I need to present some product variations rendered in a grid, without any cart options.
The idea is to have the user click a link to the product and present a page with the variations.

The easiest way I manage to do this is: in content->manage display I only show the field:Product Variations, with the format:Rendered Product, which gives me exactly what I want. Except it is displaying the rendered variations in a vertical list rather than the nice grid like it shows by default in the product list view.

Where does the presentation of this rendered product variation elements come from?

I'm using the default theme:commerce kickstart omega.

You can quite easily create a View display to list your products in a grid.

Add a new View ( Admin > Structure > Views )
Add a page display
Add relevant filters for entity type etc..
Set the style to "Grid" layout
Tinker from there with fields etc..

That should do it.


How do I make the page created from my module visible only to anonymous users? I programatically created a page using the following code.

/**
* Implements hook_menu().
*/
 function page_prog_menu() {
   $items['page_prog/custom'] = array(
     'title' => 'My Custom page',
     'page callback' => 'page_prog_custom',
     'access arguments' => array('access content'),
   );
   return $items;
 }

 /**
 * Custom callback function.
 */
 function page_prog_custom() {
   $content['raw_markup'] = array(
     '#type' => 'markup',
     '#markup' => '
Hello world
',
   );

 return $content;
 }

I need to make this page visible only to anonymous users. How can I achieve this?

I have tried with hook_permission(), but it doesn't help.

/**
* Implements hook_permission().
*/
function page_prog_permission() {
  return array(
    'access page_prog content' => array(
    'title' => t('Access content for the pages created programatically'),
    )
  );
}

'access arguments' => array('access page_prog content'),


Show the view result only when users enter a value for the exposed fields I want that a view shows its result only when users enter a value in the exposed form fields. Is there a way I can get this done?

I am using AJAX, and the view is displayed as block. Most of the options I tried don't work because of this.

For each of your fields, in your view, you have the option Hide if empty. Select it to not display anything for the field if it is empty. Note that the field label may still be displayed. Check style or row style settings to hide labels for empty fields.


convert ' to html character I have this code:

$items[$k]->user->nome = $accounts[$item->uid]->field_nome['und'][0]['safe_value']." ".$accounts[$item->uid]->field_cognome['und'][0]['safe_value'];

And the output is this:

L&#039;itto Giovanni

But I want (in HTML)

L'itto Giovanni

in html head I have

 <meta charset="utf-8">

Where is my error?

"safe_value" is a "value", passed through the function _text_sanitize().

You can use php function html_entity_decode or use "value" instant of "safe_value". Differences between value and safe_value


Getting the error "$().once is not a function" till today noon my site working fine but after that suddenly my site was struck and in error console it give me below error.

  Error: TypeError: $(...).once is not a function Source File: modules/overlay/overlay-child.js?mixmsl on Line: 111.

/**
 * Modify forms depending on their relation to the overlay.
 *
 * By default, forms are assumed to keep the flow in the overlay. Thus their
 * action attribute get a ?render=overlay suffix.
 */
Drupal.overlayChild.behaviors.parseForms = function (context, settings) {
  $('form', context).once('overlay', function () {
    // Obtain the action attribute of the form.
    var action = $(this).attr('action');
    // Keep internal forms in the overlay.
    if (action == undefined || (action.indexOf('http') != 0 && action.indexOf('https') != 0)) {
      action += (action.indexOf('?') > -1 ? '&' : '?') + 'render=overlay';
      $(this).attr('action', action);
    }
    // Submit external forms into a new window.
    else {
      $(this).attr('target', '_new');
    }
  });
};

The standard $ alias is not used in Drupal 7, to provide the best possible support for no-conflict jQuery.

You need to wrap your code in a closure like so:

(function($) {
  // Add code using $ as an alias for jQuery here...
})(jQuery);

See Managing Javascript in Drupal 7 for complete examples and explanations.


How do I translate empty text of a view? I have created a view with empty text using PHP code. Now, when I try to translate it through the translation interface (admin/build/translate/search), while I find the string (it show up all the PHP code) and translate it (I did it by adding the PHP code again with the translated strings), when I change the language of my site I see nothing. When I come back to English, it showed up correctly.

Does anyone have any idea?

If this view is showing inside of a block then make sure you have the translation "Make this block translatable" is checked, and what ever language you want to translate to is also checked.
hope this helps.


How to get the url from uri, uri given as string I have a string

$directory = "/home/ .../sites/default/files..."

I tried to get the absolute url with:

$MYURL = Url::fromUri("base://".$directory);

That leads to an exception!

Can anybody explain hot to retrieve the url from a string?

Based on that string alone you'll never get a url. Do you mean how do you get the url of the current site?

In Drupal you don't need to. As Ivan recommended in his comment, you just need

This is the way to do it if the file was uploaded in Drupal and you have the uri.

file_create_url($path)
https://api.drupal.org/api/drupal/core!includes!file.inc/function/file_create_url/8

If you don't have the URI (for example you need to link to a file in your theme, then use:

drupal_get_path('theme', 'your_theme');

https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_get_path/8

Then combine that with a link relative to the theme instead of relative to the server root like your current $directory is:

$directory = "files/myfile.png";

Then jam them together:

$my_url = drupal_get_path('theme', 'your_theme')."/".$directory;

If you do need the full site URL for some reason, you should be able to use global $base_url;
(a global variable in Drupal) or check out https://stackoverflow.com/a/14500505/430191


Issues with a form validate hook I'm encountering an issue tying in a #validate hook into the Drupal registration form. In a custom module, I have a call to the User Register form (the form that is used on Account Creation) and an addition to #validate that should run an outside validation function.

/**
 * Implements hook_form_FORM_ID_alter()
 * Form ID: user_register_form
 */
function mymodule_form_user_register_form_alter($form, &$form_state) {
  $form['#validate'][] = "mymodule_validate_register_form";
}

function mymodule_validate_register_form($form, &$form_state) {
  //validation code
}

And on running a dpm of the Register Form, the validate statement is in place. However, it appears that the functions is never being run.

When I look at the #validate array, its the last option, predated by user_account_form_validate, user_validate_picture, and user_register_validate. Is it possible that its never being run due to the order of the other validate statements, or is there something wrong in my logic? Are there other approaches to validating the data during User Registration over the hook_form_FORMID_alter function?

This:

function mymodule_form_user_register_form_alter($form, &$form_state) {

needs to be this:

function mymodule_form_user_register_form_alter(&$form, &$form_state) {

Notice $form is by reference in the second snippet.


show nodereferenced nodes in view I have 2 node types: Authors and books. Authors has node reference to book node type. Created view:

Relationships - i have used reference field, in arguments i have used Node: nid (content id from node URL).

In fields i have used my noderef relationship.

in a node.tpl.php:

print views_embed_view('video', 'block_4', $node->nid);

But it shows nothing. (i have created 1 node author, and 2 nodes book)

Views 2, Drupal 6. What i am doing wrong? Thanks

The function views_embed_view is meant to be used to embed the view in a page or a block during the processing of a page. After the page processing is done, the results are passed to the theme engine. It is not meant to be used in the theming stage.

What you can do is create a region in your template where you want the view to appear, then create your view as a block and place it in that region on the Blocks admin page, following the insructions here;


Tokens for Profile 2 field I created a field for users using the Profile 2 module with machine name "field_user_country"

I created a block on my user profile page and i need to dynamically display the country of the currently viewed profile.

I have tried various tokens and they do not work.

What token can I use to get the country of the currently viewed user profile?

Thank you.

I'm having the same issue at the moment. Looking into including a few fields from a Profile2 content type into a Display Suite custom code field.

I used the following PHP code in the custom code field (using php filter format and enabling tokens, just in case). Then I was able to view a collapsed tree of all tokens available to that node.

You could prabably do the same in a block and have it displayed when you need it.

<?php
$output .= 'Available tokens:';
$output .= theme('token_tree', array('node'), TRUE, TRUE);
return $output;
?>

I'm sure there's a better way, but that quickly worked for me! gOOD LUCK.


How to define an image style where images are the exact same dimensions (e.g. grid of square images), without cropping or distorting the image? On my site, images of any shape can be uploaded, for example:

I want these to display in a grid where every image is the same size and shape (in my case, square) - due to the nature of the images, I don't want to use cropping and I don't want any distortion of the aspect ratio, but the backgrounds can be extended. This also needs to be applied to the image itself, not a CSS wrapper.

For example, I'd like the end result to look like this:

Everything I've tried using various combinations of "scale" and "resize" either doesn't give consistent final sizes depending on whether the original was tall or wide, or distort the image. Cropping isn't an option. How can I do this?

If you don't mind applying a block background colour, this seems to be possible with Imagecache Actions module.

Download and enable the Imagecache Actions module and its imagecache_canvasactions submodule.
Add a normal "scale" action to the desired size (300 x 300). This keeps the aspect ratio.
After, add a "Define canvas" action, then set to the same dimensions under "exact size".
Make sure "Resize canvas under image" is ticked, choose an appropriate background colour, and go. This fills in any gaps to the desired size with whatever colour you choose (or transparency if you choose no colour).


entityform list fitting to selected node After searching the web for hours I'm hoping to find the answer here for my problem.

So here is my goal:
I defined a content type, travel which contains a multiple values textfield for additional services and a entityform for booking additional services (e.g. train ticket to the travel starting point).
Each travel node has of course different number of additional services, after clicking on 'booking additional services' the form appears which should include a checkbox for each additional service to select by the customer.

I defined a text list in the form for the additional services.
Now my question is, how can I generate a list of additional services for the particular travel in my form.
I can only set the possible values for the list in the field settings but these values depend on the particular travel!

Could you give a hint?

Drupal uses static forms by default, therefor one step doesn't influence another step. You are probably looking for a thing called conditional fields.

You should be able to use the Conditional Fields module for this. Although I am not entirely sure it it works on all form types.