Why can Wordpress ship with latest version of jQuery but Drupal cant? Just a general question to as what holds Drupal back from being able to use the latest version of jQuery? I am guessing it is something technical but would like some details.

Even jquery update module only updates a few versions for Drupal 7 it goes for 1.4.4 to 1.5.2 while Wordpress ships with 1.7.1

Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.2 and jQuery UI 1.8.11

My understanding is that the version of jQuery gets locked down with the version of Drupal during development to ensure stability. It is all part of the testing process. The Drupal developers fully test the system before releasing a new major version of the CMS, including the JavaScript functionality. The incremental changes that go on throughout the year do not provide the time to test at this level so the jQuery version stays the same.

I am not very familiar with Wordpress, but my understanding is that they make considerably more regular major upgrades to the versions of their CMS. So jQuery gets updated more frequently. However, from what I've read little testing takes place.

While getting stuck with an old version of jQuery can be frustrating, I'd rather go for a stable well tested system.


What is the equivalent of theme_menu_item in Drupal 7? I know that in drupal 6 exist: theme_menu_item, but in drupal 7 there is not. Is there any replacements so that I modify the output for main system menu ?

Actually I want to do a kind of filter of the menu items depending some criteria, which I will set in the function.

Looking at the function that called the theme function theme_menu_item() (menu_tree_output()), and comparing it with the Drupal 7 version of the same function, I can say that the equivalent of theme_menu_item() is theme_menu_link().


hook_views_pre_execute not working I want to alter the view query before rendering the view, so I use the hook_views_pre_execute. I want to add an 'WHERE' 'AND' condition clause to the query. So here is my code :

MYMODULE_views_pre_execute(&$view) {
    // some code here to get my node id to exclude
    $view->query->add_where('1', 'node.nid', $nid_exclude, '!=');
}

but it seems to me the hook not working, or I did mistake to the add_wherefunction?

UPDATE : The hook is executed but the view is not modified.

To alter query you should use hook_views_query_alter

Sample Code using hook_views_query_alter :

function MODULE_views_query_alter(&$view, &$query){
switch($view -> name){
    case 'products':
        if($view->current_display == 'block_1'){
            $nids = get_nid();
            $nids = !empty($nids) ? $nids : array(0);
            $query->where[1]['conditions'][2]['value'] = $nids;
            $query->where[1]['conditions'][2]['operator'] = 'IN';
        }
            break;
  }
}


views grouping by field type in a row Here is what i get in views:

(first-row)
node1title
node1body

(second-row)
node2title
node2body

and this is what i want:

(first-row)
node1title
node2title

(node2-row)
node1body
node2body

is it possible to get it in a single view?

one possible answer is to add views php module add php code in for titles and then for body.


Problem dynamically calculating field I am using Drupal 6, Ubercart 2.7, and Views 2.16 for an e-commerce site.

Using Views with the Bonus: Views Export module, I am producing an atom feed for Google Shopping. This works perfectly.

I am trying to produce a second feed for a different currency, and for my purposes, it is OK to simply multiply the sell price by 1.1 and add the currency code onto the end of the value. However, I've hit a brick wall. I've tried the following options:

Theming

I tried creating a template file for that specific field (views-view-field--google-shopping-export--page-2--sell-price.tpl.php - lol). To get this working I had to change Field Output type to "Raw" for the feed, which caused all sorts of other problems. If Field Output was set to "Normal", the template was ignored.

Dynamic Fields

I tried using the Dynamic Field and Computed Field modules, but I couldn't get either of these working - both fields were empty within the feed when I tried to pull $node->field_sell_price in any way. This makes me think that I wasn't referring to the value properly, but I tried many, many combinations - $node->field_sell_price, $node->field_sell_price[0]['value'], $node->sell_price, $node->sell_price[0]['value'] etc. I was able to pull in $node->nid and $node->type, but nothing else worked.

Are there any other options to do this? Or have I missed something obvious in the solutions above? I feel like I'm making this much more complicated than it needs to be!

Thanks for any help.

Resolved this by writing my own module implementing hook_views_pre_render and manually changing $view->result.


Why wouldn't a .install file be loaded? My latest module does not seem to be loading .install when enabled.  Here's the rundown:

I have a .module file implementing hook_menu() and hook_views_data().

Both appear to work fine, after enabling the module: navigating to the menu path works as expected and my new views base type is present.

I have a .install file implementing hook_install() hook_uninstall() and hook_schema()

None of the functions in the install file appear to run.  The new tables are not present after enabling  and there are no errors logged.

If I manually call the functions in the .install file with devel THEN I get an undefined error.  I can only assume that the install file is not being loaded.

Running the .install file through the command line PHP interpreter doesn't bring up any syntactic errors.

I'm at a loss to explain why the file is not loaded into scope when the module is enabled.

I'd appreciate any assistance.

Turns out it was an error in hook schema() unfortunately the function failed more or less silently. For example :

'description' => array(
                'type' => 'varchar',
                'size' => 'normal',
                'not null' => TRUE,
                'description' => 'Description of vaule type.',
        ),

Failed.

'description' => array(
                'type' => 'varchar',
                'size' => 'normal',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'Description of vaule type.',
        ),

Worked.

The problem was exacerbated by my mistakenly assumed notion that disabling and re-enabling a module would trigger the install, rather then the removal of the module from the system table.

Thanks again to everyone who provided feedback.


MYTHEME_form_element_FORMID? I have an override for my theme called:

corporate_form_element()

The base hook was copied and tweaked. Multiple forms have to be modified and in some cases some individual elements did too. I typically get around this by checking conditionally whether markup is needed.

For instance I check for checkboxes and theme accordingly:

<?php
if($element['#type'] == 'checkbox'){
    return '
' . $output . '
';
}
?>

However now I wish to theme two text fields quite differently than most others in forms and I have discovered there is no way to detect which form the current call is for. I have "hacked" this by adding custom '#fields' in my forms elements (either those I provided explicitly or hooked into via hook_form_alter) and checking for this.

This works but is a horrible hack and not very clear.

What is the preferfed drupal way of achiving this result? Can I overrivde MYTHEME_form_element_FORM_ID or something similar? I know this can be done to MYTHEME_form_alter but what about individual elements????

Alex

Using custom properties is not an hack; quite the opposite, it is a perfectly fine way to achieve what you want. It allows you to identify the form elements that need to be altered, which is what you want.

In fact, custom properties are normally used from Drupal, which uses the following code for fields associated to an entity.

  $element = array(
    '#entity' => $entity,
    '#entity_type' => $instance['entity_type'],
    '#bundle' => $instance['bundle'],
    '#field_name' => $field_name,
    '#language' => $langcode,
    '#field_parents' => $parents,
    '#columns' => array_keys($field['columns']),
    '#title' => check_plain($instance['label']),
    '#description' => field_filter_xss($instance['description']),
    // Only the first widget should be required.
    '#required' => $delta == 0 && $instance['required'],
    '#delta' => $delta,
  );

Custom properties are also the Drupal 7 way to pass variables to theme functions. For example, the following code is using theme_table() to render part of a page.

  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. Add content type.', array('@link' => url('admin/structure/types/add'))),
  );

Passing $build to drupal_render() produces the same output produced by the following code.

$html = theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No content types available. Add content type.', array('@link' => url('admin/structure/types/add')))));

The alternative would be adding a #after_build or #process function to the form elements, but those functions are called before the form element is rendered, which means they can just alter the form element properties.

Those functions get access to the content of $form_state, and get $form_state['input']['form_id'] or $form_state['input']['form_build_id']. This is what the documentation for drupal_build_form() says about $form_state['complete form']:

  A reference to the $form variable containing the complete form structure. #process, #after_build, #element_validate, and other handlers being invoked on a form element may use this reference to access other information in the form the element is contained in.

To add a #after_build function (which gets $element and &$form_state as parameters), you should implement hook_element_info_alter() to change the form element definition.

