How do I use a template file for preparing HTML message body for emails? I want to use a template file for preparing the email message body using the table tag, and putting the submitted form data by user in table rows. I have implemented hook_mail() with the following code.

function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      $message['body'][] = $params['message'];
      break;
   }
}

I created a template file (get_price/templates/mail-to-eberhard.html.twig), but the message body is not using my template file.

How do I make Drupal 8 use my template file?

So here is the answer:
Inside the hook theme function of your module use this code

function get_price_theme() {
  return [
    'mail_to_eberhard' => array (
        'template' => 'mail-to-eberhard',  // TWIG File
        'variables' => array('submitted_data'=>[]),
    ),
  ];
}

where variables is the array of parameter you want to send to the template file. Now create a template file named as mail-to-eberhard.html.twig inside your modules template folder.
Then inside the hook_mail() alter function use this code.

function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      //$message['subject'] = t('Article created: @title', array('@title' => $params['node_title']), $options);
      // Render the template to HTML
      // Set up email template
      $body_data = array (
         '#theme' => 'mail_to_eberhard',
         '#submitted_data' => $params['message']
      );
      //$message['body']['#theme'] = 'mail_to_eberhard';
      $message['body'][] = \Drupal::service('renderer')->render($body_data);
      break;
  }
}

now inside you template file you can use the array variables like this

You have received one new message from the Get Price Tab.

Full Name : {{ submitted_data['user_full_name'] }}

Email : {{ submitted_data['user_email'] }}

Phone : {{ submitted_data['user_number'] }}

State : {{ submitted_data['user_state'] }}

Product SKU : {{ submitted_data['product_sku'] }}

Product URL : {{ submitted_data['product_url'] }}