Notice that theme_form_element() is defined as theme wrapper for every form element, similarly to what done with the following code for the textfield form elements.

  $types['textfield'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#autocomplete_path' => FALSE,
    '#process' => array('ajax_process_form'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );

As side note, every theme function has its own preprocess functions; for example, for theme_textfield() those functions are hook_preprocess_textfield(). They can suggest a different theme function to be used by adding values to the $variables['theme_hook_suggestions'] array. ($variables is the parameter passed as reference to the theme preprocess functions.) Unfortunately, the theme and the theme preprocess functions don't get any reference to the form being build.

References

drupal_build_form()
form_builder()
system_element_info()
theme()


What happens when a site goes in maintenance mode while a user is editing an node content? Let's imagine a user is editing a node content. In the mean time, a Drupal administrator puts the site in maintenance mode.

Does the user have a chance to save his work (assuming it does
not have the "Use the site in maintenance mode" priviledge)?
Is there a way to send them a warning, like 'maintenance in 5 mins'?

Thanks.

Unless you notify the editors about that, they will lose their work on that node. You can do that either by using some contrib modules or by creating your own custom module. Either way, I think you definitely need some kind of ajax solution so they can be notified even when they are on the node edit page.

You can check Privatemsg and Private Message Growl modules. I'm not quite sure how they work but they look promising.


Is it possible to define default config entities in a single yml file? Following drupal handbook I've created configuration entity type. All works fine except that I have to create ~100 default entities. It would be significantly easier to maintain these default entities if I could define them in a single YML file but that does not work as expected.

If I create files like this:

config/install/example.entity.id1.yml
config/install/example.entity.id2.yml
config/install/example.entity.id3.yml

The config entities are created correctly. However if I create one file config/install/example.entity.yml:

id1:
  field1: val1
  field2: val2

id2:
  field1: val1
  field2: val3

id3:
  field1: val4
  field2: val12

Drupal creates simple config with key example.entity. I'd expected it to create config entities as defined in schema file.

It would be real pain to manage those default config entities with 100 separate files instead of having everything in one yml file. Is this expected behaviour?

According to Configuration Storage in Drupal 8:

  Configuration Entities must each be put into their own YAML files, and they should be generated by having the module write out its configuration (don't try writing them by hand).

So it sounds like what you're experiencing is indeed the expected behaviour, and for the time being at least, you'll need to separate each default entity into its own YAML file.


Custom module visible only for one user EDIT:

14:38 PM Amsterdam :P

Nice to see that good people help !...

What I trying to do:

This is the whole prototype code.

function oleg_menu() {

    $items=array();
    $items['user/%user/pgacademy/tests'] = array(
        'title' => 'OLEG',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('oleg_nameform',1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function oleg_nameform($form, &$form_state,$accoundID) {
     $form=array();
     dpm($accauntID);
     return $form;
}

The page even doesn't appear...
Can someone explain me why it fails,or what could be the problem ?
Oleg

What indrock says in the comments is right, you should be using a placeholder like %user.

But you'll also need to pass the argument through to the form callback like so:

function my_module_menu() {
  $items['user/%user/foo/bar'] = array(
    'title' => 'My Title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_nameform', 1),
    'access callback' =>array('user_is_logged_in'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

The signature for my_module_nameform() would be:

function my_module_nameform($form, &$form_state, $account)

user_is_logged_in() doesn't accept any parameters so there's no need for the access arguments. Again as indrock says, clear the caches whenever you make a change to the hook implementation.


Getting only TID by Entity Query I am using Drupal 8. By retrieving an entity by Entity Query I am getting an array. How can I fetch directly the TID?

Right now I am doing the following:

  public function getCommuneTidByPostalCode(int $postalCode) {
    $commune = \Drupal::entityQuery('taxonomy_term')
      ->condition('field_zipcode', $postalCode)
      ->condition('vid', 'commune')
      ->execute();

    if (!empty($commune)) {
      return intval(key($commune));
    }
  }

Can I drop somehow this part?:

if (!empty($commune)) {
  return intval(key($commune));
}

No. An entity query always returns a list, if you want just one record, you have to get that from the array.

The intval() isn't really necessary though, Drupal/PHP doesn't care if you use the tid as string or integer. Also, it always returns an array, and key() also works on an empty array, so you can really simplify that to just return key($communie);. And I'd actually recommend to use current() or reset() because the key is the revision ID and the value the ID and while terms currently do not yet use revisions, they will likely soon support that.

So...

$commune = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_zipcode', $postalCode)
  ->condition('vid', 'commune')
  ->execute();

return current($commune);

Is all you need.


Features module working confusion I want to use features module. Can i use this module as stand alone and get it working or do i need help of modules like strongarm or context module. Will have have any added advantage if i user these modules along with features module ?  Any good flow chart of how to use features module?

You can use Features without additional modules. In fact, the module page is quite clear about it. Quote:

Features also provides faux-exportable functionality for the
following Drupal core and contrib components:
- CCK fields
- CCK fieldgroups
- Content types
- Input filters
- User roles/permissions
- Custom menus and menu links *
- Taxonomy vocabularies *

  * Currently in development.

In other words, these things can be exported using features out-of-the-box. That said, I recommend installing Strongarm right away, because some of the things above are lined to variables that you will want to export as well. For instance, if you export a content type, you probably want to export its comment settings too.


Tag Users and Taxonomy terms in body field of a post I am building a Social Networking site in drupal. My client requirement is to tag users and taxonomies using a '$'. For example "$john" will tag a user john with that post. and "$Arts and Entertainment" should tag the Taxonomy term to the post.

I tried hashtags module. But it is for tagging the words in body with a "#". The words are tagged under a separate vocabulary called "Hashtags".

My functionality needs twitter OR facebook like tagging of both users and Taxonomies(with a autocomplete Dropdown).

For tagging the taxonomies, I have created a separate field called Industry Tags of type Term Reference in that content type. This field will store the mapping of that particular node to the Industry Terms(Taxonomy Terms). Iam not going to display this Industry Tags field in the frontend. Instead of that i have to save the terms that user enters in the Body field prefixed with "$" to in this field. Example: "$Education".

Also for tagging users i can use "User Reference" in the same manner i mentioned above for industry tags. But i need the functionality to be something similar to twitter / facebook.

Please suggest me some ideas for implementing this.

It will be interesting logic to figure out whether $art is a user or the start of the $art and entertainment taxonomy term, but, regardless, what you are most probably looking for is an input filter that can recognize a pattern in the text and then both create a link to either the user or taxonomy term as well as actually tagging the node with that taxonomy term if it is one.

A start might be to take a peek at the Hashtags Module and change its use of # to $ for the taxonomy portion and then extend it to include users.


I cannot modify entity values I have installed the Views Bulk Operations module and am looking to use it to mass edit my content. However, when I select a few nodes to edit and select Modify Entity Values and click Execute, I get taken to a page that simply says, "The website encountered an unexpected error. Please try again later."

Unfortunately, my server logs and Drupal logs come up empty as to what error may have occurred.

Additionally, it seems like when I select Modify Entity Values, I should see an option for what entity value I am looking to modify but I am never presented with that option.

As an alternative, I found a guide that demonstrates how to replicate this behavior with Rules components but I have not yet been able to figure out how to make this work with taxonomy terms.

I would prefer however, to simply get the Views Bulk Operations to work as I would expect.

I finally managed to get this working. Under show available tokens, I previously had selected -- All --.

I have since changed this to be just the fields that I'm interested in having edited and it works as expected now.

My theory is that I have a lot of content types with a lot of fields and it was hitting some sort of memory error. However, I never saw an error reported.


How to teach PhpStorm to recognise drupal {table} SQL syntax? I'm dealing with some really old drupal project full of SQL queries. PhpStorm's understanding of SQL is very handy however I have problems with drupalism like {table_name}. IDE complains that <reference> expected, got '{'.

How can i set up PhpStorm so that it will understand that the string inside curly braces is just a table name? Or at least make it ignore the curly braces?

In PhpStorm Preferences > Tools > Database > User Parameters:

Check "Enable in string literals with SQL injection"
Add \{\w+\} to Parameter Patterns.

You may also want to modify the line with %\w+ to be allowed for language php for placeholders like %d. See screenshot and also JetBrain's PhpStorm blog post: Database Language Injection Configuration.


How can I prevent the display of CAPTCHA for other forms except the login form? I have Drupal 7.59 installed and CAPTCHA is visible for several forms. I want it visible only for the login form.

In this section: admin/config/people/captcha, I set the 'No Challenge' for other form-ID and login-form set on 'default challenge type' but the CAPTCHA gets displayed on all forms:
by this text : "CAPTCHA: NO CHALLENGE ENABLED".

How can I prevent the display of CAPTCHA for other forms except the login form?

The message "CAPTCHA: no challenge enabled" indicates, that the form in question is not protected by a captcha.

This message is shown to site administrators and users with the "Administer CAPTCHA settings" permission only. It is intended to ease administering captchas on the form. You could, e.g. click the message to open a link that allows you to enable a captcha for this form.

If you don't require these administrative links, you can disable them within the captcha module settings. In your administrative back-end navigate to Configuration > People > CAPTCHA.

Locate the option "Add CAPTCHA administration links to forms", uncheck it and save the settings. The administration links should be gone.


How are current anonymous users calculated? I have a site running Drupal 6. When I log in to add new articles, it shows Current Anonymous / Authenticated Users.

How is this number computed?

Have a look at what's written in Comment nr 5 of issue nr 799262, ie:

Basically, the anonymous user count in Drupal core's "who's online" block counts how many sessions are stored in the database, minus the number of authenticated sessions.
If you haven't correctly configured PHP to periodically cleanup the active sessions, the table will continue to grow. I just cleaned one today with ~75,000 old anonymous sessions. This not only causes confusion in the who's online block, but also has a severe performance impact on your site if it's mildly busy.
This article shows you what you need to put in settings.php to ensure your anonymous sessions are being cleaned: https://techcommons.stanford.edu/topics/drupal/sessions-table-cleanup


CSS, Omega theme - how to make a  use 2 or 3 grids depending on screen with? This question applies to Omega theme, but I think it is general to any responsive grid based theme.

Is there a method to make a <li> occupy either 2 or 3 grids, depending on screen width?

In other words, when the body tag has class responsive-layout-wide then the <li> should occupy 3 grids (as if it had omega class grid-3) and when the body has class responsive-layout-normal it should occupy 2 grids (as if it had omega class grid-2). (The body class is determined using media queries by Omega theme)

Currently the HTML looks like this:

<li class="mydiv grid-2-normal grid-3-wide"> </li>

At design time I don't know the screen width, so I applied both possible classes. So currently, despite of the screen width, the <li> width is always 3 grids because grid-3 is added last. Does Omega have any tools to make it dynamic?

The origin of this question lays here: http://drupal.org/node/1571938, unfortunately it is not explained to the end. The Views Columns Class module says:

  So you can apply alpha to the 1st, 5th, 9th blocks and omega to the
  4th, 8th, 12th blocks but also apply alpha-mobile to the 1st, 3rd, 5th
  blocks and omega-mobile on the 2nd, 4th, 6th blocks. This gives the
  freedom to the theme to apply the styles that would render a display
  of 2 columns for smaller screen resolutions and 4 columns for larger
  screen resolutions.

So, I will end up having multiple styles for a <li> (like e.g. grid-2-normal and grid-3-wide) and my theme is supposed to react to screen width and intelligently apply appropriate style to change the <li> width. Width measured in grids (columns), not in pixels. But how this can be achieved, how to render a display of 2 columns for smaller screen resolutions and 4 columns for larger screen resolutions? Where "display" means a view display, not the whole page layout (that's what I think)

I don't know if Omega can do this out of the box, but I don't think so.  Some base themes that use the grid system can change a size based on whether a column next to it is empty, but this isn't one of those conditions.

Your best option is to use the grid-2 size in the config for that region, and then if you want it to be different, put an override for mydiv in one of the sheets that get enabled by the media queries (narrow, normal, or wide).  In your case you would add something like

.mydiv { width: 280px; }

to yourtheme-alpha-default-wide.css  The actual width will vary based on whether you are using 12, 16, or 24 columns, and you may need an !important, too.


Updating my custom module to Drupal 7 I have updated a module from Drupal 6 to Drupal 7, but the following code doesn't work anymore. I have updated the .info file, but the module still doesn't work.

function header_image_block($op='list',$delta=0,$edit=array()) {
   if ($op=='list') {
     $blocks[0] = array(
       'info' => t('Header image'),
     );
     return $blocks;
   }

   elseif ($op == 'view') {
     $block = array(
       'subject' => 'Header Images',
       'content' => changeHeader(),
     );
     return $block;
   }
}

function changeHeader() {
  $output = '';
  $output = '';
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    $path = $node->field_head_img[0]['filepath'];
    if ($path != '') {
      $output = '';
    }
  }
  return $output;
}

In Drupal 7, instead of hook_block() there are more hooks:

hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()

In short, you need to split the Drupal 6 code for hook_block() between those hooks.

As side notes:

Every function implemented from a module should be prefixed by the module short name
To load the node, you should use the following code.

if ($node = menu_get_object()) {
  // The page is a node page.
}

To access the content of a field, you should use the following code.

$items = field_get_items('node', $node, 'field_head_img');
$path = $items[0]['filepath'];

To output an image, you should use theme('image'), or theme('image_style'). As you are outputting a field, you should use field_view_field(), as in the following code.

$output = field_view_field('node', $node, 'field_head_img');


In a Drupal 7 block, how to enable calling a Javascript function using behaviors I am trying to put code into a block that contains a Javascript onclick handler.  Have been trying to figure out how to use drupal_add_js, but cannot figure out how to make an onclick function work. I believe I may need to use Drupal behaviors.

I have read the documentation, but it is not clear. Here is what I am trying but doesn't work. Any help would be appreciated.

drupal_add_js('jQuery(document).ready(function() { $("#trial").click(function() { alert("Handler called." ); } ); } );', 'inline');

$ isn't defined in the global scope...you either need to use a closure:

(function($) {
  // Use $ safely here.
})(jQuery);

or use jQuery every time

jQuery("#trial").click(...

If you check the console you should see an error in there to the effect "$ is undefined".


problem with including external library Below I check for file existence and its exists.

$path = libraries_get_path('nusoap') . '/nusoap.php';
if(file_exists($path)) {
    print file_get_contents($path);
    die;
}

But when I try to include it I get 500 Internal server error.

$path = libraries_get_path('nusoap') . '/nusoap.php';
if(file_exists($path)) {
    require_once $path;
}

Owner and Group of all files are www-data

EDIT

[Mon Dec 24 12:59:12 2012] [error] [client 2.146.17.144] PHP Fatal error:  Cannot redeclare class XMLSchema in /sites/all/modules/fedora_store/nusoap/nusoap.php on line 2049, referer: http://127.0.0.1/fedora/store/transaction/2/mellat

When you get fatal web server/PHP error it is very useful to check the logs. Usually Apache logs are placed in /var/log/apache2/error.log but it may differ.

  Owner and Group of all files are www-data

I must warn you that www-data should not be an owner for most PHP files. www-data usually needs only read permissions. But it is not directly related to this question.


How can I add Google Tag Manager's code to my website? Is there any module to add some new things like Google Tag Manager's code to Drupal based website? for example you should install Google analytic module to add analytic to your site, is any equivalent for Google Tag Manager?

There is an officially released module (since early 2014): GoogleTagManager.

  Allow the non-technical stakeholders to manage the analytics for their website using the Google Tag Manager (GTM). This module allows you to trigger the insertion of tags and tracking systems onto the pages of the site.


Is there a way to hand-code a reference to a block?, in a .tpl file? Is there a way to hand-code a reference to a specific block?, in a .tpl file?

Specifically what i’m trying to do is this. I have a Drupal commerce site and the shopping cart contents are displayed via a block view. The contents are nicely hidden until the user mouses over a link.
This is accomplished via the Ajax commerce cart module.

My global nav is hand-coded via a block-myNav.tpl.php file.
So within the nav UL the pseudo code might look like

<?php print $my_block_reference here ?>

is that crazy? is there a way to accomplish this?

I'm guessing the down vote to what probably should be the correct answer to this post is b/c the answer did not have any code.

The way to render a block is:

<?php
  //D7
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block['content']);
?>

That can be placed in the template file that you want the block to show. See here for information on what the vars are in that snippet of code.


Insert Revision log message programmatically after form submission I am trying to pragmatically set the revision log message after values of certain fields are changed (thus if a user has edits certain fields). More information is in the code comments

 function home_hub1_form_alter(&$form, FormStateInterface $form_state, $form_id){

//    Hide Revisions log message text box
$form['revision_log_message']['#access']= FALSE;

//set revision check box to false since we are creating a revision progeammatically
$form['new_revision'] = array(
    '#type' => 'hidden',
    '#value' => FALSE
);

// monitor every field if its from edit
if ($form_id == 'device_entity_edit_form'){

    $form['actions']['submit']['#submit'][] = 'home_hub1_form_device_entity_edit_submit';

  }
}

function home_hub1_form_device_entity_edit_submit(array &$form, FormStateInterface $form_state){

$form_state->setTemporaryValue('entity_validated', TRUE);

//check if a field has changed and if it has write a revision log message
if ($form['field_city']['widget']['0']['value']['#value'] != $form['field_city']['widget']['0']['value']['#default_value']) {

    $message = 'CITY changed from: ' . $form['field_city']['widget']['0']['value']['#default_value'] . ' to: ' . $form['field_city']['widget']['0']['value']['#value'];

   $form_state->setValue('revision_log_message', $message);

}

I am getting the following error: Error: Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues()

I also tried to get the node object so that i create a revision directly from it like below:

function home_hub1_form_device_entity_edit_submit(array &$form, FormStateInterface $form_state){

$node = $form_state->getFormObject()->getEntity();

//check if a field has changed and if it has write a revision log message
if ($form['field_city']['widget']['0']['value']['#value'] != $form['field_city']['widget']['0']['value']['#default_value']) {

$message = 'CITY changed from: ' . $form['field_city']['widget']['0']['value']['#default_value'] . ' to: ' . $form['field_city']['widget']['0']['value']['#value'];

  $node->setRevisionUserId(\Drupal::currentUser()->id());
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setNewRevision(TRUE); // enabling revision for the entity save.
  $node->setRevisionLogMessage($message);

}

How can I create a revision after form submission?

I found the solution. I should have used hook_form_BASE_FORM_ID_alter() instead of hook_form_FORM_ID_alter

Also the call back function should be  home_hub1_my_entity_builder


In my Simplenews twig template how do I get the URL of the page I am emailing? When a single test newsletter is sent, Drupal provides me with the expected URL as follows:
{% set foo = url('<current>') %}

{{ 'You can view this news article in your web browser' }}

Or by using the trim Twig  function
But when sending the actual newsletter issue to subscribers, the batch process causes the url(‘current’) to provide a batch url like https://my-site.uk/batch
How can I obtain the one I want (to direct newsletter recipients to the page). Will a preprocess theme function see the same url values as twig or can I reliably capture the node’s real URL there Somehow?

This is better!

      You can view this news article in your web browser


Forms alter submit button callback not working I have managed to override a profile2 form using hook form alter. After adding a second submit button to the form successful an issue arose. I can not get the call back function to work. Below is the hook and the call function. Can anyone see a issue with the code?

function multi_step_form_form_profile2_form_alter(&$form, &$form_state){
          $form['profile_x']['field_personal_info']['submit']['und'][0] = array(
            '#name' => 'personal_info_alt',
            '#type' => 'submit',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
          );
}

function testing_to_see() {
  print'I am in call back ';
  exit;

}

Thanks for the responses. The reason I am trying to add another submit button is that the current profile page is using JQuery to hide and display some field collections that have been added to the profile page.

Currently when the user fills out the inputs in a fieldset and clicks next it only hides that fieldset and then displays the next fieldset.

Now each fieldset needs to save the data on the server each time you press next. So I found a way to add a submit button using the above code and to display the next fieldset by unsetting the array.

What I can't get the submit button to do when pressed is go to a call back function so I can manipulate the process to achieve this goal.

To answer the current questions below.

field_personal_info is adding the submit button inside the fieldset
multi_step_form is the name of the module

Expanding on my comment, be sure you have the correct form ID in the hook_form_FORM_ID_alter. This is an example of how I made this work. You'll need to modify the name of the hook and the FORM_ID

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

    $form['actions']['new_button'] =  array(
            '#type' => 'submit',
            '#name' => 'personal_info_alt',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
        );
}

function testing_to_see(&$form, &$form_state) {
  drupal_set_message('I am in call back');
}


Print url to image from profile2 field with mutiple images Hello guys i've been trying to figure this out the past 20 hours but i can't.
I want to print som image url's to a link.
I have this code

<?php
  $user_fields = user_load(24);
  $profile2 = profile2_load_by_user($user_fields->uid);
  $image = field_get_items('profile2', $profile2['side'], 'field_baggrundsbillede');
?>
<?php foreach($image as $key=>$value): ?>
 $output = field_view_value('profile2', $profile2['side'], 'field_baggrundsbillede', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail'
    'image_link' => 'content',
  ),
));

   <?php print render($output) ?>

<?php endforeach; ?>

But the problem is that it prints the image file, when i want an url.
How can i make that happen?

Thanks

EDIT

  <?php
    $uid = 24;
    $user_fields = user_load($uid);
    //$profile2 = profile2_load_by_user($user_fields->uid);
    $images = field_get_items('user', $user_fields, 'field_baggrundsbillede');
  ?>
  <?php foreach($images as $key => $image): ?>
    <?php $url = file_create_url($image['uri']); ?>
    <div class="background-image" style="background-image: url(<?php echo $url ?>);">

  <?php endforeach; ?>

To get just the path of an image, use file_create_url
To get the path of an image using an image style, use image_style_url

e.g, in the context of your code:

<?php
  $uid = 24;
  $user_fields = user_load($uid);
  $profile2 = profile2_load_by_user($user_fields->uid);
  $images = field_get_items('profile2', $profile2['side'], 'field_baggrundsbillede');
?>
<?php foreach($images as $key => $image): ?>
  $url = file_create_url($image['uri']);
  // $url = image_style_url('medium', $image['uri']); // example image style url

   <?php print $url; ?>

<?php endforeach; ?>


Display a view inside a  and I have a view that outputs list items as links. Like so

Link 1
Link 2
Link 3
Link 4

I need to be able to wrap those items in

And close them. However when I attempt to do this in the template. Or in a basic page that is using a function to display the view.

When I attempt

        <?php print views_embed_view('mobile_slide_menu','block');?>

I end up with

Link 1

Link 2

Link 3

Link 4

Which doesn't work for my list. Is there any way to take only the list items and prevent it from being wrapped in all those containers. And if not is there a way to append the opening and closing tags of 'nav' and 'ul' within the view?

A tutorial with more detail can be found here tutorial. But in short what you want to do is the following:

Find the correct .tpl file and copy it into your theme. Edit the .tpl in your theme and remove the wrappers.
Don't forget to flush caches after inserting a new template. All the template files are in the sites/all/modules/views/theme folder (depending on where exactly you installed views). There are quite a lot of them and the view templating is quite complex, luckily views helps you with a list to find the right one.

You can find the list of template names you can use in the views interface (where you edit your view) under the advanced tab.
Look for the Theme: information item. Clicking it will give you the list of all the .tpl files this view would use if able (ordered from most general to most specific and highlights the current one).

Note

Be as specific as possible to prevent accidentally breaking other views (rename the template file if to match the name in the list).
more about the view templates


Use taxonomy terms to set node access for a user I have a vocabulary with two terms.

Vocab: A

Terms: b,c

I use them in two places.

  First in the registration: in the config->account->fields.
  And second one of my content type.

Now I want when a post tagged as b Just people that they are tagged with "b" in the registration can see that post.

And when a post tagged as c just the users that tagged as "c" can see the post.

Can I do this with context module?
How?

I don't think you can set this up with Context.

There is Access by Term where grants (view, update, delete) are based on the relationship between the user->term<-node.


What is the performance impact of modules that use Field API instead of a custom way of accessing the database? This answer states that it is better to share fields among content types when possible because each field added slightly negatively impacts performance.  Assuming this answer and my interpretation of it is correct, for nodes that already have lots of fields for unavoidable reasons, would avoiding the use of modules that make use of the Field API when alternatives are available enhance site performance?

For example:

Meta Tags instead of Meta Tags Quick

That can't be answered in a generic way, I think. Some facts:

Each field does add a certain overhead to the system and it means more queries when loading and saving e.g. nodes.
Being able to store information as a separate entity that has the information as properties is obviously much faster than having everything in fields.
However, modules that stores additional information to entities on it's own tables results in additional queries as well.
The advantage of field API is that the storage is pluggable, so you could for example use it together with MongoDB which could possibly drastically improve the performance, with some drawbacks however.
Fields also have read cache built-in so that subsequent entity loads will use the cache to load the field content. A module that does not use fields might not have it's own custom caching.
There is still the generic overhead added by fields but work is ongoing to improve that situation in Drupal 8 and it might possibly be backported as well.

So a module isn't more performant just because it uses fields for storing data or not, there are many more factors and it also depends on how the site is configured.


Pluralize Flag/Unflag Link Text I want to rewrite the link text for Flags such that it includes the number of flaggings for that node, as pluralizing the output.

e.g.

1 Flag
3 Flags

I can get as far as getting the flag count and pluralizing the output using a field rewrite, but the Ajax link breaks, and the field can no longer be clicked to flag or unflag the node.

I've tried the dlike module, but this doesn't seem help with pluralizing the flag/unflag link

I found I was able to do this by changing the flag link text (in the flag configuration) to [node:flag-machinename-vote-count], which gave the number of flag for that node.

Then, modifying line 57 of the flag theme file: flag.tpl.php to

<a href="<?php print $link_href; ?>" title="<?php print $link_title; ?>" class="<?php print $flag_classes ?>" rel="nofollow"><?php print format_plural($link_text, '1 Flag', '@count Flags') ; ?>&nbsp;

Note that this is actually only changing the small php snippet that displays the link text to us the format_plural function:

this <?php print $link_text; ?>

to this <?php print format_plural($link_text, '1 Flag', '@count Flags') ; ?>


Setting Drupal Image Field via Services, and image won't attach to node? I'm uploading an image via my iOS app and setting a created node's image field to the image through Drupal Services. Everything appears to be correct (see uploaded photo from 'Recent Logs'). However when I navigate to the node, the image field is empty? Any idea as to why this might be? All help is appreciated, thanks.

I'm late to the party, but I think you might be encoding the image wrongly. You need base64 encoding. Here is how encoding works on my end with Python 3.5.2:

import os, base64
size = os.path.getsize(filename)
filesize = os.stat(filename).st_size
filemime = mimetypes.guess_type(filename)
fd = open(filename, 'rb')
image_data = base64.b64encode(fd.read())
fd.close()


Token for field in field collection I have a field collection with 3 fields (title, image and link). I'd like to link the title and image to the value of the link field.

I'm using the linked field module to make the fields linkable and enabled the token module. Yet the fields from my field collection aren't in my available tokens list. They also can't be found in admin/help/token

How do I link a field from a field collection to the value of another field from that same collection? Or how do I find the correct token?

I found the solution in enabling the entity_token module. This expanded my available tokens list to include the fields within the field collection.


How can Drupal be made to serve with root-relative paths? I'm trying to avoid serving pages that load css and js resources through URLs that specify either http or https.  (I'm trying to find a workaround for the problem described in this question, in case a real solution cannot be found.)

Because Drupal is specifying http:// for the href for all the CSS and JS files, when the server erroneously switches to https, as described in the aforementioned question, the browser seems to be ignoring all these files, and I get an unstyled page.

Instead of

<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

(etc.)

I'd like to serve

<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

or even

<link type="text/css" rel="stylesheet" href="//www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

Can I make Drupal serve URLs that don't specify protocol?

You can use a template process (YOUR_THEME_process_html) hook to rewrite all resource urls (js and css) using a regular expression.

Here is an example which transforms all http:// or https:// to //:

function YOUR_THEME_process_html(&$vars)
{
    foreach (array('head', 'styles', 'scripts') as $replace) {
        if (!isset($vars[$replace])) {
            continue;
        }

        $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
    }
}


How to set proper permissions for drush rsync I have a weird problem here. When I use drush sync for my remote server, Drush changes permissions for the uploaded files to the name of the remote user for both the user and the group on the system.

The remote server is an Apache-FPM install where the name & group of webroot files have to be owned by vu2003:vu2003. Is there a way to achieve this with the aliases.drushrc.php?

Here Is my aliases file:

$aliases['live'] = array(
    'uri' => 'pts1.tk',
    'root' => '/var/www/virtual/pts1.tk/htdocs',
    'remote-host' => 'pts1.tk',
    'remote-user' => 'publisher',
    'os' => 'Ubuntu',
    'path-aliases' => array(
    '%drush' => '/usr/share/php/drush',
      '%drush-script' => '/usr/bin/drush',
      '%dump-dir' => '/tmp',
      '%files' => 'sites/default/files',
      '%private' => '/var/www/virtual/pts1.tk/000_private',
     ),
    'databases' =>
      array (
        'default' =>
        array (
          'default' =>
          array (
            'driver' => 'mysql',
            'username' => '[placeholder]',
            'password' => '[placeholder]',
            'port' => '',
            'host' => 'pts1.tk',
            'database' => '[placeholder]',
          ),
       ),
     ),
     'variables' => array(
        'site_name' => 'Drupal',
      ),
     'command-specific' => array (
       'sql-sync' => array (
         'no-cache' => TRUE,
       ),
     ),
  );

 $aliases['default'] = array(
      'root' => '/var/www/d7',
      'uri' => 'drupal.dev',
    'os' => 'Ubuntu',
    'path-aliases' => array(
    '%drush' => '/usr/share/php/drush',
      '%drush-script' => '/usr/bin/drush',
      '%dump-dir' => '/tmp',
      '%files' => 'sites/default/files',
      '%private' => '/var/www/html/private',
     ),
    'databases' =>
      array (
        'default' =>
        array (
          'default' =>
          array (
            'driver' => 'mysql',
            'username' => '[placeholder]',
            'password' => '[placeholder]',
            'port' => '',
            'host' => 'localhost',
            'database' => '[placeholder]',
          ),
       ),
     ),
     'variables' => array(
        'site_name' => 'Drupal',
      ),
     'command-specific' => array (
 'sql-sync' => array (
         'no-cache' => TRUE,
       ),
     ),
  );

The easiest solution would be to set 'remote-user' => 'vu2003', and set up the ~/.ssh/authorized_keys for that user to allow the rsync to run.


Managed file: What is the proper way of setting #default_value? $form['picture']['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('picture'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#default_value' => (isset($foo->picture->fid) ? $foo->picture->fid : ''),
  '#upload_location' => variable_get('picture_upload_location'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);

I have the above code snippet from here.  It's very useful, however I'm having a hard time setting #default_value.

What is $foo?  Where is it set and how can I change it?  Will I use the image uploaded on the other pages (coded in the same module).

Welcome to Drupal Answers. You just need to pass the fid integer value to the default value. To better understand what is fid see below description.

  fid is Unique File id that is stored in the database for each and
  every uploaded file using Drupal File System.

So, if you want to set default image then it should be uploaded via Drupal File System. Ideally, you need to store fid of the uploaded file in a variable using variable_set in submit handler and do variable_get in default value to set fid. That's it !!

Hope it answers :-)


Views only used for not logged user Is there a way to only display a view result for Not Logged user.

If yes, How I could perform this.

I'm using drupal 7

Thanks a lot

In view's settings (Page settings/Block settings) find Access. Change Permission to Role and select appropriate role (anonymouse)


Canonical link for multidomain multisite I have different domains in a site in Drupal 7, which is multidomain and multilanguage, using modules Domain Access and i18n. I have duplicate content in some URLs accross domains, and I want to avoid Google penalization by following the recommendations of using

<head><link rel="canonical" href="CANONICAL_SOURCE_URL" />

I will use a custom module. For the nature of Drupal 7, I undestand that I can check each node, and using the node->id and database call, to check the domains in which the node is active. Following an order of preferred domains, I will know that URL to set as the canonical.

Is that a good aproach? I have tried module MetaTag with Canonical, but it uses a wildcard approach so it repeats the domain in which I am, so we can have www.example.com/link1 and www.example.us/link1 as canonicals, when only one of them should be used.

How can I override MetaTag with my own link rel tag ?

It is better to use Metatag module which has ability to override meta tags on each entity objects. Other tokens must be used.


How to make a particular role user and their content not accessible/viewable to other users? How do I make the user page (/user/uid) of a particular role (PendingFreelancer) and the content they create not accessible/viewable to other users?

Content Access

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Video Tutorial
I think content access is only for content type nodes. So for the user page umm.... I can't think of anything of the top of my head. I will edit this if I can think of something. Perhaps the only solution is doing it with a custom module programmatically.

If you use pathauto you could make so the user page path is user/[user:role]/[user:name]
then you could use
Path Access

Path_access provides the means to restrict pages based on their path
alias - meaning you can lock out certain user role groups from whole
sections of a site using wildcards.

and lock them out from certain [user:role] paths.


Drupal 8. Imce module show thumbnails instead of a filename Is it possibility to show thumbnails instead of a filename in imce file manager? Just not see any options for this..

Short answer: No

Long answer: This seems like it existed in the 6.x branch of the module as a "Box View", but in 7.x it looks like it's been dropped. See here for the 6.x discussion. And there's a ticket for 7.x too, with 0 activity.

Edit: Serhiy found out that for D7 there's a template file which can be modified to display thumbnails instead of a list.


Automatic base URL not picking up https:// My Drupal site is using https:// but the base URL is not using it.

My site therefore is not opening properly. Is there any way to make Drupal pick up the correct base URL?

I tried adding $base_url in settings.php but it's giving me this error:

  GET https://example.com/js/admin_menu/cache/6599fa6c7ea0ac232a88eaa63e957878 404 (Not Found)

Try setting the $base_url on the protocol:

  $base_url = ((isset($_SERVER['HTTPS'])) ? 'https://' : 'http://') . 'www.yoururl.com';


How to send a notification to admin on profile picture change? I want the new uploaded pictures to be sent (notification) to me (admin) for review and approval just to be sure they are in line with the terms and conditions of the webpage. Naked or semi-naked pictures are strictly forbidden.

How can I achieve this?

I suggest you try to use a combination of 2 approaches, as further detailed below.

Approach 1 - Prior approval required

If you'd use the the Profile 2 module, then the Profile 2 Moderation module, which depends on the Profile 2 module, enables moderation on user profiles. Here is a (self explaining?) screenprint from its project page.

Be aware however that, as mentioned on the project page, it requires a Profile revisions patch.

Approach 2 - After the facts

Use the Rules module to be informed about all sorts of updates that you're interested in, similar to what's detailed in my answer to "How to send an eMail notification when a specific field of a node or user has been changed?".

With this approach, and as per all the great things you can do with this module, your options are virtually unlimited. This approach also allows you to implement this type of moderation using a granular approach: start small, maybe only using a few custom rules, and keep refining them and continue adding new ones.

Not to forget all the available integrations with tons of other modules, of which the Flag module is probably your very first priority to also add that module for what you're trying to implement. Just a basic usecase about this:

Use Rules to flag any user for which some profile update happened.
Use Views to build a list of such flagged users.

If you'd only implement these 2 bullets of this approach (a matter of minutes, say an hour at max), you'd already have a Version 1.0 of your User Profile Moderation Dashboard (call it your MVP if you prefer ...).

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.


Is it possible to use %user_uid_optional as a view path? I am using %user_uid_optional in the path of a view, but it doesn't seem to be working because the tab is not showing. It looks like that the user_uid_optional_to_arg function is not being called. Do you have any idea?

When declaring a views path, you can only use '%'.
This is because Menu API can't handle two loader functions in the same path, and Views already has its own (that loads the view itself).


File upload via REST returns 403 I've been attempting to get a file to upload using REST services and have been having a heck of a time getting it to work. All attempts come back as 403 (Forbidden).

Here's the code:

export const postImage = async file => {
  const url = "http://XXXXXX.com/entity/file?_format=json";

  const reader = new FileReader();

  reader.readAsDataURL(file);

  reader.onload = async e => {
    const body = {
      filename: [{ value: file.name }],
      filemime: [{ value: file.type }],
      filesize: [{ value: file.size }],
      type: [{ target_id: "image" }],
      data: [{ value: Base64.encode(e.target.result) }]
    };

const requestObject = {
  body: JSON.stringify(body),
  method: "POST",
  mode: "cors",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: "Basic XXXXXXXXX",
    "X-CSRF-Token": "XXXXXXXX"
  }
};

const response = await fetch(url, requestObject);

const data = await response.json();

return data

I have been able to properly POST with content just fine using the same authentication. Setup for File in REST is just like with Content (JSON, basic auth). The account I'm posting from has full admin privileges. Any help would be greatly appreciated.

I was missing the File Entity module. Installed it and was good to go.

Also, was having trouble when using normal json format. Switched to hal_json and that got it.

It's also worth noting that using Base64.encode is unnecessary because FileReader does that for you. Also, you need to split off the file type from the returned data string, otherwise the file will be corrupted when you go to upload it.


Drupal.t() does not work I am tring to use Drupal.t() within some javascript, and I am not able to do it.

Actually, it throws no errors, Doing something like :

console.log(Drupal.t('supplier'));

returns 'supplier', even though I am in another language and the alternative value was supplied for such language (The PHP code with the t() function works).

Extra question : Is there a way, to know from Drupal Javascript utilities the current locale, I am in ?

At the moment, I found a workaround by testing the following (pure jQuery) :

if(jQuery('body').hasClass('i18n-fr')){//so that we can
 locale = '/fr';                       //make localized ajax calls.
}

Cheers,

Any ideas ?

After using Drupal.t(), clear the cache once, and search text to translate from admin/build/translate/search.


How much time does it take to manage sites within a multisite architecture as compared to multiple single installs? A service my company offers is similar to managed hosting where we help keep a server, Drupal, related modules, and backups up to date on behalf of clients who can't or don't want to do that in house, and typically this averages out to be about 30 to 90 min of work per site per month.
A client has asked me to manage their entire portfolio of 70 Drupal sites, all of which are part of a multisite architecture with site files on one server and DB on another.
I can't imagine that this is 70 hours of work, but I'm not familiar enough with multisite installs of this size to understand fully what this would entail.
To ensure that I estimate time correctly, what would I need to take into consideration when comparing management solutions for single server / single site installations as compared to the same number of sites in a multisite installation?

Short: It really depends.

Long: Each individual multisite installation adds complexity to the whole. If these 70 sites are more ore less the same in terms of individual content but (nearly) same codebase, modules and similar themes (imagine a large organization spread over the world with region specific characteristics), you'll most likely need less time to maintain.

If these are 70 profoundly individual sites, you'll probably end up checking dependencies over dependencies for modules and themes, debugging deadlocks and incompatabilities. Maintaining this can be a real challenge and 70 hours a month are gone faster than you have "drushed and rollbacked" everything to working.

Accurate documentation and a SLA designed fair for both parties should be the key to a successful maintenance.

(I maintain a multisite installation with around 30 instances for a large organization with all the pros described above.)


Integrate core search block with search_api and Solr Since search_api does not rely on the core Search module, the search bar (Search Form block) isn't used.  For a current project I want to use search_api, but the wireframes require the search bar at the top of the page.  The apachesolr module overrides that block so that it uses the Solr search instead of the core search when you specify that Solr is the default search.  Is there a way with search_api to enable the core Search Form block and have it use a specific search page?  In addition, you would also need to be able to keep the core Search module from indexing everything into the db, since that partially defeats the purpose of using Solr, but I'm guessing I could just form_alter that form (admin/config/search/settings) to add a 0 value.

Thanks.

I think he/she means http://drupal.org/project/search_api_page provides search blocks automatically.  You could also create view that provides that block.

You could also replace the core Search module with Search api + http://drupal.org/project/search_api_db.


Migration not found - D8 Following this I have created a module to migrate d7 users to d8. I have enabled all mandatory modules needed to run migration. But when I do drush migrate-import {mymigrationid} ; it says : Migration not found.
But When I did "drush config-list|grep migrate" , it is showing that particular migration:

migrate.migration.d7vm_users
migrate_plus.migration.custom_user

But when I'm doing drush migrate-status, these migrations are not listing up there.
Can anyone tell what's supposed to get missed?
Here is my mymodule/config/install/vm.yml file
id: d7vm_users
label: User accounts
migration_tags:
  - Drupal 7
dependencies:
  enforced:
    module:
      - mymodule
source:
  plugin: d7vm_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  timezone: timezone
  langcode: language
  init: init

and src/Plugin/migrate/source/User.php
<?php
/**
 * @file
 * Contains \Drupal\mymodule\Plugin\migrate\source\User.
 */

namespace Drupal\mymodule\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Extract users from Drupal 7 database.
 *
 * @MigrateSource(
 *   id = "d7vm_users"
 * )
 */
class User extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('users', 'dcf_u')
      ->fields('dcf_u', ['uid', 'status', 'created','access', 'login',    'name',
        'pass', 'mail', 'init', 'language']);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'uid' => $this->t('Account ID'),
      'status' => $this->t('Blocked/Allowed'),
      'created' => $this->t('Registered date'),
      'access' => $this->t('Time of last access'),
      'login' => $this->t('Time of last login'),
      'name' => $this->t('Account name (for login)'),
      'pass' => $this->t('Account password (raw)'),
      'mail' => $this->t('Account email'),
      'init' => $this->t('init'),
      'language' => $this->t('language'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'dcf_u',
      ],
    ];
  }

}
?>

If your source plugin extends SqlBase, you need to make sure you have the database configuration set up correctly. Otherwise Migrate will silently ignore the migration.

In your settings.php or settings.local.php, add the following database configuration:

$databases['migrate']['default'] = array(
  'driver' => 'mysql',
  'database' => 'NAME OF YOUR SOURCE DB',
  'username' => 'YOUR DB USER',
  'password' => 'YOUR DB PASSWORD',
  'host' => 'localhost',  // change this as necessary
);

By default, Migrate looks for a DB connection named "migrate". If you use any other name, the migrations won't appear when you run drush migrate-status.

Note: The "migrate" connection is in addition to your "default" connection. You should have two connections in your settings if you're migrating from a MySQL database.

In case anyone's curious, the DB connection check occurs in the method SqlBase::getDatabase() in drupal/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php.

This is documented in https://www.drupal.org/node/2830031 and apparently will be fixed in Drupal 8.4.


Linking Custom Content Types Together I'm attempting to create a site that lists my brother's DVD releases.

I've been able to do this with Views, but I would like a more user friendly interface so I don't have to administer the site in the future, and my brother can do it himself.

Basically I have two Content Types:  Releases, and Scenes.

When creating a Release, I want (my brother) to be able to select Scenes that have already been added, and arrange them in a specific order as though they are a Custom Field in the Releases Content Type.

I don't think Views out of the box is friendly enough for my brother.

Any ideas, modules, hints, or search keywords that might help me engineer a solution?

A reference module is what you're looking for. References is the standard right now, though there are other options such as Entity Reference.

To use your reference module, add a "node reference" field to your Release content type. When configuring that field, allow it to refer only to nodes of the "Scene" content type.

For the sort order, I believe if you use the autocomplete widget for your nodereference field then it should give you sorting capabilities on the Release node-add form, without needing another field in the Scene content type or any more work in Views. Just make sure when configuring the nodereference field that you set the number of allowed node references to "unlimited".


List nodes within a date range I am looking for a solution which displays node list within the date range. Requirement is to display events from today to next 6 days group by date. I have a content type "Agenda" with a date field enabled. So the display should look like:

  2 Jan 2012
      -- 8:00 AM Agenda A
      -- 9:00 AM Agenda B
      3 Jan 2012
      -- 8:00 AM Agenda C
      -- 9:00 AM Agenda D
      4 Jan 2012
      -- 8:00 AM Agenda..
      -- 9:00 AM Agenda..
      5 Jan 2012
      -- 8:00 AM Agenda..
      -- 9:00 AM Agenda..
      6 Jan 2012
      -- No events scheduled
      7 Jan 2012
      -- No events scheduled

I tried with the Views module and the Calendar module also, but I don't want to display in calendar style format, and I need to display only these 6 days (now +6 day), not the entire month view. Other styles are not fulfilling my requirement.

Here I have display 6 dates and display node/event associated with its otherwise display "No events".

Could you please suggest something?

I'm assuming you know how to filter the view to get the nodes based on the date and date + 6, but are having troubles grouping them together on output by date.

I see you are using D7, but to do this in D6, you would add the date field twice in the view and override one of these with a template to output just the day in question and group on that now simplified field.

A good article on that is http://drupal.org/node/388140 which shows you how to do it by month; to do it by day just change the date function to include it as well.

I would imagine D7 is very similar, and that this helps out.


Access to private file only from website, not using direct link My private files has a visible URL like the following: https://mywebsite.com/system/files/myimage.jpg.

How can I restrict access to the file, so it cannot be viewed directly from this URL but only from link on my website?

I have tried to use SESSION as follows.

$_SESSION['file-access'] = TRUE;
$output = theme('image_style', array('style_name' => 'foto_preview', 'path' => $uri));

Then I controlled in hook_file_download() if the SESSION key 'file-access' exists, but the session key never exists.
The image I wish to display is the value of an image field. I cannot use $user because I wish to display private files also for anonymous users.

Can anybody help on how to restrict the direct access to a private file, but allow access from website?

EDIT 30.7.2013: my mistake, using sessios works OK, I had a mistake in another unrelated part of code. The problem is solved.

You need to use private filesystem as shown in documentation. Then you can create custom module to implement more advanced rules, like link timeouts et cetera.


Commerce Feeds - Taxonomy term processor Issue Using Commerce Feeds version: 7.x-1.3

I am running the "taxonomy term processor". I have tried every available combination for "Update existing terms" (Do not update existing terms, Replace existing terms, Update existing terms . . . even Skip hash check - 'checked' and Skip hash check - 'unchecked').

No matter what I do, the csv import file that I am uploading just adds to what I have already imported. If I am uploading the same file and have added additional terms, I would think there would be a way of JUST adding the new terms, not duplicating everything again.

Am I missing something or is this a bug?

Thank you!

Tom

Tom, I found your question today while fighting the same problem in the standard Feeds module.  In the Processor > Mapping setup, do you have fields set as unique targets in the "target configuration" column?

In my system, I found that even though I had tried to set the imported column to be a 'unique target', that setting had not been saved. After going through the process of setting unique targets, updating the column map, and saving again, the duplication problem has now been solved in my system.


Drupal::httpClient() and proxy settings I've defined a proxy in my settings.php:

$settings['http_client_config']['proxy']['http'] = 'http://ip:port';
$settings['http_client_config']['proxy']['https'] = 'http://ip:port';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

In real I've replaced ip and port with nummeric values.

In a custom module I've defined:

$client = \Drupal::httpClient();
//$request = $client->get($this->source_url.'service=wms&request=getcapabilities');

These works, when Im not behind a proxy. How, can I add the proxy settings to this request?

$set =\Drupal\Core\Site\Settings::get('http_client_config');
$proxy = $set['proxy'];
//Get GetCapabilies.
$client = \Drupal::httpClient();
$request = $client->get($this->source_url.'service=wms&request=getcapabilities');

I don't find any way to add the proxy settings.

You can pass all http client config to the "client factory". You can also include your own custom settings.

$settings = \Drupal::service('settings');
$clientConfig = $settings->get('http_client_config') ?? [];
$client = \Drupal::service('http_client_factory')
                   ->fromOptions($clientConfig);


How to discard unsaved changes to a variant? While working on a variant for /node/%node I did something that now causes a 'The requested page "/admin/structure/pages/edit/node_view" could not be found.' error and am unable to access any of the variants.

How do I discard all the changes since the last save?

Finally got the answer from a Drupal guru- just deleted an entry from the ctools_object_cache table in the database. Everything works fine now.


How to check payment successfully? I use module ubercart. Payment method is PayPal. I want process some task after user payment successfully. I write custom module. I want know how to check user payment successfully with some hook, event can catch?

I have the answer with suggestion of maintainer module. I can use hook_uc_payment_receipt_insert() to do that.

/**
 * Implements hook_uc_payment_receipt_insert().
 */
function uc_payment_uc_payment_receipt_insert(PaymentReceiptInterface $payment) {
  $order = $payment->getOrder();

  // Log a message against the order.
  $method_name = $payment->getMethod() ? $payment->getMethod()->getPlugin()->cartReviewTitle() : t('Other');
  $log_message = t('@method payment for @amount entered.', array('@method' => $method_name, '@amount' => uc_currency_format($payment->getAmount())));
  $order->logChanges(array($log_message));

  // Automatically mark paid orders as "payment received".
  // @todo Remove when Rules is available.
  if (uc_payment_balance($order) <= 0) {
    $state = $order->getStateId();
    if ($state == 'in_checkout' || $state == 'post_checkout') {
      $order->setStatusId('payment_received')->save();
    }
  }
}

Source


Hook not firing for custom entity -- how to set theme suggestions? I have an entity whose machine name is orb_act.  This code is not firing in Drupal 8:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_orb_act_alter(array &$suggestions, array $variables) {

  // Add template suggestions based on the current view mode.

  $suggestions[] = 'orb_act';
  $suggestions[] = 'orb_act__' . $variables['elements']['#view_mode'];

}

How do I set my template suggestions?

The theme system doesn't know about entity types by default. You need to implement hook_theme() yourself at the moment. You likely also need a preprocess function to define a few standard things.

The console project generates this when creating a new entity type through it, you could try that to see how it looks. Otherwise look at what node module does in node_theme() and template_preprocess_node().


Generate form from XML I have a standard form structure with fieldsets etc. I'm trying to populate my form into various nodes. This means that the same form will be displayed on more than one nodes. For every node, the form's fields will be enabled or disabled. This depends from XML files where it is described which fields will be enabled or disabled. This is a complex problem where i don't know how to start searching.

I'm not sure about D8, but for a D7 site I would read the XML file within a hook_form_alter() function, and use this to select enabled or disabled each form element depending on the rules set forth within the XML.

Of course as lovely, or convoluted as that sounds, it's a pretty nasty performance hit to show a form so caching would be important here.

I hope I understood your question correctly.


Validation on textfield I have gotten my validation module to kind of work, I have this:

function product_id_form_validate($form, &$form_state) {

if($form_state['node']->field_product_id['und']['0']['value'] == '123'){
    form_set_error('field_product_id', 'Product ID: is taken');
}

}

But when I change the value in field_product_id the value doesn't change upon save, it stays the same as when I first entered the form. Is there a function I need to call to say, when I click save look at this field again?

Thanks

Submitted values are stored in the $form_state['values'] array so you need to test that instead:

if ($form_state['values']['field_product_id'][LANGUAGE_NONE][0]['value'] == '123') {
  ...
}


Using exposed filters as part of the rendered page's title I'm using exposed filters in a Drupal 7 site. I'd like to make the selected items from those filters part of the titles. Is there a way I can get the text value of those selected filters and use that text as part of the title?

Settings are as allowed:

I'm also using Better Exposed Filters in this view.

A also have this question. But now I'm trying this module: https://drupal.org/project/exposed_filter_data?
And this module is not working for me.

I found this:

/**
 * THEME_PREPROCESS_VIEWS_VIEW
 * @param type $vars
 *
 */
function MYTHEME_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'viewName') {
    // get var from GET
    $obj_type = $_GET['obj_type'];
    if (isset($obj_type)) {
      // obj_type is the taxonomy term, get taxonomy term name
      $tax_name=taxonomy_term_load($obj_type)->name;
      // if taxonomy term have parents
      $tax_parent = taxonomy_get_parents_all($obj_type);
      if (isset($tax_parent[1])) {
        // add parent name to taxonomy term name
        $tax_name =  $tax_parent[1]->name . ', ' . $tax_name;
      }
      //update title
      $vars['view']->build_info['title'] = $tax_name;
    }
}

And this is working!


How to get the "label" of "Allowed Values" for a text list programmatically? I created a text list field on the user entity.  I entered the following for Allowed values list:
apple|A delicious apple
pear|A very delicious pear
orange|A not so delicious orange

I can access the key for the field like this:
$current_user->get('field_list_fruits')->value,

which returns apple.  But how do I get the text A delicious apple programmatically?

Load the field config and look for the key/value pair from the allowed value list?
Much easier though is using the field formatter for this field type OptionsDefaultFormatter:
$build = $user->field_foo->view(['type' => 'list_default']);

What you do with $build depends on the use case. Put it in a render array to be rendered later or
$output = \Drupal::service('renderer')->renderPlain($build);

if you need it now and can't wait until the page is rendered, for example if you want to send an email.


Override login page with Panels I want to override the login page using panels. I found a tutorial that shows me how to do it using Panels Everywhere, but that overrides the whole page (with site_template).  I just want to override the page content.

Is this possible?

You can override existing paths with the Page Manager Existing Pages Module.

I have not used it with a login page but it works well for other cases. You can use it to override an existing page's path and then add the original content for that path as a panels pane alongside your custom additions.


Caching interfering with jQuery and drupal behaviors? I'm on the new side to coding so this is mysterious to me:

On several sites that I'm working on the jQuery library stops being added through drupal behaviors spontaneously as javascript and module files and page templates are altered.  Once the site cache is cleared through drush the behaviors properly call jQuery again.

I work with 3 others, and though our database is centralized our file trees are local. We use git for version control.

Any information as to why this caching incident keeps happening would be very helpful.  I'm trying to learn more about the caching process but so far I haven't found anything that clears this up.

Just like when you add a menu item or some theme elements, you need to clear the cache when you add new javascript.

For a site in development mode you can simply turn off caching so that you don't have to remember to clear the cache every time ('drush cc all' is handy):

Drupal 6: /admin/settings/performance: Caching mode set to disabled

Drupal 7: /admin/config/development/performance: Uncheck cache pages for anonymous users

Disabling "aggregate javascript", will make it much easier to debug your js with chrome or firebug.


How to prevent Rules scheduled within a month may have an offset that is off by 1 or 2 days? I have been using Rules to send out emails to users based on their user role. Based on the role, they should get emails at different times based on an event.

Whenever a rule is triggered in a month with more or less than 30 days however, the offset doesn't seem to work and my scheduled events are one day off. In the case of February (with 28 days), it's even two days off.

I'm assuming this is because after 30 days it calculates it as a month? I'm at a loss as to how to fix this.

These schedules are tied to certain events and should always be triggered a certain number of days after the event start date.

Understanding the issue

The explanation for what you're experiencing can be found in the description of the (open) issue about "Dates are poorly handled". Here is part of what it includes:

/**
 * Defines possible duration multiplier.
 */
function rules_ui_element_duration_multipliers() {
  return array(
    1 => t('seconds'),
    60 => t('minutes'),
    3600 => t('hours'),
    // Just use approximate numbers for days (might last 23h on DST change),
    // months and years.
    86400 => t('days'),
    86400 * 30 => t('months'),
    86400 * 30 * 12 => t('years'),
  );
}

From the above code, it's obvious that there may be a discrepancy of some days if scheduling a rule X months from now (every month is assumed to have exactly 30 days, which is not the case of course). Similar problem when using years, and also a (minor) problem of 1 hour when using DST.

Making it work for MONTHLY executions

So far the bad news ... the good news is that there is a work around for this. If you use the Rules Once per Day module, you can take advantage of these additional facilities of this module (as mentioned on its project page):

  The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

  From version 7.x-1.1 there is now a "Day of the month" condition, too.

With that, you should be able to adapt any rule to perform its Rules Actions only once a week, or once a month.

Making it work for YEARLY executions

But, there is even more, for those cases where you want a rule to only execute once a year, you can use a Rule as explained in this issue and which looks like so:

Create a rule triggered by the "Once per day" event
Add a "Current day of the month" condition:

Comparison "equals"
Day of the month value "1"

Add a "Text comparison" condition:

Data selector "site:name" (dummy text, not used)
PHP evaluation "return date('m');" ( ! )
Matching text "^01$" (for January)
Comparison operation value "Regular expression"

The above logic will ensure that your Rules Action(s) are executed on exactly the 1st of January of every year (adapt the "1" and/or "January" to fit whatever other day of a year).

( ! ): I admit, this solution (only required for "YEARLY" though) requires the PHP filter to be enabled, which I try to avoid at any cost (I've not found an alternative for this yet ...).

PS: I'm assuming this question is about D7.


Unable to create multi-site sub-directory in drupal I need help creating multi-site sub-directory in drupal. I have done all setting changes in localhost windows wamp server don't know what is missing.

let say, mysite is a main site and project1, project2 sub directory. Sharing same code base but different database.

In hosts file i have done the changes like this.

127.0.0.1 project1
127.0.0.1 project2

created project1 and project2 folder under sites folder and added setting files

     DocumentRoot "C:/wamp/www/mysite"
     ServerName project1

Its working fine for http:// localhost/mysite/ and http:// project1/,http:// project2.

But I want to show it in sub-directory like http:// localhost/mysite/project1 or http:// localhost/mysite/project2.

I have tried with doing Apache alias as well and it is point to relevant DB also but when I clicked any links from http:// localhost/mysite/project1 it will show an error message.

You don't need to alter the hosts file if you don't care about serving on more than one address. If you have an Apache vhost entry for 127.0.0.1/localhost (you will by default, and I think Apache will add a hosts entry for 127.0.0.1) then if you have a public_html dir at mysite you can just dump any number of Drupal installs under that dir.

E.g.
/home/niklp/public_html/index.html <- get this working, then you can do:
/home/niklp/public_html/drupal1
...
/home/niklp/public_html/drupalx

Sorry if this is a little vague but it's not a Drupal issue, it's an Apache config thing that should be easily resolved.

Edit: you will have a billion less issues if you get off windows and onto linux even for basic setups.


What is the ID or class for the Wizard Page name? In Webform 8 I am using the Attachment PDF / Entity Print to send a PDF of the submission via e-mail.

I am able to target the field labels, fieldset and webform-elements to add CSS but cannot find the correct ID or class for the wizard page titles.

Where do I find it?

Each wizard page is rendered as details element.

Below is the Entity Print markup from the webform_example.module's 'Example: Wizard'.

<details
 class="webform-container webform-container-type-details js-form-wrapper form-wrapper"
 data-webform-element-id="example_wizard--information"
 id="example_wizard--information"
 open="open">
   <summary
     role="button"
     aria-controls="example_wizard--information"
     aria-expanded="true"
     aria-pressed="true">
     Your Information
     </summary>
   <div class="details-wrapper">
   ...
   </div>
</details>


Checkboxes: how do I set the default values or show the user defined values using Form API? I am using an checkboxes element within a form in module that I started developing for Drupal 7. This is my first attempt at module development and using the Form API. I am creating a list of checkboxes that list down all the content types of a specific site. An array of all the content types can be obtained by using the following: $nodeTypesRaw=node_type_get_names();. An array with the machine names of the content types as the keys and the human readable names as the values are obtained.

By default, I would like all the checkboxes to be selected and when the form is submitted. How do I achieve that? The Form API pages on the drupal site aren't very helpful with regards to setting the default values for checkboxes.

$nodeTypesRaw=node_type_get_names();
$nodeMachineNames=array_keys($nodeTypesRaw);
$form['process_comments']['custommod_published_comments_select_node_types']['custommod_published_comments_node_types_checkboxes']=array(
          '#deafult_value'=>$nodeMachineNames,
          '#options'=>$nodeTypesRaw,
          '#type'=>'checkboxes',
);

I initially started out with the above code, but it won't work. It does display the list of checkboxes, but they are not checked by default. The variable does get on form submission though (checked via drush and var_dump).

From Drupal.org:

$form['element_id'] = array(
  '#type' => 'checkboxes',
  '#options' => array(1 => "One", 2 => "Two", 3 => "Three"),
  '#default_value' => array(1, 3),
);

Default value is set as an array representing keys of selected options.

Looking at the code in your question, problem is with spelling. you are setting '#deafult_value' when you want to set '#default_value'.


how to print a form in twig where a variable number of form elements have been printed already? I am using a Twig template to render a form that has a variable number of elements.
Each element's key in the form is sequential integer.
So in my template, I can do this:
{% for item in form|children %}
  {{ item }}
{% endfor %}

However, then I have a broken form, because there's no <FORM> HTML element, or the form ID for submission.
I've looked at twig templates for forms in core, but they all work with fixed elements, so they're able to do something like this, seen in modules/content_moderation/templates/entity-moderation-form.html.twig:
{{ form|without('current', 'new_state', 'revision_log', 'submit') }}

If you look at form.html.twig in the Drupal Core's system module, you'll see:
{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

Using this as a guide, you should be able to do:
<form{{ attributes }}>
  {% for item in form|children %}
    {{ item }}
  {% endfor %}
</form>

children is already a variable in the template so you can just use it like:
<form{{ attributes }}>
  {% for item in children %}
    {{ item }}
  {% endfor %}
</form>

But if you're not wrapping the individual children, why even use a custom template? Why not just use the default form.html.twig.


How to restore complete database keeping the site in maintenance mode in Drupal 7 I need to restore complete database in a regular basis (weekly). I am using pure PHP + system call to mysqldump and mysql to backup and restore full database. The restore process takes 2 minutes. What would be the correct procedure in order to keep the site in maintenance instead of getting a Drupal database error? Is there some sequence of table restoration?

For example, I use UPDATE variable SET value = 's:1:\"1\";' WHERE name= 'maintenance_mode';" just before the restoration, but obviously as there is a DROP TABLE if exists maintenance_mode in the SQL backup file, the site will show an error instead of the maintenance screen for a moment, and maybe in more occasions if there are incongruences among the different tables as they are updated.

I was thinking of controlling the process with the .htaccess, forwarding all traffic to a static HTML maintenance page.

Update: I have created my own module as there are many other tables which are outside Drupal and the product has to be specifically integrated with the requirements of the customer. So I cannot use the Backup and Migrate module (as suggested in one of the answers).

Add a maintenance-page--offline.tpl.php page to your theme , and whenever the connection to DB is lost drupal will show this page instead of an error , but designing this page you cant use formal variables which are used in theme like $title or $styles and ... cause these are stored in DB and in your situation there is no access to that , so you must add them using php or just implement some strings .

Check this page for more help : Theming the Drupal maintenance page


Filtering among Exposed Filters : Parent/Child relationship between two Exposed Filter in Drupal View I wanted to make a page with exposed filter search app in Drupal for a list of people.

I started by creating content type Bio and populated it as following:-

Then, I continued making a view with exposed filters of the fields of content type Bio. With the help of Better Exposed Filters, I am showing both Filters through Checkboxes through AJAX, as below:-

Now, until now, it's working fine. when I select a region or/and any city, the content updates according to that.

What I am hoping to create is a dependency between the region and city. All I want is that when I select any region in the Filter by Region, the lower filter values in the Filter by City automatically adjust and show me only the cities for which the region field in Bio is the selected city.

As an example, If a user selects EMEA, the city exposed filters should only show European cities.

I have been stuck in this for hours now. I have tried various solutions (View Dependent Filtersand Filter Fields) but to no avail.

I'll be therefore very thankful for any help whatsoever.

Look at my currently developing site's exposed filter(where 'Бренд' and 'Модель' fields): Link

If you want to achive this kind of functionality then you can achieve it like this. First you need to alter exposed filter function:

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-VIEWS_NAME_VIEWS_DISPLAY') {
    if(!empty($form_state['values'])) {
      $form_state['input'] = array_merge($form_state['input'],$form_state['values']);
    }

    // Marks
    $mark_childs = populate_terms_by_vocab('transport_models', TRUE, FALSE);
    $form['field_adv_mark_tid']['#options'] = array('All' => t('--Выберите')) + $mark_childs;
    $form['field_adv_mark_tid']['#ajax'] = array(
      'callback' => 'adv_mark_callback',
      'wrapper' => 'model-wrapper',
      'effect' => 'none',
      'progress' => array(
        'type' => 'throbber',
        'message' => '',
      ),
    );
    // marks end

    // Models begin
    $selectedMark = isset($form_state['input']['field_adv_mark_tid']) ? $form_state['input']['field_adv_mark_tid'] : NULL;

    if($selectedMark != NULL || $selectedMark != FALSE) {
      $model_childs = populate_terms_by_vocab('transport_models', FALSE, $selectedMark);
    }
    elseif($selectedMark == NULL || $selectedMark == FALSE) {
      $model_childs = array();
    }

    $form['field_adv_model_tid']['#options'] = array('All' => t('--Выберите')) + $model_childs;
    $form['field_adv_model_tid']['#prefix'] = '
';
    $form['field_adv_model_tid']['#suffix'] = '
';
    // models end
  }
}

// This is an Ajax callback for $form['field_adv_mark_tid']['#ajax']
function adv_mark_callback($form, $form_state) {
  return $form['field_adv_model_tid'];
}

// This is a helper function which returns terms (suitable for form selectlist, checkboxes or radios..)
function populate_terms_by_vocab($vocabulary_machine_name, $only_parents = TRUE, $parent = FALSE) {
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_machine_name);
  $terms = array();
  if($parent == FALSE) {
    $terms = taxonomy_get_tree($vocab->vid, 0, NULL, FALSE);
  }
  elseif($parent == TRUE) {
    $terms = taxonomy_get_tree($vocab->vid, $parent, NULL, FALSE);
  }

  $child_terms = array();
  foreach($terms as $key => $value) {
    if($only_parents && $terms[$key]->parents[0] == 0) {
      $child_terms[$terms[$key]->tid] = $terms[$key]->name;
    }
    elseif($only_parents == FALSE && $terms[$key]->parents[0] != 0) {
      $child_terms[$terms[$key]->tid] = $terms[$key]->name;
    }
  }

  return $child_terms;
}

I thinks the logic is the same.. In my case, I am adding to my entity type the two same term reference fields, and on content creation form I am displaying them as different parent field and child field (with pre-render function). By that, first field is holding the top level terms, the second field is holding child terms. And by views ui I am exposing them separately. And, that piece of code is displaying them as I want..


Why does hook_menu() not show my items in menu? Here's my code and I can't get why hook_menu doesn't work. My block menu doesn't showing in menu. As I understood this code (hook_menu()) should show link in which for will work drupal_post_form using function instance_export_form.

So I mean that when I follow admin/config/content/instances_export I get just content menu list, not a form which I need

    <?php

function instances_export_block_info()
{
    $blocks['instances_export'] = array(
        'info'  => t('Instance export'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );

    return $blocks;
}

function instance_export_menu()
{
    $items = array();

    $items['admin/config/content/instance_export/settings'] = array(
        'access arguments' => array('administer site configuration'),
        'title'            => 'Configure export',
        'description'      => 'Chose what you want to export and where',
        'page callback'    => 'drupal_get_form',
    );

    $items['admin/config/content/instances_export'] = array(
        'title'            => 'Form to export data',
        'page callback'    => 'drupal_post_form',
        'page arguments'   => array('instance_export_form'),
        'access arguments' => array('administer site configuration'),
    );

    return $items;
}

Here info file

 name = Instance export and import module
    description = Allow to export synchronize few instance of Drupal
    core = 7.x
    version = «7.x-1.0»
    configure = admin/config/content/instances_export
    files[]=instance_export.module

There are a few things that look out of place there:

Your module name is instance_export so you should not use instance_export_form as a function name because Drupal will think that you are defining hook_form() and you will run into problems. Best to use function names that are less likely to clash with other modules.
The menu item admin/config/content/instance_export/settings is using drupal_get_form() as the callback but isn't passing in any form ID as 'page arguments'
The menu item admin/config/content/instances_export uses the page callback drupal_post_form(), which is not a Drupal function. I assume you want drupal_get_form() here also.

Something like this should work better:

function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instances_export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

Note that I made up a form function for the first menu item (instance_export_settings_form) and changes the one for the second menu item (instance_export_export_form). This would be whatever you want your functions to be.

Also, if you want these pages to be tabs in your module's admin area do it like this instead:

function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'type'             => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['admin/config/content/instances_export/export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
    'type'             => MENU_LOCAL_TASK,
  );

  return $items;
}

I'm assuming that your hook_block_info() is not relevant to this question.


Display term refference field in node I have term refference in user fields. I would like to show under name of author's node that field.

I try this code:

<?php print $node_author->field_NAME[$node->language][0]['taxonomy_term']; ?>

But this won't work.

Anyone can help me?

Thank you!

You can adjust some of the settings of a field on the 'manage fields' tab of the content type configuration.

To position or further manipulate the output of a particular field in the template, edit node.tpl.php and where you want your field to appear, add

if(!empty($content['field_term'])) {
  print render($content['field_term']);
}

(Or if your field isn't called 'field_term', whatever your field's name is.)