Message : {{ submitted_data['user_message'] }`


Bootstrap Views Accordion Problem I am trying to create a website. For this website, Ι am using the bootstrap business theme (Bootstrap Business Demo) of the good people of More than just Themes. I have also downloaded and enabled the Views module and the Views Bootstrap module.

I have created multiple views, all of which have as content types articles: one of them is the view studies, another one is named announcement and another one is called events. Along with these views, I have created their assorted blocks.

The blocks are customized as follows:

  Format
  : Bootstrap accordion using fields

  Fields: Content: Body , Content: Title

The problem:

I have set the blocks (three blocks each representing a different view) to appear in the themes' second sidebar. When I press the elements of any block different from the top one, the top blocks' collapse effect of the corresponding item is activated instead. That is, if I press the second accordion item of the third block, the second accordion item of the first block will be expanded(if it doesn't exist, then the second item of the second block will be expanded etc.).

The proposed solution:

I think I know why this is happening. I am currently working on the how. I used the inspect element feature of my chromium browser and came up with this:

Studies block, first element:

     Study 1

Announcements block, first element:

     Announcement 1

Events block, first element:

     Event 1

Although their data parent is different (views-bootstrap-accordion-[1-3]), all of these items reference the same collapse0 id(?) element. I am currently trying to figure out the css(?) file these point to and see if I can fix this, either by tweaking the module (views bootstrap) or the theme(bootstrap business).

Any help would be mush appreciated.

Came across your post considering I had the exact same problem. I had several different attached views to my page that were grouped by different taxonomy terms.

The way I fixed it is a little janky, but it works... basically edit the Views Bootstrap module in sites/all/modules/views_bootstrap/templates/accordion/views-bootstrap-accordion-plugin-style.tpl.php and store a random integer in PHP as a variable with rand(); then append that variable to the $key on your accordion-toggle  tag as well as the "collapse" div.

It should work after that.


Run feeds importer from outside the site I have a Feeds importer that's running periodically (with cron) using "Feeds Fetcher Directory" fetcher. Now I need to run the importer on demand from other app outside the site. Is there a way to just run the importer (not cron) in a similar way as cron does? (going to some url)

I'm using Drupal 7.53.

Thanks!

Since version 7.x-2.0-beta3, Feeds has Drush support. You could use the following command to trigger an import (where 'my_importer' is the machine name of your importer):

drush feeds-import my_importer

If the importer is attached to a content type, specify also the feed
node with the option '--nid':

drush feeds-import my_importer --nid=2

Note that a source for the importer in question must exist*. So you need to have gone through the import form at least once.

You could write a shell script that executes the drush command and that is triggered when the url is requested.

*The drush command 'feeds-import' has more options, allowing you to perform an import even when no source was created yet. But I don't think that applies in your situation. See https://drushcommands.com/drush-7x/feeds/feeds-import for more information.


Saving a default value when using entityMetaDataWrapper->save() I have an entity that I import some data into, then create and save via entityMetadataWrapper->save().

When I looked on the form, it appeared that a default value that I set up for a field that I'm not importing was being saved, but later when I try to use that field, it's null in the code.  If I go to my entity and save it, then the default value is saved and all is right with the world.  Is there something special I need to do before save() to tell it to use my default value and actually save it?

The default value is used for the widget form only, it won't be automatically set if you use node_save or a metadata wrapper. You see it in the form when you edit the newly created entity because there's no value for that field, and Drupal dutifully fills in the default value. It doesn't update the value of that field on the entity, just populates the form input.

You'll need to populate it manually, but you can get the right value with the field API:

$instance = field_info_instance('node', 'field_foo', 'article');
$default_value = $instance['default_value'];


Programatically accessing block settings Is it possible in Drupal 7 to load block visibility settings programatically in module? I'm rendering block programatically and I want to include checking those settings, so it still will be possible to hide block from UI. Property of "status" and "visibility" are not enough, since it's possible that the block won't be placed in any region at all.

Sure, block_load gives you the contents of the whole row from the block table:

$block = block_load('module', 'delta');

$region = $block->region;
$weight = $block->weight;
$custom = $block->custom;
$visibility = $block->visibility;
$pages = $block->pages;
$title = $block->title;

And so on.


Organising content using Taxonomy and Views I'm just starting out with Drupal and I'm interested in how to display my content and organise it in the site.

I can see that creating basic pages I can use the Menu module to add them to the hierarchy of the menu, but is this the only way to organise content?

I'm trying to learn the Views module, which is complicated! But it seems more logical to me to create a custom taxonomy and then use the Views module to display a subsection of that taxonomy.

Is this possible?

Yes it is possible. You should learn Panels too. Panels works very nice with Taxonomy and Views. Try lullabot video tutorial about views, very good.


Reloading option in a select list with ajax So here is my problem:

I have a form so users can create orders. There is a 'Client' select list where they can select the client of the order. When we select a client, we use ajax to load client info (address, tax rate, discount ...) and populate some field. This works fine.

I am now adding a feature to be able to create directly a client from the order, in a modal.
So I have a button in the order form, that triggers ajax to open a modal and render the new client form:

  $account_form = drupal_get_form('mymodule_creation_account_custom_form',$form['field_client']);
  $output = drupal_render($account_form);

  $commands = array();
  $commands[] = ajax_command_invoke('div#createClientModal','foundation',array('reveal', 'open'));
  $commands[] = ajax_command_replace('#new-account-form-placeholder',$output);
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

Then I fill in the info, and submit the account from the modal:

  $account = my_module_new_account_form_submit($form, $form_state);

  $form['client_hidden_field']['und']['#options'][$account->nid] = $account->title;
  $form['client_hidden_field']['und']['#default_value'] = $form['client_hidden_field']['und']['#value'] = $account->nid;

  $commands = array();
  // Closing the modal
  $commands[] = ajax_command_invoke('div#createClientModal','foundation',array('reveal', 'close'));
  $commands[] = ajax_command_replace('.field-name-field-client', render($form['client_hidden_field']));
  $commands[] = ajax_command_invoke('.field-name-field-client select','change');

  // Replace the form with an empty div
  $commands[] = ajax_command_replace('div#account-form-wrapper','

');

  return array(
    '#type' => 'ajax',
    '#commands' => $commands
  );

So what I am doing in this last submit, is creating the new account (that works), it returns me the nid. Then, as I have stored in a variable ($form['client_hidden_field']) the client field, I update it with the new option, select the option, replace the old client select list with the new one, and trigger change to call the old callback that loads a client info when it is selected.

I have tried lots of thing and each time I select the new client created, I get an 'Illegal choice'. I have tried without default value, without triggering a 'change', in JS with a command_invoke and nothings seems to work.

The only success I had was :
I do all these step, I manually select a client (one already existing before), and then select the new one. After that I didn't have the 'Illegal choice' and was able to save. But this is not a way to make it work.

If someone has any idea, I would love your help !

Thanks

Ed

Have you tried with $form_state['rebuild']=TRUE. It will help you to update your changes while adding new client.


No results behavior in Views not working when referencing another field after cache clear My Setup:

I am using Drupal 7.41 and Views / Views UI 3.11.

I have a taxonomy named sermon series that includes a field called series image.
I have a content type called sermons that has an image called sermon image and a term reference to the sermon series taxonomy.
Lastly, I have a View called sermons that:

pulls in the most recent 1 node from the content type sermons
has a relationship to the taxonomy sermon series
has the first field in the fields list as the sermon series image (from taxonomy) and is set to "hide from display". The replacement pattern token for this field is [field_sermon_image_2]
has the second field in the fields list as the sermon image (from content type) and is set to show in the display.

this field has a no results behavior set to the token [field_sermon_image_2]

Expected Behavior:

If the most recent node has an image associated with it, that image will show. If there is no image associated with the node, it will show the image associated with the taxonomy sermon series.

Actual Behavior

When I create a node with the sermon image filled out, everything works as expected and the view shows the sermon image associated with the Node shows.

When I create a node without a sermon image filled out, the view correctly shows the sermon series image associated with the taxonomy sermon series.

Here's where it gets weird. If I create a node without a sermon image filled out, see the view correctly show the sermon series image from the taxonomy, then either clear cache or wait until cache expires, no image shows up at all. I know the fallback is working correctly as even the [field_sermon_image_2] has a no results behavior fallback to a generic image and that's what always shows up.

Through some testing, I found that unpublishing the node, viewing the view, then re-publishing the node will bring the correct image back (at least until the next cache flush).

I'm not sure where to look for this odd behavior. It seems like I have everything setup correctly in my view as I can get the correct images to show up, I just can't get them to show up consistently.

Any advice you can give would be appreciated. Thanks!

I replicated your scenario and its working fine for me.

Here is what I did.

In Taxonomy I added a Vocabulary called "Sermons", I added an image
field called "tax image"
I added a term name of "Mega Man" to Sermons, and uploaded a
mega man picture to the "tax image" field.
Created an Article with title of "Enter Shikari is awesome" which has "Article Picture" as a field and I uploaded a picture of the band. Term Ref "Mega Man"
I Created another Article with title "Woooo" this time I did not upload any image to the "Article Picture" field. Term Ref "Mega Man"

Now in Views

In FILTER CRITERIA I added Content Type Is one of Article (so it only shows Article nodes)
In RELATIONSHIP I added Content: Taxonomy terms on node

Check marked "Sermon Series"
Check marked Require this relationship.

In FIELDS and I added the "tax image"

checked exclude from display.

In FIELDS I added "Article Picture"

No Results behaviour I put the token [field_tax_image]

I put a cache of 1 hour.

So here is what my View looks like

I added another Article with title "Kewl its working!!!" with Term Ref "Mega Man" and left the "Article Picture" field empty.
I Cleared the cache (since my view is cached, it won't show "kewl is working!!! until I clear it).

RESULT AS EXPECTED Kewl its working!!! and Wooo do not have Article Pictures, so Mega Man (tax image) shows up.


What are the legal considerations to build a service like Drupal Gardens and earn profit from it? I ask for your help to clarify a doubt I had on the usage and licensing of the Drupal platform to build a commercial project like Drupal Gardens.

Today, I have read both licensing and usage rules from the drupal.com and drupal.org, but I have found nothing that could give an straight answer to my curiosity about what will take both legally and economic to maintain a site 'like' Drupal Gardens. Being specific a service where people will pay to get a deployed Drupal instance.

The primary complication is the use of the Trademark "Drupal" in the product or service's name or domain. You'll need to contact the Drupal Association at http://association.drupal.org, or Dries Buytaert, the trademark holder.

If you're not interested in using the Drupal trademark as part of your product or service's name there shouldn't be any problem.


use different layouts for different pages I developed the layout of the first page in page.tpl.php.
Here I've created some regions, to put the blocks.
The problem is that these blocks reflect my "content type",
and it has a link that when i do to click, don't happens the linking.

I would like to link to a page with a different layout but I do not know where to set the second layout and how to redirect the link to this page.
thank you!

EDIT

the layout of the content type is level node (node.tpl.php), while the layout of the first page I set it at page (page.tpl.php). Going on the first page, I find a link within the block that should bring to the page of the node, but does nothing ...

As you can see, the title is my link to the node:

EDIT

in the layout of my first page I removed the "content", this may be the error?

Custom content types are should be themed at the node level.  Add a node template file to the theme/templates directory according to your content type.  For example, I have a "Trip" content type.  This gets themed with a node--trip.tpl.php file.

You don't need to do anything special to redirect.


Translate "Link text" in View I have the following text/token in one of my field's "Link text" field.

"Download [file:name]"

How do I translate "Download"

Here is a screenshot:

https://www.dropbox.com/s/lwquchykaymh20j/Screenshot%202014-05-28%2023.15.14.png

If you have the Locale module enabled, you can translate the string on the page admin/config/regional/translate/translate - just search for Download and the string should appear in the translatable strings.

In order to translate the string you have to open the actual page once to let drupal register the translatable string.


Changing an exposed filter to use check_plain() or filter_xss() I have a view with a search filter. I am using Acunetix scanner to scan for vulnerabilities, which reports me an issue about the search filter. How do I alter it to use check_plain(filter_xss($string)) or filter_xss(check_plain($string)) in view exposed forms (a block, in my case)?

You can write a form alter in your custom module. ie :

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form') {
        $view = $form_state['view'];
        if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
            // alter your exposed form here
            $form['yourdata_item'] = check_plain(filter_xss($string));
        }
    }
}


About Corolla Theme Logo I am using my logo with the Corolla theme but its give me the following error:

  No setting detected for Mobile first or Desktop first. Please review "Settings > Mobile first or Desktop first" and select an option.

What do I have to do? How can I resolve this error?

You're using the 3.x-dev version of Corolla, which is not quite ready for release.  You should consider using the stable 2.x release instead.

To fix the error, you will need to go the Corolla theme administration page (/admin/appearance/settings/corolla) and choose either "mobile first" or "desktop first" under "CSS Global Settings."

P.S.  In the future, this type of theme-specific question should be filed as a "Support request" in the Corolla issue queue.


How do I re-name my zone--content.tpl.php file for a separate front page layout? I am using Omega 3.x along with Delta and contexts for creating a drupal theme for my site. I have experience with using D6 themes like Zen but I am still learning my way around Omega.

I want to know how I can create and name a separate template for my zone called content for the front page. I wouldn't mind a hard coded or a Delta+context solution or for that matter any other method to achieve my goal as long as Omega is used.

This was too much for a comment so I put it in an answer. newdwardss's answer contains the right methodology, but it doesn't address the Omega theme.

You can use the same logic as in that answer, but customise it for the zone template:

function MYTHEME_preprocess_zone(&$vars) {
  if ($vars['zone'] == 'content' && drupal_is_front_page()) {
    $vars['theme_hook_suggestions'][] = 'zone__content__front';
  }
}

That will allow you to use a template file called zone--content--front.tpl.php which will only be used for that zone, and only when on the front page.


profile2 - change default edit path to custom profile I use profile2 module. After visiting user account, user is able to edit account by clicking on edit tab. It leads to Account secondary tab (user/x/edit). User is presented with empty passwords fields and other fields which can be sometimes confusing.

Question: Is it possible to change this default path to direct user to main profile created by profile2 module? (user/x/edit/main)

Thank you

Well actually you can, there is a submodule of the profile2 called "profile pages"

  With profile2 user account settings and user profiles are conceptually
  different things, e.g. with the "Profile pages" module enabled users
  get two separate menu links "My account" and "My profile".

Via the included "Profile pages" module profiles can be viewed and edited at their own page and get their own menu link, e.g. "My profile".

with the profile menu paths already setted up for your custom profile then you need to remove the edit tab that points to the default profile edit page of drupal. For delete this tab follow this tutorial http://www.zyxware.com/articles/4159/solved-drupal-how-to-hide-menu-tabs-and-menu-links-in-drupal-7

Then you can add your own edit tab that will link to your custom profile edit page https://www.drupal.org/node/1578582


Can I add a custom block? I want to have a block with 3 text body fields. I've done this before in Drupal 8 where I created a custom block and was able to add different fields to it.
In my Drupal 7 setup, I can add a block but cannot see where to add a custom block. Is this possible? If not, is there a way to set up a block with 3 different body fields?

Use the Bean module, this will allow you to create custom Block types with fields, even image fields. It integrates nicely with the blocks module.


Can not see test modules in module install page In Drupal 7, tests module can be added with hidden = TRUE property in .info file to not to display on modules list page, but tests can find and enable them using protected $modules property.

But Drupal 8 doesn't have this property and the test modules don't appear in modules list page. How does it work?

Test modules are under module_name/tests/ or module_name/tests/directory and can be enabled by TestDiscovery service. As ExtensionDiscovery::scan() calls TestDiscovery::getExtensions() method with $include_test flag TRUE.

The flag can be overridden by settings:
    if (!isset($include_tests)) {
      $include_tests = Settings::get('extension_discovery_scan_tests') || drupal_valid_test_ua();
    }

See also ExtensionDiscovery::scanDirectory
 and RecursiveExtensionFilterIterator::acceptTests()

For manually enabling and testing a test module, it could be moved under modules directory (from /tests) and move back once development done to enable it via test.


How can i prove that the activation link sent to subscriber (anonymous user) has actually been activated? Where can i find a log entry or related information documenting that the activation link in the confirmation mail sent to simplenews-subscribers has been activated?

You can check the Status of your subscribers by going to People > Newsletter subscriptions (/admin/people/simplenews).

There are 4 places within Drupal admin navigation that Simplenews entries are interspersed into:

Configuration » Web services » Newsletters (/admin/config/services/simplenews) for creating different Newsletters (you want at least one)
Structure » Content types » Simplenews newsletter (/admin/structure/types/manage/simplenews) to choose and edit a Content type to use for the newsletter content
People » Newsletter subscriptions (/admin/people/simplenews) to list and filter all your Subscribers
Content » Newsletters (/admin/content/simplenews) to see all the created Newsletter issues and their status


Field with '#type' = 'hidden' in hook form alter doesn't show #id in the source and it's not possible to show it with jQuery I put in my template.php an hook_form_alter function where I assign '#type'= 'hidden' to "field_bergamo".

But I want to show it when in the select list "Provincia" of the same form
I select the option "Bergamo".

I suppose to solve with jQuery, but in the inspector of the page I can't
see the
"#edit-field-bergamo" ID, only the name.

I tried "jQuery ('input[name="field_bergamo"]').show()", it doesn't work.

If I don't assign ['#type'] = 'hidden' to "field_bergamo" in
hook_form_alter I can see the
"#edit-field-bergamo" in the inspector and
the jQuery commands .show() .hide() work correctly.

Why if I assign ['#type'] = 'hidden', the field doesn't have an ID and
doesn't react to my jQuery commands?

Any solution?

P.S. I can't use Conditional Field because the select list "provincia" is
inside a field type "Postal address" and is not singularly accessible.

And I don't like to install a module if not strictly necessary!

You've converted the element to a hidden input type.

Hidden inputs cannot be rendered, as the name suggests (they're hidden by their nature). So trying to use javascript to "show" them will never have any effect - there's nothing to show.

Add that to the fact that a changed hidden input element will invoke a validation failure for a tainted form, and it should be easy to see why the Drupal devs didn't bother to add an HTML ID to the element. Trying to access it with CSS/JS makes very little sense most of the time.

If you just meant to hide the original input, not convert it to a different input type, just use CSS to hide/show it as normal.


How do I build a form with embedded view results I need to create a sign up form that also displays all of the submitted values above each value on the same page.  I have searched for hours and cannot find anything that describes how to achieve this.
So it would be formatted like:

Sign Up Form

Results of value 1:

value1, user 1

value1, user 2

value1, user 3

[enter value for value1] <= this is the form field to enter a new value1 for current user

Result of value 2:

value2, user 4

value2, user 2

value2, user 6

[enter value for value1] <= this is the form field to enter a new value1 for current user

[submit]

I have come close with webform and building a webform-form--nid.tpl.php file to override the default template, and use views to create tables for the results but the view tables are listing all of blank fields as well.  I have tried entitfyform but don't know how to split up the form to allow to have the views above each relevant section.

Sign Up Form

<?php
    function formfun_menu() {
    $items = array();
    $items['formfun'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'FORM FUN',
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('formfun_form'), //put the name of the form here
    'type' => MENU_NORMAL_ITEM,

    'access callback' => TRUE
  );
  return $items;
}

function formfun_upload_form($form, &$form_state) {

$form['add'] = array(
 '#type' => 'fieldset',
'#title' => t('Add company details'),
);
  $form['add']['companyname'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => 'Company Name',
  );

  $form['add']['contactname'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => 'Contact Name',
  );

    $form['add']['companyaddress'] = array(
    '#type' => 'textarea',
    '#required' => TRUE,
    '#title' => 'Contact Address',
  );

    $form['add']['postalcode'] = array(
    '#type' => 'textfield',
    '#title' => 'Postal Code',
  );

    $form['add']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
  );

    $form['add']['country'] = array(
    '#type' => 'textfield',
    '#title' => 'Country',
  );

    $form['add']['file'] = array(
        '#type'     => 'file',
        '#title'    => t('Choose a file'),
);

  $form['add']['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),

  );
   return $form;
}

function formfun_submit($form, &$form_state) {

    echo '<pre>';
var_dump($form_state['values']);
echo '</pre>';

    db_insert('details')
    ->fields(array(
    'companyname' => $form_state['values']['companyname'],
        'contactname' => $form_state['values']['contactname'],
        'companyaddress' => $form_state['values']['companyaddress'],
         'postalcode' => $form_state['values']['postalcode'],
        'city' => $form_state['values']['city'],
         'country' => $form_state['values']['country'],
         'image' => $form_state['values']['file'],
   ))
   ->execute();
    drupal_set_message("successfully saved Security Settings");
    exit();
}

function formfun_validate($form,&$form_state)

{
  }


Is it reasonable to run hundreds of sites by one Drupal core? There are more than 100 sites that are supported by our company and they can be presented as sub domain as well. from technical perspective is it reasonable to run all of these sites using only one Drupal core? is there any drawback in doing such thing? or we should have multiple cores?

Technically, there shouldn't be. But even if I had enough server resources, I'd reconsider my approach. A few problems I can think about. Note that they are really small annoyances and there are workarounds. If each site of your network has to be a very serious site, and all you are expecting is less files on the server and ease of updates, I think it's a bad idea.

Your sites.php file will get larger. You can specify which settings.php file should be used in the sites/sites.php file. That file will get larger with the number of sites in your network. However, in a age that you store 100 configurations in $GLOBALS, this shouldn't be a problem.
Your modules page will load slower if you put all modules in sites/all/modules folder, but only want to use them in a few sites.
In core or shared module updates, make one wrong move and everyone will know.
You can't use different robots.txt.
In fact, you can't use just about any "known files". favicon.ico, apple-touch-icon, Bing verification file, oh gosh.
Say hello to the complicated vhosts file and .htaccess for me. I'm a fat guy and so they should be.


How do I populate an email field from a single user “Name” reference? I have a content type in which I use an entity reference to reference a Name field in a user account. I am trying to populate an email field in the content type with the email of the entity referenced above. I have tried creating an entity reference view and can get it to show and save: Name, Email Address in the node. However, because of some rules I am using, I really need them to be saved to separate fields. So I tried the Entity Reference Autofill module which seems like it does exactly what I am looking for, but, it only works with existing fields, and for some reason, I can’t get the user account fields to show-up as existing fields when trying to add them to the content type.

So, is there a way for a single reference to populate more fields using the initial reference as a ‘key’?

Or…

Is there a way to get user account fields to show-up as existing fileds so I can just use the Entity Reference Autofill module?

Thanks so much.

Maybe I don't understand the need, but once you reference an entity what is the point of adding the values from the referenced entity into the referencing entity?

Is this a UI thing when creating a node? Or a display issue when displaying a node?

If it's a display issue, wouldn't you just create a new display for the reference user for when it is being referenced only showing the fields that you want shown?

To do what I am saying, you would need either https://www.drupal.org/project/ds Display Suite, or embed a view, or call the referenced user fields in a template or module.


How to auto submit only after typing at least three character in view exposed filter I have a view with exposed filters using AJAX and auto-submit feature.

The problem is it reacts to every char I type but what I want is that when a user type at least three character in the text field then it should auto submit and display search result. But Cant figure out how to implement this. Please help

Attach custom_form_validate for that form using
form_alter
Do what ever you want in this custom_validation.
Reference


Get form values in hook_user_insert() How can I get form values like first name, last name, email and password in hook_user_insert() in Drupal 8?

The $account argument have the data that you like, but the password is protected.

It's not the best practice, but you can use reflection to get it:

/** @var \Drupal\Core\Field\FieldItemList $passObject */
$passObject = $account->get('pass');
/** @var \Drupal\Core\Field\Plugin\Field\FieldType\PasswordItem $passItem */
$passItem = $passObject->get(0);
$reflection = new \ReflectionClass($passItem);
$reflectionProperty = $reflection->getProperty('values');
// This do the magic.
$reflectionProperty->setAccessible(true);
$pass = $reflectionProperty->getValue($passItem)['value'];

See more about hook_user_insert here.


how to obtain fivestar field value in rules? I'm trying to a grab a value of a fivestar field within rules and having no luck.

Basically I'm getting users to fill a feedback form and if the fivestar field value is less than 3 Stars then I want the rule to fire but no luck.

Can someone help me figure out to what's going wrong.

Thanks

I'm not sure about forms, since you didn't mention how you set those up on your website, but I can help you with the case where the Rule is called after saving a new comment with a Fivestar field, say it's called Stars. Follow the guidelines underneath for your Rule:

Events: After saving a new comment.

Conditions:

Check whether the comment has a field Stars with Entity has field.
Check whether the field Stars is not empty with NOT Data value is empty.
Run this custom code: return $comment->field_stars['und'][0]['rating']<=60;.

Adapt these steps to your needs. Be sure to compare the rating with a score out of 100, since Fivestar works internally with percentages.


Aegir and SA-CORE-2014-005 Case:

- Aegir server 2.1 on Drupal 6.31
-- Platform Hostmaster: Drupal 6.31
--- Hostmaster: ?
-- Platform 1: Drupal 7.31
--- Site 1: HACKED
--- Site 2: HACKED
-- Platform 2: Drupal 7.32
--- Site 3: ?
--- Site 4: ?

Actions:

So the attackers get access on site 1 + site 2 using the SA-CORE-2014-005.
Platforms 1 and sites 1 and site 2 totally deleted or restored from an old backup and then updated (files and db).

Questions:

Is there a case that the hackers gain access on Hostmaster or on sites 3 and site 4?
Or even worst… the hackers gain that level of access on the server that can compromise a new Aegir install?

If site 1 and 2 are compromised, it's entirely possible that
sites 3 and 4 are either in danger of being compromised or have
already been compromised.
More or less, yes. If they already have sites 1 and 2, it's extremely likely that they can directly access your server.

You should consider your current server and the sites running on it as tainted and rebuild from scratch. Despite @Clive's assertion, there is no user account sandboxing happening at the per-site level.


How to show upcoming events in the current month with calendar module? I'm using Drupal 7 Module Calendar, Views and Panels.

I used the block-mini-calendar view of Calendar module to display on my frontpage.

Then I created a custom view to display only a list of the day's events selected by the user.

I put as Context-Filter:
Date: Date (node) (Content: Dates - start date (event_calendar_date))

And Filter Criteria:
Content: Published (Yes)
Content: Type (= Event Calendar)

Then, I created a panel-page that receive the arguments of the date by URL and passes to my view created (My view created above I've put in my panel created with the URL of events/%date).

All previous flow works well. I'm listing all events of the day selected by the user. But, I need to display all events that are within the range of parameter passed in the URL(day selected) and the last day of the current month that the user is.

What changes should I do in my view?

Sorry for my english. Thanks in advance.

Try paginating the view by Date,I guess should get the month options in the pagination as well.I do not have a drupal set up with calendar so can not confirm, you have to give a try.


Search api solr: The Solr server could not be reached I've got a working solr server, however my drupal always fails to connect, what am I doing wrong?

When adding my server and clicking on the solr server url it takes me to my server (so my path is correct), yet I keep getting a message: The Solr server could not be reached.

I am hosting apache solr on a server (not locally).

Host: Server IP address
Port: 8983
Instance: /solr

Can anyone help me out ?

@see "Your site was unable to contact the Apache Solr server"

I follow this article https://www.lullabot.com/blog/article/installing-solr-use-drupal ,some day comes this errors after I reconfig of my site& apache.
but I sloved like this


Rules: use a View's result as a condition? How can I use the results of a view as a condition in a rule?

I have rule that fires off a daily digest email with contents from a view (using Views Rules). The view simply returns nodes that have a specific field value. When the view doesn't return any nodes, the rule still fires off what is essentially an empty email. I want to prevent this. I need a condition like "View has no results" (negated)… but I don't see anything like that. What's the workaround?

Even though your own answer is indeed a way to solve your question, it doesn't say that for this to work, it requires the Conditional Rules module to be enabled (without that, you cannot add a Rules Condition as an extra rules Action).

An alternative solution to solve your question, is to use the Views Bulk Operations (VBO) module to transform your view into a VBO view, so that you can use a Rules Condition "Check number of results returned by a VBO View" in which you can perfectly construct the Rules Condition you're looking for.

Have a look at "this answer" for an illustration of how this specific Rules Condition is used.

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


How can I apply node template file only to node view page but not revision page? I have a node template named node-"content-type-name".tpl.php which overrides the default node.tpl.php for this content type.

But this template file is applied to also node revision pages. Is there anyway I can apply the node template file to just node view/edit page without revision page?

I don't have a D6 site around with revisions enabled so I can't test this, but the following code should disable the custom template for the revision pages:

function MYTHEME_preprocess_node(&$vars) {
  $template_name = 'node-content-type-name';

  // Work out if we're on a revision page
  $on_revision_page = arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions';

  // See if the rogue template file is available as one of the suggestions.
  $template_index = array_search($template_name, $vars['template_files']);

  if ($on_revision_page && $template_index !== FALSE) {
    // Remove the rogue template file from the suggestions.
    unset($vars['template_files'][$template_index]);
  }
}


How can I print usernames in order using entity_load function? I'm using drupal 7.28, and I have fetched user id using entity_load('user'), so I need descending sorting on usernames using this way of logic, let me know if anyone has an idea.Here is my code that I have written in my file.

$users = entity_load('user',$sort);
$usersIds = array_keys($users);
foreach($usersIds as $usrId)
{
   $user = user_load($usrId);
   $user_load_name = array($user->name);
   echo "<pre>";
   print_r($user_load_name);
}

small change in your code will do it for you

$users = entity_load('user');//load all user in your site
$usersIds = array_keys($users); // get all uid of the user
foreach($usersIds as $usrId) {
    $user = user_load($usrId);
    $user_load_name = $user->name;//get the user name
    $user_load_name1[] = $user_load_name;// store all user name in array
 }
 natcasesort($user_load_name1);//For sorting array in ascending order INCASE SENCITIVE order
 $arr = array_reverse($user_load_name1, true);// For making it in descending

This code will only give the user name in Decending order if you want it in ascending order just remove array_reverse() line that will be enough.

hope it helps you :)


Cannot import Paragraph based Feature into new site Perhaps someone with a bit more Features expertise can help me here.

I have a Drupal site with 25 or so Paragraph types that I would like to export (one by one) to its own contained Feature.

I installed the latest version of Features, and created a new bundle called Paragraphs. In this new bundle, I enabled Paragraphs as a Base Type so they are an exportable option.

I go back to the main Features admin, and click "Create new feature". I fill out the basic info here, the name of the feature, then I select the Paragraph Type I want to export and wait for all of the required dependencies to auto populate. I finish the export by clicking on "Write" which produces the module folder.

In the new Drupal site I want to import it to, I see it in the list of Features. When I go to enable the module, I get an error like:

  Error importing field.field.paragraph.text_editor.field_rich_text :
  Attempt to create a field field_rich_text that does not exist on
  entity type paragraph.

Except... this Feature should be introducing this field into the application and install it. The Paragraph just has a long text field for CKEditor, and there is no field.storage.paragraph.field_rich_text.yml file that is exported. Yet, field.storage.paragraph.field_rich_text is listed as a config dependency in the same said Feature.

Did I miss a step here? I basically want to export my Paragraph types as if they were Node types. I want to install them into a new Drupal installation without wiring them to any reference fields or Node types - I want to do that later.

Why am I getting errors like Attempt to create a field field_rich_text that does not exist on entity type paragraph.? I get a similar error for each Paragraph I try to enable, which are all made up of basic fields and nothing special.

Note: it looks like the auto detection doesn't quite work. For example, if I pick one of the Paragraphs from the list of non-exported Features on the overview page, the field storage definitions that are marked as a dependency in the output are NOT selected for being exported here.

I started over and removed all the exported Features, and created a new Feature. This time, when I picked the paragraph type, it still did not include the field storage definition for the field that is being bundled. When I selected it, exported it, this time it enabled on the new site, no error.

What is the proper way to do this? Do I have to go through one by one and simply ensure the field storage(s) are exported myself?

My best answer to this question is: Features is awesome but a little buggy, or seemingly so, due to field and field storage dependencies. The best solution I have found in Drupal using features and all these export issues is to create a content type where you create ALL your field base instances. I always call mine xxxFields. Then in all other content types, always add an "existing" field. really all this is doing is helping with user error. I have used features from 7 and now into 8, and I find that most issues arise through configuration of numerous content types which share fields, which creates dependency issues when trying to export features modules.

I believe your specific issue may be that that module is trying to create itself but has a dependency for a field base and field storage configuration that was created in another content type.


Drupal form creating method without using a module I am working on a Drupal site and it has a custom form in the frontend. I want to remove that form, but the problem is it is not generated by a custom module.

There is only one custom module. so I disabled it to check if that's the module generating the form. I cleared the cache also.

But the form is still there. So is there any other method of adding a form to a Drupal site without using a custom module?

As the comments and the other answer says, there are several possibilities:

A contributed module such as Webform.
Someone with very bad habits hard-coded that form inside templates, other modules or even Drupal core.
A block/node could contain that form, specially if the PHP-filter is enabled. Even with the HTML filter enabled (and submitting the form to another page).

If you see some custom text, or the name of the fields are unique or rare, you could try to search inside Drupal root directory for them:

grep -r 'Custom text' /var/www/drupal

phpMyAdmin includes a functionality to search across an entire database. If you feel desperate, try to search inside the Drupal database for the text you see in the form.

Examining the outputted HTML code could help. You will see if the form has an ID, for example.


How to display a node edit form in custom URL I have a node created (using Default content) as part of the site install and it is available to edit at node/[nid]/edit. However, this node holds some of the site-specific content (for example, content to display on sitewide banner) and should be available under the site configuration section instead of node/[nid]/edit so that I can restrict the edit access with specific permission.
Why not the configuration/settings form? Because the node type has rich fields like image upload, entity reference, etc, and would be nice to use the node/entity's field API and display modes.
Is there a way to get the edit page of just this node at /admin/config/system/banner-settings?

Create a new menu item in a custom module
# mymodule.routing.yml

mymodule.banner_settings_form:
  path: /admin/config/system/banner-settings/{node}
  defaults:
    _entity_form: node.edit
    # Copy UUID from exported default content.
    node: 05d6a9e5-6e78-42bb-b3fe-b9a6344f4022
  requirements:
    _entity_access: node.update
    # Custom permission check.
    _permission: 'administer site banner configuration'
  options:
    _admin_route: true
    _node_operation_route: true
    parameters:
      node:
        type: 'entity:node'
        # Part of jsonapi module.
        converter: paramconverter.jsonapi.entity_uuid

Visiting /admin/config/system/banner-settings would take the default UUID value from the route and renders the form.
P.S: After saving the form it would redirect back to node/[nid] and this can be avoided by passing ?destination=<your path> in the link.


Delete drupal content page How can one Delete Drupal content page (article/basic page) without actually visiting the page. Without Drush or visiting the database (which is a little complicated in D.7).

goto admin/content and press delete per page next to its title. You don't have to Edit the page. You will have to confirm your delete choice.


Term reference field won't display I'm trying to add tags to my blog posts on my Drupal 7 site. I've added the Term Reference field to the content type and when I add a blog post it is letting me add tags without a problem, however despite the field being visible in the 'Manage Display' tab I can't get them to show up when viewing the blog entry.

I know that the field is working because I have the Metatag module installed and that's producing metatags from the field token. I've checked the page source though and the field isn't even there but hidden because of CSS.

Anyone any ideas?

It turns out that my theme was hiding any term reference fields by default, which I discovered after switching back to the default theme (thank you too @NoSssweat for suggesting I do this).

I created the theme using Artisteer (please keep comments about my decision to do so to a minimum - I only use it as a starting point) and following @JimmyKo's comment I found the following lines in the node.tpl.php file:

$terms = themename_art_terms_D7($content);
hide($content[$terms['#field_name']]);

After I commented these out the term reference field started appearing. Thinking back, I may have ticked an option in Artisteer to say that I didn't want tags to appear so I can't definitely lay the blame on the software!


node_publish_action is not publishing the node I'm trying to add a submit handler to a "Done" button that should publish a node when the button is pressed. It's a scenario where the Rules module won't cut it, it has to be in code. I tried to following:

function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form['#form_id'] == 'my_node_form'){
    if ($form['actions']['done'] !== NULL){
      $user = user_load($form['uid']['#value']);
      $form['actions']['done']['#submit'][] = 'mymodule_publish_submit';
    }
  }
}

function mymodule_publish_submit($form, &$form_state) {
    $nid = $form['nid']['#value'];
    $node = node_load($nid, $vid = NULL, $reset = FALSE);
    node_publish_action($node, $context = array());
}

but it's not working. My debug text shows up so I know the submit handler is getting called. Where am I going wrong?

Contrary to this comment on the API documentation, node_save() is required after node_publish_action() is called.

So the submit handler should look like this:

function mymodule_publish_submit($form, &$form_state) {
  $nid = $form['nid']['#value'];
  $node = node_load($nid, $vid = NULL, $reset = FALSE);
  node_publish_action($node, $context = array());
  node_save($node);
}

As pointed out by jimajamma, the previous code contains a hook_action() which allows integration with Actions. The following code does the same thing, but doesn't use the hook_action()

function mymodule_publish_submit($form, &$form_state) {
  $nid = $form['nid']['#value'];
  $node = node_load($nid, $vid = NULL, $reset = FALSE);
  $node->status = 1; // 0 = unpublished, 1 = published. There are no other states
  node_save($node);
}

Pretty simple.


Attach Galleries to Content Types I am working with drupal 7 and I need to attach a gallery to the content type. I looked at the current solutions where I can create a Image content type and  create node references. I am looking for something where any user would be able to contribute images, multi-upload images at the same time, if possible can also add images from URL.

Also is it possible to do something where the user can just click on a "Add images" link and the user would be presented with a image upload screen ?

There are plenty of approaches to this, the main difference being whether you use the Media module or Drupal 7 core's built in image field. The image field route I think will be simpler as you have to create your own view mode to have custom image sizes with display suite and the 7.x-2.x version is still under heavy development. See the related Media modules for options. There are modules for multiple uploads and creating image galleries.

If you choose to use D7 core's image field you can add galleries to content types with the Views Galleriffic module.

Here are Step by step instructions for D7.

You can also switch between styles.

Default

Thumbnails above

For multiple uploads you can try Multiupload Imagefield Widget.

For a remote URL you can try Filefield Sources.

For an "Add image" button you can just create a link to the "/node/add/gallery" node or create a custom form.


Using an F5 server as reverse proxy cache (instead of Varnish) Does anyone have any experience, positive or negative, with using Drupal behind F5?

Did you succeed or fail?

In either cases, what functionality did you achieve? How far did you get?

I have used F5 as a load balancer with Drupal without issue. We were using varnish between Drupal and the F5 as a reverse proxy.

Pressflow and varnish have been tested well together, F5 is quite a high end bit of kit so I don't know if anyone else has tried it. From what I remember F5 is very flexible so you should be able to get it to work in the same way as varnish (same headers being sent etc).


Operations bulk form for custom content entity There is a custom entity called organisation. I am trying to build a view to allow bulk delete of the entities.

I checked the view for display content and there is a field to display the checkbox(Node operations bulk form).

This field doesn't show up for the custom entity. Enabling the actions module does not help.

Adding a custom action for delete organisation does not help either. The new action shows up on the list of actions, but the "operations bulk form" does not show up on views for the entity.

Thanks in advance for your help

You need both an action plugin and an action config entity

Create the plugin with drush: drush generate plugin-action
Create the action config entity: look at
"system.action.comment_delete_action.yml" for an example.

After creating these, clear the cache and it should be available in views under the label "Bulk update".


XML Sitemap Last Modified Date on a View The site I am working on has a front page gallery view.

Is there any way to update the last modified date of the view in the XMLSitemap file? As currently it is just empty.

The short answer is: No.

How are you including the views in the sitemap? I assume that you are just putting in custom paths? Without writing custom code, the only thing you can do for the custom path is to change the change frequency to a realistic amount. Don't exaggerate the frequency too much, or crawlers will start ignoring it.


List main menu links I need a list of main menu item links to display on a page (sort of a sitemap).
How would I accomplish this in Drupal 7?

Go to admin/structure/block and configure the Main Menu block

You want to go further you can Install Menu block module

So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!


Drupal cannot generate the derived image ANYMORE? OK, My situation is really complicated (or Im stupid).
I start my website http://rlsgame.org with Drupal System (even if Im .NET developer)...
After 3 month, my website start grow up (about 2000 article and 3000 members) But a problem appear !!! I didnt touch anything, It appear just like that !!

When I want submit a Node, I have an issue with Images, I cant see the preview image :

and After submiting the Node, here is the result:

I refresh the page and the nothing, But after i press CTR+F5, the article is fine:

you can check the page here: http://rlsgame.org/PC/Games/ArmA-III
All is fine...

But the big problem is that Drupal System cannot generate the derived image of User Picture !!
Even if I press CTR+F5 like before, the problem is still here, look an exemple of a profile page:

Link: http://rlsgame.org/users/gamer

The old users profile is fine, because the picture is generated before the problem, exemple:

Link: http://rlsgame.org/users/mgs

And one more thing it start to appear too, Drupal start Caching comments (not like before this problem), when I post comment, sometimes it apear without Caching, and sometimes I must wait about 10 sec, for exemple, I post a comment and nothing appear, and I navigate to the homepage, and here we go, the msg appears:

I think if I fix the issue, All those problems will disappear ...

Im looking for fixing that 10 days ago, So Just for info:

All files permission Are OK:
sites/default  => 555
sites/default/files  => 755  (and all sub-folders too including styles)
And paths of File system are OK
Drupal is updated to 7.26 (latest version)

And the problem is not from the server (Im working on Shared Server) because I downloaded my website and run it in Local but I see the same problem plus My website work before so the problem is not from the server.

Ah, one thing, when i check Reports Log, I see a lot of warning, here is an exemple:

Thats all, plz help me to fix that, Im losing traffic....

Thanx for advance.

In your settings.php file add this

$conf['image_allow_insecure_derivatives'] = TRUE;

In the future you should use image_style_url() when using image styles as this will then add in itok parameter for images. Usage: image_style_url doesn't create images

More info about this: https://drupal.org/drupal-7.21-release-notes


How would a customer be able to get free shipping when there are no free shipping options? We just launched our ecommerce store using Drupal Commerce Kickstart, which heavily uses Rules to manage shipping.

We have had two orders from the same Virginia-based customer. Both orders were processed without shipping applied. When I select the same items, enter the same Virginia USA shipping address and go through the checkout process, I get the expected behavior of Standard Shipping - $15 being applied. I cannot replicate the behavior.

The checkout process / sequence is as follows.

The "Standard Shipping - Domestic" rule is called for:

Addresses within the "US"
Orders not contain three Product Categories (bikes, wheels, forks)

*The order in question does not contain these items.

I attempted to duplicate in both Chrome Incognito & Firefox. No issues on my side. I see the following:

One option to select from under "Shipping"

Shipping applied under "Review Order"

When viewing in admin mode, I see shipping applied as a line item on the order.

PLUS - The correct sequence is maintained

When I view the customer order, there is no shipping line item.

AND the customer appears to be going through a different order sequence and bypasses the Shipping selection. How is this possible? I am totally confused.

How is it possible to bypass the checkout sequence in Commerce Kickstart?
1. Test: Checkout > Shipping > Review Order
2. User: Create order > Add item to cart > Pending (Which is typically after the order is fully paid. We have confirmed that payment has been received.)

Very curious. Curiouser & curiouser.

If the issue is that shipping selection needs to happen for Express Checkout users, then if you edit the Express Checkout module's order confirmation checkout pane you can choose which checkout panes from other pages should appear on the final confirmation page. Make sure you check the box there for shipping service selection and it should show up as expected.


Capturing cache metadata from file_create_url? I'm writing a Drupal 8 controller which takes in a media entity, and returns a redirect response to the actual file URL.

It works by finding the file associated with the media entity, and then does this:

      $url = file_create_url($file->getFileUri());

      $response = new CacheableRedirectResponse($url);
      $response->addCacheableDependency($media);
      $response->addCacheableDependency($file);

      return $response;

However, this results in a LogicException: "The controller result claims to be providing relevant cache metadata, but leaked metadata was detected"

Ok, so what's happening is that file_create_url() ends up generating cache metadata, and that cache metadata is not being attached the response object. But it doesn't seem possible for me to do that, because file_create_url just returns a string and not the cache metadata object.

Here's my current workaround, but I'm not sure if this is correct either:

      $context = new RenderContext();
      $url = \Drupal::service('renderer')->executeInRenderContext($context, function () use ($file) {
        return file_create_url($file->getFileUri());
      });

      $response = new CacheableRedirectResponse($url);
      $response->addCacheableDependency($media);
      $response->addCacheableDependency($file);
      if (!$context->isEmpty()) {
        $metadata = $context->pop();
        $response->addCacheableDependency($metadata);
      }

      return $response;

Anyone with more experience with cache metadata know if this is the correct way to handle this situation?

Thank you

This code seems to be OK to me until file_create_url() is transformed into a service which can handle cacheable metadata like UrlGenerator.

An easier way to avoid this error message would be to return an uncacheable RedirectResponse:

  $url = file_create_url($file->getFileUri());
  $response = new RedirectResponse($url);
  return $response;


Using Views in Complex Pages I would like to use Views to create content for custom content type pages.  This seems to be consistent with the use of Views in the Admin pages of Drupal 8.  I'm running into problems integrating Views (the page content) with the page layout of the page.  This should be simple -- but it does not seem to be.  In all of this I would like to use the base features of Drupal 8 without custom or contributed modules.

The key functions that I am working to implement is being able to embed a View anywhere I would like in a page.  Said another away, I would like to embed several Views (page content) into specific portions of a complex page structure (page layout).

In Drupal 6 we have a content type and associated template file. Embedding a View in the template is straight-forward -- we use PHP code.
I tried creating Views as Blocks and placing them in different Block layout areas.  This became complicated quickly -- to much so.  The problem is the page layout must become part of the Views. There may be a solution involving the creation of custom Block layout regions and make the Views part of these new region.  The page design has several layers of content for mobile devices.  We would need Block layout regions for "Layer 1", "Layer 2" and "Layer 3" which are all part of the page Body.  I don't know if this will work.
I created a custom module that creates a Block for the page.  I can render whatever I want including layout elements and embedded Views content.  The problem is I am quickly generating a lot of custom code -- one of my goals is to avoid this.
I'm starting to look at Page Manager and Panels for a solution.  Bringing these modules into the design for a seemingly simple problem does not seem like the correct answer.
It seems there should be a simple way to embed a View into a Twig file associated with a content type.  This is where we started -- the Drupal 6 approach.  This simple solution has been difficult for me to achieve.

Any ideas?

The content we want to create has four parts. All four portions of content is a part of the "content" region of the page -- the top and three overlays. Here is a rough prototype: raystedman.org/d8/landing

You can still embed views in templates, just prepare them in yourtheme_preprocess_TEMPLATE(&$variables), put them in $variables['some_key'] and then display in your template as {{ some_key }}.

I'm starting to look at Page Manager and Panels for a solution. Bringing these modules into the design for a seemingly simple problem does not seem like the correct answer.

I don't see why it wouldn't be. It's possible to do a lot more with just Drupal 8 core than before, but not everything. Using contrib modules is perfectly fine, as long as you try to not add every single module out there to your site.

The only problem is that it is a bit early for many contrib modules unless you know what you're doing and can dig into the code in case you run into issues.


Render menu block in twig template In page--front.html.twig I load a nested twig file {% include
"header.twig" {} %}
In header.twig I want to render my menu block

I tried the following but no result:

In my_theme.theme I added:

function crm_theme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('crmnavigation');
  $variables['block_output'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

In header.twig I added {{ my_navigation }} but it doesn't show the menu block?

The easiest solution is to make use of twig tweaks module, Install twig tweak

drush -y en twig_tweak,
drush cr,

now you can place navigation anywhere. In your case inside header.twig file place

{{ drupal_block('crmnavigation') }}

You can also render entities, views and many other things. well explained here http://www.wdtutorials.com/drupal/theming/drupal-8-tutorial-43-twig-tweak-module-article-video#.WCPOxeErIyk


drush only runs with sudo When I run drush without sudo I get the header plus: drush is designed to run via the command line. Drush with sudo works as intended.

I have read that: You do not need root-level permissions to use Drush: it'll work as long as the user invoking it has direct access to the Drupal installation directory.

This does not seem to be true in this case. Even when I su to the exact user that owns the Drupal installation, I still cannot run Drush without the error message.

drwxr-xr-x 10 ouruser www-data     4096 May 18  2012 html

Is there something incorrect about permissions or is there another problem going on?

Greggles comment is most likely correct. Check your php path my going to the phpinfo path in the reports section. The URL is admin/reports/status/php.


Overriding menu.html.twig just for the primary menu Drupal 8 Beta 1 has a lot of nice templates to use which can be brought into a custom theme and then customized. I brought in core's menu.html.twig into my custom theme and indeed I can customize markup in there. However, this template overrides all Drupal menus, not just the primary menu which is the one I want to override.

I tried the Devel module for Drupal 8 figuring I might get some insight about what's going on under the hood. However, the module still looks like it's in a state of flux and I got massive errors. My goto module for template suggestions for Drupal 7 is Devel Themer (Theme Developer) but alas no Drupal 8 version.

I also tried getting specific with the template name and tried menu--primary.html.twig but that did not work either.

I then tried within the template wrapping an if around the part that I want to modify as such:

{% if primary_menu %}
   <ul{{ attributes.addClass('foobar-menu') }}>
{% endif %}

... but no joy there either. so I am out of ideas on how to do this.

Answering my own question here, this will probably be useful for those looking to debug twig.

Activate devel Kint (part of the Devel module) on the modules page or with Drush
In your site /sites/default/services.yml change the following settings:

parameters:
  twig.config:
    debug: true
cache: false
auto_reload: true
Then in the template you want to debug, place this code in it:

{{ kint() }}

Now you get a nice tree of variables that prints out similar to what you would get if you did an old style kpr(get_defined_vars()); in Drupal 7.

I see from the debug printout that the name of the menu is simply main.
Now I change the overridden template in my custom theme's template folder to menu--main.html.twig
Voila, the template is only specific for the primary main menu now
Customize as a themer to your hearts content.
Throughout this process, don't forget to clear cache and change / remove any debug code when you are done.

In addition to this, with debugging active, Chrome prints out possible template suggestions a la devel_themer so you don't necessarily have to use Kint.


Summary/Trimmed field in view doesn't include Read More link I have a view, and the key display points are:

Format: Unformatted List (I'm adjusting the views look through CSS)
Show: Fields

One of the fields to show is Body (so, a textarea.) When I choose to display it as "Summary or Trimmed", and set the trim length to, say, 600, it trims it fine, but it doesn't show a "Read More" link to the content's page. Is there something I'm missing?

did you check " Add a read-more link if output is trimmed. "?

If yes, maybe the problem is, that the text is not trimmed. If you want to have a "read more" link in any case, then you sould add the field "Link" to the view. You can then also enter your custom text, e.g. "details..." instead of "read more" etc.


How many taxonomy terms are too many? I have a website where I publish book reviews. For each book I publish 2-3 quotes from the book. I'm using the following fields as taxonomy, so that when a user clicks on them he/she can find more content of that category.

Book name
Author name
Publisher

Lets say, over the period of time, I add reviews of about 5000 books, then there will be 5000 taxonomy terms for "book name". Same for the other categories.

My question is, are these too many taxonomy terms for Drupal? Or is there a better way of doing this. All I'm trying to do is, when a user clicks on author's name, he/she can find more content from that author.

Short answers:

Drupal should have no problem with 5000 terms.
Using a taxonomy for this is the best solution in Drupal.

You may also want to use Taxonomy manager as suggested by kala4e4k in a comment.

What is the upper limit?

Well, taxonomy vocabularies are managed by the database, so this limit is determined by the maximum number of rows you can store in a table in the database you're using.

If you're using MySQL, there is no built-in limit to the number of rows per table (just pick a big enough number type to manage the primary key), but there are other constraints on table size besides number of rows. If you have a 500 Gbyte hard drive and each record is 1 KB is size, your maximum number of rows will be 500 million (if you dedicate the entire drive to this single table, which is not a very realistic scenario). If you buy a 10 Tbyte hard drive, you may run into your operating systems file size limitation (for instance, I believe Ubuntu's maximum is 5 TB, so your limit will be 5 000 million terms instead of 10 000 milion - given the same assumptions about record size).


Remove number and reference list from mime mail plaintext emails Mime mail converts urls from "www.google.com" to "www.google.com [1]" in the plaintext version of email, and adds a reference list to bottom, "[1] www.google.com ". How do i remove this number and the reference list from the bottom of the plaintext email?

Edit: The mail itself has both, html and plaintext-version in itself. I want the users who view the plaintext-version of the email to not see the numbering.

I have found the solution. Mimemail creates the plaintext version of the mail in mimemail.inc, in the beginning of the function mimemail_html_body():

  if (empty($plaintext)) {
    // @todo Remove once filter_xss() can handle direct descendant selectors in inline CSS.
    // @see http://drupal.org/node/1116930
    // @see http://drupal.org/node/370903
    // Pull out the message body.
    preg_match('|<body.*?</body>|mis', $body, $matches);
    $plaintext = drupal_html_to_text($matches[0]);
  }

And here the drupal_html_to_text() creates the plaintext mail with the footnotes and the url numbering. The plaintext is created here if one is not provided already. So, the simple solution is to provide the plaintext version ourselves.

My email templates are defined by my implementation of hook_mail, as text without html (and mimemail in itself creates a html version of my emails, and in the above function, creates again a plaintext version of the mail, with the footnotes and url-numbering). So, I can provide a plaintext version of the email in my implementation of hook_mail_alter:

    function mymodule_mail_alter(&$message) {
        $message['params']['plaintext'] = drupal_html_to_text(implode("\r\n\r\n", $message['body']));
}

(The $message['body'] is the array containing the message, with message rows as entries in the array). This might not need to be wrapped around the drupal_html_to_text() function, but in case i go nuts and start inserting html into my messages, that function will strip it off. If i start to write my emails in html, I need to write a custom function (almost a straight copy of the drupal_html_to_text() function) to create the plain text version of my mails, but without the footnotes and url numbering.

Thanks for your help, I would not have found this solution by my self.


Security issues concerning including external code for module I would like to implement some external code in my custom module and if I understand correctly (correct me if I'm wrong), you can drop those folders in both sites/all/libraries as well as in sites/all/modules/custom/myModule/libraries.

What would the better security-wise place to include the folder be?

If you can think of another reason why to place it in the first folder or the second, I'm happy to hear it.

If your web server is set up correctly then both of the paths you've mentioned will have the same permissions (readable but not writeable by the server), so they would be equally secure/insecure depending on the rest of your server setup.

I must admit I haven't come across a path like the second one you mention, although I know most contributed modules that have been updated to Drupal 7 use the sites/all/libraries folder for storing external code libraries.


How to sort by condition in entityQuery I want to get a list that the items with a specific term in the top (like promote). The query would be like:

$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'news')
  ->sort('field_product_category', $tid, '<>') //Error <>
  ->range(0, 5);

Can I put calculation in sort condition? I do not want to make 2 queries.

I don't think you can sort that way with an entity query.  But with a select query, you have more flexibility.

I would try something like this:

$database = \Drupal::service('database');

$query = $database->select('node_field_data', 'nfd')
  ->fields('nfd', ['id']);

$query->condition('nfd.status', 1);
$query->condition('nfd.type', 'news');
$query->range(0, 5);

$query->leftJoin('field_product_category', 'pc', 'pc.entity_id = nfd.nid');
$query->addExpression('pc.field_product_category_target_id <> :target_tid', 'is_featured', [':target_tid', $target_tid]);

$query->orderBy('is_featured');
$query->orderBy('nfd.changed');

$matches = $query->execute()->fetchAll();


What is the convention for naming routes? Lets say I have these paths:

/admin
/admin/settings
/admin/settings/myentities
myentity/id
/admin/settings/myentities/id/edit
/admin/settings/myentities/id/delete

What would be the proper route names for each one of them?

My current usage is this:

admin

/admin

admin.settings

/admin/settings

admin.settings.myentities OR admin.myentities

/admin/settings/myentities

myentit OR myentity.view

/myentity/id

myentity.edit OR admin.myentities.edit OR admin.settings.myentities.edit

/admin/settings/myentities/id/edit

The things I mostly not sure about is whether I should use the path structure for the route name or not(ie. /path/to/some/where => path.somewhere OR path.to.some.where) and when it comes to entities if I should use admin.myentities + admin.myentities.myentity OR admin.myentity.edit) etc..

By design, the route name should NOT mirror the path.  You want to be able to change the path without breaking the route name, which is why other code in the system should refer to the route name only, not the path.  Having a route name that maps directly to the path is akin to a CSS class named .left-align-blue :-)

Some of these conventions are still shaking out.  However, for the typical case the recommended pattern is $module_name.$something_meaningful.  So in your mymodule module, you'd have routes like:

mymodule.settings
mymodule.advanced_settings
mymodule.status_page

And so on.  Note those tell you little about the path.  That's by design, as above.

For entities it's a little bit trickier since core has the advantage that most entities are the same name as the module.  Contrib doesn't always have that.  I would recommend either $entityname.$operation or $module_name.$entityname_$operation.  (I don't think core has any double-period route names at present, but I could be wrong.)

So if I were writing a module with a new entity called "nerd" (it's a candy site), I'd have:

nerd.view (for the page that lets you view a nerd)
nerd.edit (for the edit page)
nerd.delete (for the delete confirmation page)

And so on.  Make sense?


Defining Devel generation rules for custom nodes I have Devel module installed, I use it mostly for generating content.

I wanted to know if it was possible to define some custom rules to generate content for my custom nodes.

For example: I want the node titles to be fetched from a php array or another source instead of the automatic Lorem Ipsum fragments.

I've done some google researches but I can't find a starting point to do this.

Thanks

I usually create a simple custom module for migratig data from an external data source and no need to use devel for this kind of tasks.

you have a very good example here :

http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7

you can simply adapt the code and make a foreach loop on your array.


page.tpl.php override for Panels Pages? I want to use a specific tpl.php file for all Panels Custom pages.

I get some formatting issues if I try to use "Panels Everywhere" module, so would like an alternative.

You can use a template_preprocess_page function to add your custom tpl for Panels page. Here's how:

/**
 * Implements template_preprocess_page().
 */
 function MODULEORTHEMENAME_preprocess_page(&$variables) {
    if (module_exists('page_manager') && count(page_manager_get_current_page())) {
        $variables['theme_hook_suggestions'][] = 'page__panels';
    }
 }

Then create a page--panels.tpl.php for your custom Panels page.


Skip a form step programmatically in simple_multistep module I am trying to skip a step in multistep node form using Simple Multistep module. I have tried following snippet that works pretty good to skip one step.

$skipStep = $form_state->get('multistep_controller');
$skipStep->increaseStep();
$form_state->setRebuild();

However, it has a problem click on back button it doesn't come back.

I have search a lot but no luck, do anyone have idea?

I have solved it by using reduceStep() method to come back.

$skipStep->reduceStep();
$form_state->set('multistep_controller', $skipStep);
$form_state->setRebuild();

Hope this would help someone.


How to create custom date display format in drupal 7? I have created content type for an events in which I mentioned multiple values for date field. I want to display date like Nov. 2, 6 & 8   or Nov. 2-5, 12 2014 & Jan 22 2015

After some research I am able to create a view of event date field like

Nov 23 2014, Nov 26 2014, Nov 30 2014, Jan 03 2015 to Jan 05 2015

But still not getting format I want like

Nov 23, 26, 30 2014 & Jan 03-05 2015

If you are comfortable with coding then go for template file changes.
You have to do changes in node.tpl.php.

Else you can do also without coding refer https://stackoverflow.com/questions/8375674/how-can-a-custom-drupal-date-format-be-added

If you have created view for event display then it is easy to display date field as you want.
Go to date fields setting. There is a option for formatter. Like below screenshot. Here you can add custom date display format.


Why are there several branches at the official documentation (e.g. 8.0.x, 8.1.x)? Why are there several branches (e.g. 8.0.x, 8.1.x) at the official documentation?

Is it planned that sub versions of Drupal 8 will be developed independently?

If yes, then what's the point?
If no, then why are these branches mentioned in the documentation?

Drupal 8 made the switch to semantic versioning, and a shorter release cycle between minor versions.

Per release policy, there can be differences between minor versions.  In general, new minor versions are backwards compatible (or provide a BC layer), but can also introduce new features.  In addition, as minor versions get released, some functionality remains but becomes deprecated.

This is why there is different documentation for different minor versions; the document actually is slightly different.

To keep on top of changes in Drupal 8, monitor the list of Change Records or the Twitter account that announces each new one.


Rearrange Date input field rendering In a function that is a response to a drupal_get_form() I am constructing a form that includes a date field

$form['dob'] = array(
    '#type' => 'date',
    '#date_format' => 'm-d-Y',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
);

This however displays the the input with year first then month and date. How can I change this to render the month first then day and then year?

You need to change #type value to date_select

So your code should look like this

$form['dob'] = array(
    '#type' => 'date_select',
    '#date_format' => 'm-d-Y',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
);

If you want text field instead of select dropdown menu you can change date_select to date_text


Bypass drupal theme with hook_menu() function? I have a page within Drupal administration where I want to bypass all of the normal Drupal theming and calculations to only show the HTML that's returned by the function. Is this possible?

 $items['admin/special_blank_page'] = array(
    'title' => 'PDF',
    'page callback' => 'special_blank_page',
    'type' => MENU_LOCAL_TASK,
  );

//...

  function special_blank_page(){
      $html ='Only show this HTML';
      return $html;
  }

Just to offer an alternative to Ayesh K's solution, you can set the delivery callback of your menu item

  The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal_deliver_html_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal_deliver_html_page() for an example.


Undefined index: und on .tpl.php for content type How can i fix the error message?

  the error message is Notice: Undefined index: und in include() (line
  9 of /var/www/html/sites/all/modules/custom/theme/icons.tpl.php).

my code is:

<?php
global $language ;
global $base_url , $base_path ;
$lang = $language->language;
$count = 0;
foreach ($data as $kay => $node_obj) {
    $node = node_load($node_obj->nid);
if (isset($node->field_description[$lang])) {
    $img_url = $node->field_icon['und'][0]['uri'] ;
$count++;

?>

I fix it by

add

!empty( )

like this

$img_url = !empty($node->field_icon['und'][0]['uri']) ;


Importing external resources via REST as nodes or other entities I'm just getting my feet wet with Drupal 8, having written a decent amount of modules for various projects for Drupal 6 and 7. We are trying to leverage Drupal as a CMS add-on to our club management software. A lot of our customers have asked us both how we would integrate into an external system and also how we could provide customer websites. We've decided to try and leverage Drupal 8 to provide a hosted CMS to our customers.

We are developing a REST API for our product that will expose various resources such as Events, Equipment items, Equipment Reservations, etc... What we want to do is have those available in Drupal, preferably as full-fledged entities so that customers could add additional information to these items that is stored with Drupal. For an example, we would provide an Event object via our API and then a customer could add a "photo gallery" field in Drupal to add photos to the event.

We'd also show an events and equipment usage calendars using data from our product, likely as blocks.

What I'm somewhat stuck on is how to define an Entity without storing it in the SQL database. We want our system (via REST) to be the canonical source with addons and UI provided by Drupal.

Can anyone point me in the right direction as to how I could create an entity type with its core storage outside of Drupal and linked via an API?

I should note, I already found the External Entities module, but I don't see how it exposes the external entities as viewable or fieldable objects.  Perhaps I'm just missing something here?

Thanks in advance!

I haven't looked at that module yet, but pretty much everything that involves the storage of an entity goes through the storage handler of a given entity type.

Drupal 8 provides to real implementations, SqlContentEntityStorage for content entities stored in the database and ConfigEntityStorage for config entities stored in configuration. And a few test and example implementations too.

So the first thing you need to implement is your own storage. Do whatever you want in the relevant methods like load()/save()/delete(), see EntityStorageInterface.

Additionally, you will have to implement a entity query, so you can create lists with conditions, sorts and so on. That also comes from storage (getQuery()), initialized based on a given service name, see for example entity.query.sql and entity.query.config. That's a factory that returns the actual query object and in there, you can again do whatever you want. For content entities, it's transformed to an SQL query while config entity queries are actually mostly implemented in PHP, with some optimizations and lookups.

If you also want to use views, you have to write a backend for that too, since it doesn't use entity query (yet). There's https://www.drupal.org/project/efq_views, not sure how far it is for Drupal 8.


How on node forms do I set multiple vertical tabs to be always open? How can I make sure that the Menu Settings part when editing a node is always open just like the published section. See the image below.

You can do this with the hook_form_node_form_alter. Add the following to a custom module.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YourCustomModuleNAme_form_node_form_alter(&$form, FormStateInterface $form_state){
  //- MENU SETTINGS
  $form["menu"]['#open']                 = TRUE;
  //- COMMENT SETTINGS
  $form["comment"]["widget"][0]['#open'] = TRUE;
}

Change the value of #open to true to show the menu as openend.

In some cases it is necessary to move this hook implementation to the end of the list. Because the menu group added by menu_ui Module can overwrite your settings to #open false again. For this you can use the following:

/**
 * Implements hook_module_implements_alter().
 */
function YourCustomModuleNAme_module_implements_alter(&$implementations, $hook){
  switch ($hook) {
    // Move our hook_form_FORM_ID_alter() implementation to the end of the list.
    case 'form_alter':
      $group = $implementations['YourCustomModuleNAme'];
      unset($implementations['YourCustomModuleNAme']);
      $implementations['YourCustomModuleNAme'] = $group;
      break;
  }
}


Problem with PDO MySQL For the last couple of days I've been getting the following error:

  Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /home/mydomain/public_html/drupal/includes/database/mysql/database.inc on line 46

This comes after my Hosting did an upgrade and PHP is now version 5.2.17.  From what they have told me, I think I have to enable a PDO MySQL extension in php.ini.  The problem is I'm on a shared hosting and I don't have access to the file; also, my Hosting said they can't change it either.  My info.php shows:

  PDO

  PDO support enabled
     PDO drivers sqlite, sqlite2

  pdo_sqlite
     PDO Driver for SQLite 3.x enabled
     PECL Module version (bundled) 1.0.1 $Id: pdo_sqlite.c 293036 2010-01-03 09:23:27Z   sebastian $
     SQLite Library 3.3.7

I tried modifying the .htaccess file and/or adding my own php.ini file to the root directory per some suggestions I found, but nothing I've tried has worked yet.

Can anyone please suggest what else I could do?

EDIT:

Once again I asked the Hosting to enable PDO_MySQL extension and their answer was that they could not, that cPanel (to which they migrated from Plesk, causing this whole problem) had this extension disabled by default and changing it would affect their servers.  Their solution?  That I would change my programming to adjust to these new features, which I wouldn't even know how to go about.  Are they right requesting that I do this? Is there any other way?

Your hoster needs to enable that extension. I don't think you can do that in a local php.ini file.

I don't believe that they can't do it, they just need to add an extension=pdo_mysql.so to the php.ini, install the package, depending on whatever setup they are using. It's their job to do that, pdo_mysql is a hard requirement for Drupal 7.


How do I create a dynamic query that filters on month and day? I want to get the list of the nodes, whose content type is Donors, where the date in the field_data_field_donor_date_of_birth matches today (except the year).

How can I achieve it using a dynamic query or the EntityFieldQuery class?

This is the code I tried so far.

$query = db_select('node', 'node');
$query->fields('node', ['nid','title'])
  ->condition('node.status', 1)
  ->condition('node.type', 'CONTENT_TYPE_DONOR');

$query->innerJoin('field_data_field_donor_date_of_birth',
 'field_donor_date_of_birth'
, 'field_donor_date_of_birth.entity_id = node.nid');
$query->condition('field_donor_date_of_birth.field_donor_date_of_birth_value', $birth_date, '=');

$result = $query->execute();

I was able to query the date by using a where clause instead of condition.
Example, replace

 $query->condition('field_donor_date_of_birth.field_donor_date_of_birth_value', $birth_date, '=');

with

$time = format_date(time(), 'custom', 'm-d');
$query->where("DATE_FORMAT(field_donor_date_of_birth.field_donor_date_of_birth_value, '%m-%d') = '$time'");


how to create a view that shows blogs count for a user? I want to create a view that list out the following fields

User name
User email
Discussion count
Blog count

I created the view and add the User: Name and User: Email in the fields but it shows me the duplicate users and Also I have no idea about how to add the discussion count and blog count to the view.

I have created the view of node type.
Any help?

I'm going to take a stab at answering this. Create a view where:

Under Fields you select the User name, email and User:Uid. Then add a custom field.
Under the custom field write a query in Value:

<?php $result = db_result(db_query("SELECT COUNT(nid) FROM node where uid='%s' and type='blog'",$data->users_uid));
echo $result;
?>

This query find the number of posts written by each user.

Under filters choose Node:type = 'content type used to store profiles'
(as you want to count the number of blogs of every user who has a profile).


Custom entity api admin UI overview table how to add extra columns and operations? Drupal 7 I've seen this: Custom entity operation links but it's for Drupal 8 and dealing with nodes whereas mine is a non-node type entity.

So how does one go about adding stuff to the row? I want to add custom operations and basically get control of it but I can't see where to start.

I've extended EntityDefaultUIController in the conventional way (like this). When you go the administrative UI we can debug and break in entity.ui.inc and see the following code snippets which seems to be where this gets invoked. But I've got a feeling that there's a quicker and easier way than adding extended versions of the already existing EntityDefaultUIController functions. But what holds the operations & additional column row information?

entity.ui.inc

within overviewTable(...) ...

foreach ($entities as $entity) {
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);
}

... which leads us to the following function (same file)

protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {

and we get use of $additional_cols in the 4th (0th + 3 in array speak) parameter but as you can see it's not passed as a parameter above so how do you go about getting this additional information added into the overviewTable?

    // Add in any passed additional cols.
    foreach ($additional_cols as $col) {
        $row[] = $col;
    }

I figured out how do do this, and it, of course, isn't terribly straightforward...

You're on the right track, you just need to override the EntityDefaultUIController::overviewTable function in your own custom class. I don't think there's an easier way (since you're looking for one).

So, copy the the implementation of overviewTable from EntityDefaultUIController (in entity/includes/entity.ui.inc in the Entity API module) into your custom ui controller class and look for the calls to:

$this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);

...and add the $additional_cols parameter which should be an array populated with the extra data (which you can pull from the $entity object already populated in the foreach loop. So, do something like:

foreach ($entities as $entity) {
  $additional_cols = array($entity->someField, $entity->someOtherField);
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity, $additional_cols);
}

In addition to that you'd have to add the associated headers into the render array at the end of the overviewTable function like so...

$additional_headers = array('some field', 'some other field');

$render = array(
  '#theme' => 'table',
  '#header' => $this->overviewTableHeaders($conditions, $rows, $additional_headers),
  '#rows' => $rows,
  '#empty' => t('None.'),
);

...my guess is that you already figured out this much, but to answer your question, no, I don't think that there's an easier way. I hope this helps you, or someone else. ...or if someone knows this easier way, let me know too... =)


How to create a rule which asks the user whether to proceed or not? With the D7 version of the Rules module, is there any way to create a rule which asks the triggering user whether to proceed or not?

Specifically, I'm trying to set up an "After updating existing content" rule but I would like it to ask the user "Do you wish to <action>? Yes/No" then continue executing if they choose "Yes" or halt and return to the node view if they click "No".

I was hoping it could be done within the rules UI somehow but if I have to code a custom module, so be it.

I've looked through all the modules in the "Rules" category on drupal.org and I've looked at all the available rule conditions in the rules UI but I haven't found anything useful so far.

You might want to check, and experiment with, the Rules Link module. Here is an excerpt from its project page:

... lets you create links which trigger arbitrary functionality with the help of Rules.
There are three types of links (usages):

Javascript - Links that will trigger the rules using Ajax.
Token - This are basic links, that will reload the page after calling them.
Confirmation link - Show a confirmation form before executing the rule

The module's Readme.txt contains some more documentation about how to use it.
Example Configuration

Define a rules_link with a "Link type" of "Confirmation" and make sure to define a "Path" for it, e.g. http://example.com/confirmation-page.
Edit the rules_link you created and go to "Configure rules" then create a "Reaction" rule containing all the actions you want to take if the user clicks "Confirm" on the confirmation page.
Create a normal rule for the particular event you want to trigger the confirmation page on (in this case we're using an "After updating existing content" event).
Add whatever conditions you might require then add a single "Page redirect" action where the "URL" is defined as the path to the rules_link confirmation page plus a node ID token and a destination parameter, e.g. confirmation-page/[node:nid]?destination=node/[node:nid].

With this configuration, when the user updates a node with nid 12345 they are redirected to "http://example.com/confirmation-page/12345?destination=node/12345". If they click "Confirm" the rest of the required actions are executed before returning to the updated node. If they click "Cancel" they return directly to the updated node without any further actions executing.


Highlight the argument passed in the exposed filters I have a view page like http://localhost/drupal/myviews, which looks like in the following screenshot:

I pass arguments to this page using a URL like http://localhost/drupal/myviews/voc3; the page looks like in the following screenshot:

So all this works fine.  When the argument is passed within the URL, can I highlight that argument in the exposed filter?

I was able to create a solution for a regular Taxonomy: Term ID (no depth) filter, so this may not be applicable for you (the filter with depth was behaving erratically for me).

This code will set the dropdown element to the term provided in the argument, and will defer to the dropdown selection if one is chosen.

Add this to your custom module and then flush caches:

function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'name_of_view') {
    if(!isset($_GET['tid'])) {
      $arg = arg(1);
      if(isset($arg)) {
        $selected_value = array_search($arg, $form['tid']['#options']);
        if(isset($selected_value)) {
          $form_state['input']['tid'] = $selected_value;
        }
      }
    }
    else {
      $form_state['view']->args = array();
    }
  }
}

You can try changing every instance of 'tid' to 'term_node_tid_depth' if you are going with a Taxonomy With Depth filter (use a dpm($form) to verify the filter name).