Drupal: Multilingual SEO website I am trying to build a simple website with a blog. The website needs to have, at least, 4 languages and SEO optimization (Title Description Keywords).
Please advise me on which modules to use and if there is any how-to tutorials to do so. Are there any pre-made profiles I can use?
In the end I would like to create a profile which I will replicate for feature projects.

For a multilingual Drupal 7 site you could enable the Locale and Content translation modules, they are both included in the Drupal Core.

Also, you might want to check the Internationlization module and the Entity translation module.

Basically you start of by adding languages to your site, you can do this in the administration area (/admin/config/regional/language). After that you can allow content types to be translated (/admin/structure/types). When you add a node you will then be able to choose between the enabled languages.

As for SEO: you could check the Drupal SEO Tools, it has a huge list of modules that you can use.


Alter hook_field_formatter_view? What is the best way to alter field output? I found "hook_field_formatter_view" but seems nothing like "hook_field_formatter_view_alter" exists. In my case I have address fields (Addressfield module) which used in "Shipping" and "Billing" panes on DrupalCommerce's checkout page. I want to add some js to these fields, preferable using Drupal's Form API "#attached"

You may want to try to alter it with a preprocess function:

function example_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if ($field_name == 'field_example_field') {
    // Your code here.
  }
}

I ran a test to modify $variables['element']['#attached']['js'] but Drupal didn't recognize the changes to the element. Not sure why. So, you may have to use drupal_add_js.


modify date token in View to extract only year? We have a content type using a date field, in which the date is entered in the format mm/yyyy. An example entry might be 04/2016. In one particular View, we want to use only the Year value. It appears the token for this field is

[field_delivery_date-value]

In the Rewrite area for this View field, is there an operation that can be performed on the token in order to extract and display only the year value? Or would this need to be done in another way, not using tokens and the rewrite option?

Steps to get the just the year for Delivery Date field

Navigate to /admin/config/regional/date-time/formats page.
Click on Add Format button (/admin/config/regional/date-time/formats/add)
In the Format string text field add Y and save it.
Now add a date type by navigating to /admin/config/regional/date-time page.
Add a new date type and use the the format that we have added in the previous steps.
In the view select the type you want the date to be rendered.

So instead of Rewriting the output, you would directly get the year.

Hope that this will help you.


How to display the pager on top and bottom of a custom search results page? I have used the core Search Page functionality in Drupal 8 to built a search engine on my site.  The pager is displayed at the bottom by default. How can i display the pager on the top also?

Note: I have not used views to built the search page.

Thanks!

You could use CSS

.[wrapping-div-class] { position: relative; }
.[wrapping-div-class] .pager { position: absolute; top: 0px; }


Problem installing Drupal 6.22 with Drush I'm trying to install Drupal 6.22 with Drush 4.4 on my CentOS 5.6 box, but am having problems getting it to work.

I run the following command:

drush dl drupal-6.22 --drupal-project-rename=drupal1

Then I run:

drush status

and get:

 Drupal version         :  6.22
 Default theme          :  garland
 Administration theme   :  garland
 PHP configuration      :  /etc/php.ini
 Drush version          :  4.4
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/html/drupal1

Which seems to suggest that all was downloaded properly.

Then I run the following command to start setting it up:

drush site-install standard --account-name=admin --account-pass=REMOVED --db-url=mysql://admin:REMOVED@localhost/drupal1db

It asks me if I want to continue and I choose 'yes'. After a second or two, it returns me to the command line prompt.

Then I run 'drush status' again, which returns the following error:

Table 'drupal1db.access' doesn't exist                [warning]
query: SELECT 1 FROM access WHERE type = 'host' AND
LOWER('127.0.0.1') LIKE LOWER(mask) AND status = 0 LIMIT 0,
1 database.mysql.inc:135
Table 'drupal1db.cache' doesn't exist                 [warning]
query: SELECT data, created, headers, expire, serialized FROM cache
WHERE cid = 'variables' database.mysql.inc:135
Table 'drupal1db.variable' doesn't exist              [warning]
query: SELECT * FROM variable database.mysql.inc:135
Table 'drupal1db.cache' doesn't exist                 [warning]
query: UPDATE cache SET data = '', created = 1309816902,
expire = 0, headers = '', serialized = 0 WHERE cid =
'variables' database.mysql.inc:135
Table 'drupal1db.system' doesn't exist                [warning]
query: SELECT name, filename, throttle FROM system WHERE type =
'module' AND status = 1 AND bootstrap = 1 ORDER BY weight
ASC, filename ASC database.mysql.inc:135
Table 'drupal1db.url_alias' doesn't exist             [warning]
query: SELECT COUNT(pid) FROM url_alias database.mysql.inc:135
PHP Fatal error:  Call to undefined function filter_xss() in /var/www/html/drupal1/includes/common.inc on line 655
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Call to undefined function filter_xss() in
/var/www/html/drupal1/includes/common.inc, line 655

I go to the Drupal directory in my browser and it just shows a blank white page.

Any ideas?

I had a similar problem when trying to install Drupal 6.26 with drush 4.5 and 5.0 (I tried both).

You do not have to create the database.  You can but drush will drop it and re-create it.

I fixed my problem by doing :

drush site-install default --db-url=mysql://drupaldbuser:REMOVED@localhost/drupal-6-25

I used the profile default rather than standard since drupal 6.x uses default as the default profile.  The standard profile is the new default name in Drupal 7.

http://drupal.org/node/1410242#comment-5795114
http://knol.google.com/k/how-to-install-drupal-with-drush


Form API multiplie file upload validation error I have a simple form with a multiple file upload field. I am trying to validate the documents against extensions and file size. The validation seems to work, but now if I don't select any file (field is not required), the validation fails and I get an error:

  Fatal error: Call to a member function getError() on a non-object in /home/www/test/core/modules/file/file.module on line 726

Here is my validation function:

public function validateForm(array &$form, FormStateInterface $form_state) {

  $validators = array(
    'file_validate_extensions' => array('pdf doc docx xls xlsx txt jpg jpeg png gif'),
    'file_validate_size' => array(7 * 1024 * 1024), // 7MB file size limit
  );

  /** @var File[] $documents */
  $documents = file_save_upload('documents_upload', $validators, 'public://');
  $error = false;
  if(null !== $documents) {

    foreach($documents as $i => $document) {
      if ($document === FALSE) {
        $error = true;
      }
    }

    if ($error === true) {
      $form_state->setErrorByName('documents_upload', 'Error: could not upload file.');
    }
  }
}

Any idea?

This happened to me today. After some research it's appear that Drupal8 have a bug with empty file form element when this one is multiple.

The file_save_upload function expects an array looks like this when element is empty :

 ['form_field_name' => NULL]

But actually for an empty multiple file form element the array is:

 ['form_field_name' => [0 => NULL]]

So the condition check for an empty value and fail. The code continue until it try to use getError() on a null value.

Here is a function to check if a file were uploaded or not. You can use it in the validateForm callback of your form class or in a hook.

function isFileUploaded($form_field_name) {
  $all_files = \Drupal::request()->files->get('files', array());

  return isset($all_files[$form_field_name]) &&
    !empty($all_files[$form_field_name]) &&
    NULL !== reset($all_files[$form_field_name]);
}

It's not very pretty but it'll work until they fix that bug.


How to pass multiple values in setArguments() and render view? I want to pass multiple values in setArguments() and render view. I'm using below code but it's showing only 1 value instead of multiple.

 public function _ajax_generate_request_view(array $form, FormStateInterface $form_state) {
  $view = \Drupal\views\Views::getView('play_center_generate_request');
  $view->setArguments(array('23','46'));
  $view->execute();
  $render_view = $view->render();
  $ajax_response->addCommand(new HtmlCommand('#view_wrappers', $render_view));
  return $ajax_response;
}

Depends if you need OR or AND clause :

$view->setArguments(array('23,46'));
$view->setArguments(array('23+46'));

One string for each argument.


How to create a contact form using FAPI in a custom module? I want to create a contact form using FAPI my custom module.

I created 2 files: one is .info and the other is .module. But I do not understand how I should link that module with my template name page--contact-us.tpl.php as I already activated that module from module list.

I used the code below in my module_name-module:

<?php
  function my_module_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
  );
  $form['company'] = array(
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#type' => 'textfield',
  );
  return $form;
  }

And in my template.php file I wrote this code:

<?php
 function mytheme_theme($existing, $type, $theme, $path) {
 $items['my_module_form'] = array(
 'render element' => 'form',
 'template' => 'page--contact-us',
 'path' => drupal_get_path('theme', 'mytheme') . '/template',
  );
  return $items;
  }
  ?>

Finally I wrote a single line of code in my page--contact-us.tpl.php file to check whether a name field is appearing or not:

<?php print render($form['name']); ?>.

But nothing is happening on my contact-us page ... Why?

UPDATED: I also implemented hook_menu, here it is:

 function form_module_menu() {
 $items = array();
 $items['contact-us'] = array(
 'page callback' => 'drupal_get_form',
 'page arguments' => array('form_module_form'),
 'access callback' => TRUE
 );
 return
 $items;
 }

When dealing with Form API in Drupal 7 there are two major steps:

Step 1: Create and implement the form in a module

In this step 1, you will setup the form, and then validate and submit the form, as further detailed below.

a) Setup the form

    function form_example() {
       $form['first_name']=array(
       '#type' => 'textfield',
       '#title' => t('First name'),
       '#description' => t('Enter first name'),
        );
        $form['last_name']=array(
        '#type' => 'textfield',
        '#title' => t('Last name'),
        '#description' => t('Enter last name'),
        );
    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
        );

    return $form;
    }

    function form_example_validate($form, &$form_state) {

    }
    function form_example_submit($form, &$form_state) {

    }

b) Validate and submit the form

Now the form is ready to be displayed.

One way to display the form, is to theme the form in the module and then print the form.

function mytheme_theme($existing, $type, $theme, $path) {
   'theme_contact_form' => array (
        'variables' => array(
            'contact_form' => FALSE,
            ),
        'template' =>'theme-contact-form',
    ),
 }
function mytheme_block_info() {
   $blocks['block_contact_form'] = array(
      'info' => t('My Theme Contact form'),
      );
   return $blocks;
}
function mytheme_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'block_contact_form':
        $block['content'] = array(
            '#theme' => 'theme_contact_form',
            '#contact_form' => drupal_get_form('form_example'),
            );
        break;
  }
  return $block;
}

Then create theme-contact-form.tpl.php in the module file and print the form:

<?php print render($contact_form); ?>

With all previous steps complpeted, the form is created and implemented in the module.

Step 2: style the form

To style the form from theme layer, refer to How to a use a template file to theme a form?


New Account, change Duplicate E-mail error I run a drupal / civicrm build for a non-profit.  We are very careful with our members information, and want to make sure that no one trying to, would be able to figure out if someone they knew was a registered user.

The problem we have is when someone goes to create a new user account, if they use an e-mail that is already on our site, they get an error message saying that they can't use that e-mail because it's already registered on the site.

There are plenty of people - bosses, spouses, etc who could be testing an e-mail address to see if someone they know is on our site, and this error message pretty much confirms it.

Is it possible to change the error message to something else?  We have the e-mail confirmation enabled, why can't it say, "An e-mail has been sent to abc@xyz.com with your login information?"

You can do a couple of things. One, I would advise installing the Username Enumeration Prevention module:

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

This will stop forgot password form abuse.

Secondly, hiding this fact on the registration side is hard. You can't have duplicate email or usernames in Drupal (not easily), and if you get an error on that then it is pretty apparent it is already in use. Giving a vague error here could also confuse actual users who are trying to register.


Custom Theme Repository update I have a custom theme that I use in several websites.
My theme is on gitlab.
I can download my theme by composer in different websites.
My problem is when I update repository theme with a fix or new feature and then this do not mirror on websites, even if I delete theme folder and composer.json info, it's always stuck on the same version.
My composer.json of theme repository
{
"name": "test/test-theme",
"description": "Drupal Custom Theme",
"type": "drupal-custom-theme",
"minimum-stability": "dev",
"require": {}

}
My composer.json from the website:
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "package",
        "package": {
          "name": "test/test-theme",
          "version": "dev",
          "type": "drupal-custom-theme",
          "source": {
            "type": "git",
            "url": "{URL}",
            "reference": "master"
          }
        }
      }
],
"require": {
    "test/test-theme": "dev",
 }

How can I update my theme last features with composer?

We had a similar setup. But the only difference is we create a new tag for every update in the theme repository. So we just reference the new tag in  website composer.I would suggest you to try that instead of referencing branch so you get updated code on every compiser update.
If you are not interested in doing in that manner I would suggest you to clear composer cache and execute composer update you will probably get the updated code.


How do I get the default billing/shipping customer profile in code? Is there a way to get the default billing/shipping customer profile from a user?

I'm getting all customer profiles with:

$profiles = commerce_customer_profile_load_multiple(array(), array('uid' => $user->uid));

But which customer profile was set as default by the user?

You can get default user profile address with

commerce_addressbook_get_default_profile_id($uid, $type)

Returns the default profile id for a specific uid and profile type.

@param $uid
    The uid of the user whose default profile id should be returned.

@param $type
    The type of customer profile to look up.

@return
   The id of the default profile if set, FALSE otherwise.

An example if want get  current user shipping addresss use below code :

global $user;
$default_pid=commerce_addressbook_get_default_profile_id($user->uid,'shipping');


How to add a field to a group with form_alter I have a group in a node set as a vertical tab, and I want to add some markup into this vertical tab via code. How can I do it?

Thanks!

Let's say that you are doing this in a module named custom.

First, take a look at how the form is structured using dsm($form) in custom.module.  Make sure you have the devel module enabled and that you have permissions to see devel's output.

<?php

custom_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

That will give you the structure of the $form array, which you can then add your markup to.  So, let's say that you want to add some markup to the author pane in the vertical tabs.  From the output from dsm($form), we see that we are working with $form['author'].

So, in custom_form_alter(), we simply add the markup element we desire using the standards documented in the Drupal 7 Form API.

In the code below, I also give the custom element (which I have aptly named "custom") a weight, so it appears above the other elements.

/**
 * Implements hook_form_alter().
 */
function custom_form_alter(&$form, $form_state, $form_id) {
  // Add custom markup to the "Authoring Information" tab when adding or editing a page.
  if ($form_id == 'page_node_form') {
    $form['author']['custom']['#markup'] = 'Text goes here';
    $form['author']['custom']['#weight'] = -9;
  }
}

Also, rather than using an if statement to target the form id, I could have used hook_form_FORM_ID_alter(), like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_form_page_node_form_alter(&$form, $form_state, $form_id) {
  // Add custom markup to the "Authoring Information" tab when adding or editing a page.
  $form['author']['custom']['#markup'] = 'Text goes here';
  $form['author']['custom']['#weight'] = -9;
}


How to show/hide a link based on a permission? I'm looking for a way to hide/show a link from the main-menu if the current user has a specific permission. The menu item has already been created and the menu item links to a node that is controlled by hook_node_access().

By default, Drupal will hide all menu items that the user doesn't have access to, so the easiest thing to do, it to require the selected access for the page that the menu item is linking to.


What does the term 'Bootstrap' mean? Referring to https://www.drupal.org/project/health_check

I am confused as to what 'If Drupal fails to bootstrap' means.

What is term 'bootstrap' referring to? Does it make a database call? From what I have read bootstrap can mean from the Drupal core.

So if the healthcheck module fails is it because it cannot see the database, will the module render a 200 or some other response code?

In computing, "bootstrapping" refers to software getting to a state to where it can perform the task being requested.

In the context of Drupal, it means the code starts and does everything up to the point where it generates the page.  It more-or-less includes

connecting to the database
reading configuration
loading modules

The bootstrap process is pretty much the same for everything request; what happens when a page gets rendered and sent to the browser differs page-to-page.

So, when "Drupal fails to bootstrap", it means that it wasn't able to get to a point to figure out what to do, and is considered a Fatal Error.  In my experience nine times out of ten when it happens in a production environment, it is because there was a problem connecting to the database.


How to display results tagged with just one term ID when there are multiple filters I have a blog in Drupal 7 and used Views to display the fields.  I have 2 sets of tags displayed on the sidebar:

1) SHAPES

Triangle

Square

Rectangle

2) COLOR

Red

Blue

Green

I created the 2 groups of tags via Structure > Taxonomy > Vocabulary > Add Term

For the View, I created one View with two exposed filters (similar to what was done in this tutorial)

VIEW:

Path: '/blog/tag'

Filter Criteria:
    1) 'Content: Shape (exposed)'

        Exposed form in Block: 'Yes'

        Filter identifier: 'shape_id'

    2) 'Content: Color (exposed)'

        Exposed form in Block: 'Yes'

        Filter identifier: 'color_id'

Exposed form style: BEF

The exposed filters are set to the appropriate block region in Structure > Blocks.

If I click 'triangle', only blog posts tagged with 'triangle' should be displayed.  Then if I click 'red', only posts tagged with 'red' should be displayed.

It looks like the correct blog posts are being displayed when I click on the terms.  The URL gets appended with IDs from both vocabularies, but I can't seem to get the right combos to display.

Desired URL when 'triangle' is clicked: '/blog/tag/?shape_id=1&color_id=All'

Desired URL when 'red' is clicked: '/blog/tag/?shape_id=All&color_id=1'

So, essentially the results should display items tagged with just one term ID.

However, how it is currently working is that if I click 'triangle', and then 'red', both 'triangle' and 'red' have the 'selected' class (are both bolded) and the url is: '/blog/tag/?shape_id=1&color_id=1'

The only way I was able to get the desired URLs is if I have the '-Any-' option displayed.  However, the use case I have is to NOT have '-Any-' listed in the list of tags.

Is this even possible without '-Any-' listed in the list of terms?  I have never used multiple exposed filters before, so any guidance would be great as I've researched this for almost a week now. I read in another post that contextual filters would allow me to create separate path aliases that are clean urls, but I have not been successfully able to do this.

Any help would be greatly appreciated.  Thank you for your time.

When I tried using the taxonomy term pages approach, I could not figure out how to get the fields displaying properly.  The fields displayed were based on the teaser in my Blog content type.  And using exposed filter option was not a solution since my use case was to only display results based on one tag.  What worked for me:

1) Add new view to existing Blog View

2) FORMAT: 'Unformatted list'
    SHOW: 'Fields'

3) FIELDS: [add fields that you need displayed]

4) FILTER CRITERIA: 'Content: Published (Yes)'; 'Content: Type (= Blog)'

5) PATH: '/blog/[YOUR VOCABULARY NAME]/%'

6) CONTEXTUAL FILTERS: 'Content: Has Taxonomy Term ID'

WHEN THE FILTER VALUE IS NOT IN THE URL: 'Display all results for the specified field'

WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED: select 'Override title' and in the input field, enter: '[YOUR VOCABULARY NAME]/%1'

select 'Specify validation criteria'

Validator drop-down, select 'Taxonomy Term'

Vocabularies: select appropriate Vocabulary name

Filter value type drop-down: 'Term name converted to term ID'

select 'Transform dashes in URL to spaces in term name filter values'

Action to take if filter value does not validate: select appropriate one that works for your needs (in my case: 'Display contents of "No Results found"')

If you need to display the term name in the heading on the results page, in the same view > HEADER > Add 'Global: Unfiltered Text' > then in text area, add something like "VIEWING RESULTS FOR [YOUR VOCABULARY NAME] / %1"

Save the View.  Since I had multiple filters, I cloned the above view and renamed everything. So, I ended up adding 3 additional views to my existing Blog View.

I had previously set URL aliases for Taxonomy Term Paths, so I removed these

Also, I had to go back to my Taxonomy Terms individually and delete the URL alias that was generated from the pattern

To have the list of tags displaying on the right with the desired URL structure of /blog/[YOUR VOCABULARY NAME]/[YOUR TERM NAME], I created a separate new view:

SHOW: 'Taxonomy Terms' of type '[YOUR VOCABULARY NAME]'

Create a Block

'Unformatted list' of 'Fields'

FIELDS: 'Taxonomy: Term Name' > click this and unselect 'Link this field to its taxonomy term page'.  Then expand "Rewrite Results" section and select 'Output this field as a link' > in the Link path: 'blog/[YOUR VOCABULARY NAME]/[name]' (the [name] at the end of the url structure should appear as you see it with the square brackets) > select 'Replace spaces with dashes' > Transform the case to 'lower case' > click Apply

FILTER CRITERIA: 'Taxonomy vocabulary: Machine Name (= [YOUR VOCABULARY NAME])'

Save the View

Then in Structure > Blocks, place the block in the appropriate region

Hope this helps someone!


How do I get the display id of a view in Drupal 6? I'm trying to use the views_data_export module to get the content of a Drupal 6 view in xml format. On the module's page, it says to use this command:

drush views-data-export [view-name] [display-id] [output-file]

I can figure out the view name well enough, but how do I get the display id?

Edit the view, then hover over the tab link for your display.  Look at the URL.  It will look something like:

http://thesite.com/admin/build/views/edit/the_view_name#views-tab-the_display_id

You should be able to use "the_view_name" and "the_display_id" in the drush command.


Aligning the Article/Node Title next to image I've been working on a theme just in my spare time and I'm trying to style the way the article/node is displayed. Currently its simply formatted to:

title
submitted info
image
Short summary/description
read more / login

I want the field layout to be somewhat like the one they use on the League of Legends website (I believe that site is using Drupal)I want to make it so they layout is basically like this part of the site:

However I am unsure how to do this and what files I need to edit, I've been styling the rest of the site using responsive.css however I'm not sure how to change the layout and style it all.

Any help with this would be much appreciated.

Thanks,
Ben

There are several ways you can go about re-structuring your html.  Two options would be:

Overriding / creating template files for the content type that you
are trying to modify.
Using a contrib module like Display
Suite which gives you an interface to
easily modify a content types structure and classes.


Drupal Commerce - Product Variation Type missing Nodes I've installed kickstart 2.0 with the demo data.
I tried creating my own product variation types and product displays.
I can't see to get my products to display in the same way to the commerce built-in demo products.

I think this is my custom product variation type seems to be missing the correct "Node: Product list" and "Node: Full Content" options (Product Variation Type -> Manage Display section)

Please see attachments.
"Tops" is the built in product variation type delivered with CK 2.0.
"Photos" is a product variation type i created.

Drupal commerce is my first exposure to drupal hence my knowledge of nodes isn't sound, please let me know what I'm missing?

You can add and remove Displays to your content types by expanding the 'Custom Display Settings' section right under all those fields in the 'Manage display' tab.  It's hard to notice because it's collapsed by default.

You'll probably see a different list than me, because it also depends on the modules you have enabled on your site:

However, my feeling is that - though I haven't used kickstart and its examples - the differentiation in the look of your content type and theirs also has a lot to do with theming.  That's a big topic, but I'd check to see whether there are templates and css styles that apply to those sample content types that you can copy over to yours...


How can I create a new content type based on an attached format I'm creating an intranet company portal website and the HR department requests I create a new Content Type/View for employee records. They sent me a document based on the format they would like. I was hoping to get some input on the easiest way of creating this content type/View

I uploaded the format to the following snapshot:

My questions are as follows

How can I format the Expiration Date field to align to the right of it's specific corresponding field
When adding new content with the HR content type, is it possible for the user to click "Add new Incident/Disciplinary/Recognition field"? For example, start with one field for each but if the employee has earned more rewards etc they can add a new field?

Thank you for your help

1)
Place each expiration field above the corresponding other field and then add the following CSS rules to your theme:

form.node-form .field-name-field-product-EXPIRATION-DATE {
position:absolute;
right:0;
width:200px;
}

On the content creation pages, this will move the expiration field to the top right of the field below.

2) Yes, users can add an unlimited amount of values to each field. To enable this go to the desired field in your content type and edit it. There look for "Number of values" near the bottom of the page. Choose the desired amount. Suppose you choose 5, the user creating the content can add up to 5 values for this one field. I hope this works out for you.


Is it possible to use a condition set component as a parameter for another component? Some of my Rules (say they are part of a collection S) execute in their actions Rules components of the following form: If conditions A and conditions B, then do actions. Now, conditions A and actions are always the same; only conditions B changes according to the particular Rule in S.

It is frustrating to add the same conditions and actions to the Rules components every time. Therefore, my idea is to enclose every conditions B in a Rules conditions component, and then use those components as a variable in  1 "abstract" Rules component that captures the above pattern. Is that possible?

This answer provides a way to capture the following common pattern for Rules: "If conditions A and conditions B, then do actions" for fixed conditions A and actions. Instead of creating a separate condition set component for every conditions B (and then use those components inside some kind of "abstract" Rules component as a variable), the following approach is way easier:

Create a condition set component for conditions A, say My component for conditions A.
Create an action set component for actions, say My component for actions.
For every conditions B, create a new Rule.
For every new Rule, add My component for conditions A to the conditions, and My component for actions to the actions. Then, complement the conditions with conditions B.

Result: we fixed the never-changing conditions A and actions in 2 Rules components. That saves us a lot of redundant repetitive work. If we want to implement 10 cases of the general pattern, then we end up with 10 Rules + 2 Rules components = 12 Rules in total.

Let's compare this approach with the initial idea. We would have to create 10 Rules components for the conditions B + 1 "abstract" Rules component + 10 Rules that contain this "abstract" Rules component in their actions = 21 Rules in total.

The advantage of the proposed alternative approach is less Rules in total. The disadvantage is that every Rule needs to include the same action set and condition set components. But to be honest, adding those 2 components to the Rules takes much less clicks and time than creating new Rules... I think this problem nicely illustrates the power of action sets and condition sets in the Rules module (a feature that might seem somewhat obscure for beginners).


How to change the label of title field How to change the label of title field bydefault its showing Title I need to change it to "Custom-title" of node edit form programatically.

I tried

 function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id =="slices_slices_cta_5_edit_form")
{
    kint($form[title][widget][0]['#title']);
    dpm($form[title][widget][0]['#title']->jsonSerialize());
   $form[title][widget][0]['#title']->jsonSerialize()==t("Custom-title");
     //dpm($form[title][widget][0]['#title']->getArguments());

}

I just want to change [string] property of class TranslatableMarkup's object of above screen shot.

How to access the value of a Drupal\Core\StringTranslation\TranslatableMarkup object within a form

I want to do something like below example:

$form[title][widget][0]['#title']->string = t('New-title');

Not working above solution.

You can change the title label by editing the node type settings by going to Admin > Content Types > (type) > Edit. No code needed, and this can be exported to configuration.

I’m not even sure what your code is trying to do, but you don’t need it.


Styling the autocomplete dropdown to work with the up/down arrow keys The following custom styling for drupal core's autocomplete dropdown works when hovering, but it is ignored when using the up/down arrow keys. (Currently, pressing the arrow keys only turns the text white.)

Does anybody know the secret to getting styles and keypresses working together?

#autocomplete li:hover, #autocomplete li:focus{
background-color:#428bca;
color:green;
}

This should work:

#autocomplete li.selected {
  background-color:#428bca;
  color:green;
}

The items from the autocomplete list are having the .selected class added on hover/key navigation.


Is aegir a good choice for me? I want to use aegir for a website that users can create their own sub-sites.

From aegir installation guide:

  when a new site is installed, the web server will be automatically configured (vhost) and restarted

Does this mean that every time a new subsite will be created, server restarts and will be out of access for a few seconds?

Aegir is a powerful tool to manage hosting environments, deploy new versions of your site, clone a live site to a testing environment... Stuff like that. I don't know which kind of users you're talking about, but I would only give access to experienced Drupal developers. If you want 'normal' end users of a site to be able to setup their own subsite, maybe http://drupal.org/project/subdomain is right for you.


Form Redirect not working if 'destination' is in URL In one of my forms, I'm trying to set a $form_state['redirect'] so the form will go to that destination after the user clicks one of the action buttons.

If I inspect $form_state['redirect'] both before and after I add the redirect, it is NULL before, and after contains the proper array. Here's how I'm setting up the redirect:

$form_state['redirect'] = array(
  'my/custom/path/' . $nid,
  array('query' => drupal_get_destination()),
);

I want to preserve the destination from the form that the user's viewing to the next path (that's why I'm calling drupal_get_destination(), which returns an array with 'destination' => 'some/path/here' inside.

It seems that, because there's already a destination in the path of the current form, the form redirects to that destination no matter what I put in my own form submit handler (see above code). I even tried using drupal_goto() and that didn't redirect the user either.

When a form is processed, the value of $form_state['redirect'] is sent to drupal_goto(), and drupal_goto() always favors $_GET['destination'] over its own $path parameter.

For the sake of completeness, in Drupal 6, you were somewhat out of luck without setting your own headers in hook_exit():

function mymodule_exit($destination = NULL) {
  $my_destination = 'foo/bar';
  header('Location: ' . url($my_destination));
  exit;
}

In Drupal 7, hook_drupal_goto_alter() was added for this specific use case:

function mymodule_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  $path = 'foo/bar';
}

Another option for Drupal 7, which is closer to what you want to do, is to reset the static cache for drupal_get_destination()  in your submit handler using drupal_static_reset():

function mymodule_form_submit($form, &$form_state) {
  // See note
  $form_state['redirect'][] = drupal_get_destination();
  $form_state['redirect'][] = 'foo/bar';

  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();
}

Since you call drupal_get_destination() immediately after the reset, Drupal is blissfully unaware of the destination parameter for the rest of the page build, including when it calls drupal_goto().

Note: I changed the code for defining $form_state['redirect'] because you never want to overwrite the variable: other submit handlers might've defined their own redirects. Drupal will always use the last item in the array, so if you want foo/bar to override the destination parameter (and every other redirect defined up to that point), it needs to be last.


Howto print out the pagination for EntityFieldQueries? I have this code that uses an EntityFieldQuery object:

$query = new EntityFieldQuery;
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'yacht')
  ->propertyCondition("status", 1)
  ->pager(3, 1);

// […] switch case defaulting to:
$query->fieldOrderBy("field_bautyp", 'value', "asc");
// […]

$query->execute();
$nodes = node_load_multiple(array_keys($result['node']));
return theme('yacht_display', array('nodes' => $nodes));

And in the yacht_display.tpl.php

<some HTML-Code and iteration over the $nodes>
<?php var_dump(theme_pager()); # => NULL ?>

It apparently works; when I add ?page=2,5 to the URL I get different results.
Now I need to render the pager. Simply calling theme_pager() does not work; calling theme('pager', array("element" => 1)) always returns NULL.

What am I doing wrong?

UPDATE: updated the code to its current state

The ->initializePager() part is wrong; why would you do that?
Kill that line, and call execute() as usual.
Just calling theme('pager') should be enough; I am not sure why it fails. (Maybe because of the call to initializePager().)


how to display sales volume for a product or a product variation in drupal commerce? I need to display number of sales for a product or a product variation in product list. But I cannot find a decent way to go.
Can I count order numbers for a product or a product variation with their relation? How should I do?
I looked this thread Drupal Commerce: Number of a sales per product, what he want is a view, but I need to display number of sales in product list.
I appreciate for any help or comments.

Look at https://drupal.org/project/commerce_reports and edit your product list View to do what it does in its product sales report.


Where do I specify the URL of the incoming XML? In D8 I installed the feeds module.

I added a feed type named Coindesk

Before I can do the mapping I should add a url to this feedtype. I cannot find where I should do this. I looked in all the settings...

Where should I add the url van de XMl feed?

You make the linkage to the XML input in feeds instance definition.

The D8 Feeds module follows the entity module with definitions and instances.

There are the feed type definition which defines the processors and mappings.  These are created in the configurations feeds admin screen.

And there are the feeds instances.  These are where you define the input and it's basic settings for a feed type.  They are created under content / feeds.

This is an improvement over the prior versions as it lets you use the same feeds mappings over different inputs.


Can I manually migrate comments? I have a Drupal 7 site and I'm thinking about upgrading it to Drupal 8. I want to refactor the site, so I just need to export the content.

So far, I've tested exporting content types using feeds module and a csv file, as I don't quite understand how to do the export using .yaml files. It did work: I exported the stuff I wanted using views in my current site, and then imported it back using Feeds.

I would like to know if there's a way of manually importing into Drupal 8 all the comments (where I already have imported the content).

I will appreciate any suggestion! Thank you!

Give a try to Migrate module that is for Drupal 7 and comes as part of Drupal 8. It can import comments. You might also be interested in reviewing all migrate tools listed on https://www.drupal.org/docs/8/upgrade/drupal-8-migrate-modules


Find out what time was last comment posted on a node I want to put a new icon next to node listed in a block if it was created/updated or commented on in last 1 day. I'm able to fetch all the nodes which were created/updated or commented on sorted in descending order of their time of creation/update or comment.

This is my code in template.php:

 function analytic_preprocess_views_view_fields(&$vars) {
     $viewName = $vars['view']->name;
     $view1 = "view1";
     $view2 = "view2";
     $view3 = "view3";

    if (strcasecmp($viewName, $view1) == 0 ||
        strcasecmp($viewName, $view2) == 0 ||
        strcasecmp($viewName, $view3) == 0)
      {
           if (isset($vars['view']->name)) {
              $created = $vars['row']->node_created;
              $changed = $vars['row']->node_changed;

              $cexpire = $created + (1 * 24 * 60 * 60); //one day later
              $uexpire = $changed + (1 * 24 * 60 * 60); //one day later

              if (($cexpire > time()) || ($uexpire > time())) {
                    $vars['newicon'] = '<img src="'. path_to_theme().'/images/new_icon.gif">';
              }
       }
    }
}

Problem is that when I commented on an older article which I created few months back, it was accurately displayed at the top of my block but 'NEW' icon didn't appear next to it and I saw this error on the page:

Notice: Undefined variable: newicon in include() (line 28 of /home/user/public_html/sites/all/themes/analytic/views-view-fields--viewname.tpl.php).

where I'm displaying/rendering this image.

My understanding is that for the node which just has a new comment I don't have the time of update. How do I get that? Like I have node_created and node_changed.

node_created and node_changed refers only to node itself.

In views you should be able to add relationship " Comment: Last Comment".
Then, you'll have filter and field like "Comment: comment time". You can add this field as non-display one and then use it in templates for fields after it. Will be simpler and more reliable than preprocess functions.


Is there an installation package builder for Drupal? Does anybody know of any websites that provide a service that allows you to select which modules you want, and download a pre-assembled installation package with the selected modules already in the /modules/ folder?

You could make your own easily with the Drush Make module; the Profiler Builder module will tell you what to include in your make file.

This requires you have some knowledge of using drush.


How do I display last five nodes, with the latest at the bottom using views? I am creating a view which lists node titles for a specific node type. I want to display the 5 latest nodes with the latest at the bottom of the list.

If I sort using the post date criteria in an ascending manner, then the earliest 5 posts are shown. If I use descending, then the latest 5 are shown, but the the latest is at the top.

I'm fairly certain that Views does not support this. It's a somewhat frequent request for listing comments as well, but you can't add sorting after filtering/paging.

The easiest way is to change the view template to output the rows in reverse order.


Pass argument to view for pager limit It is possible to pass and argument to a view for the limit on its pager? I see that there is this question for Drupal 7, but not Drupal 8.

Try this out :

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_build().
 */
function customModule_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'your_view_id') {
   //- Set the new limit here // 3
   $view->setItemsPerPage(3);
  }
}


Error 500 only on permissions page I know that there are a lot of topic concerning the famous error 500 but i didn't find my answer in one of them.

Actually i have an error 500 when i load admin/people/permissions or when i'am trying to save new permissions. It's not all the time but i will say that it happens 80% of the time.
This permission page is very slow to load and when i haven't this error, it takes my navigator between 30s to 1m to display it.

I used google developper tools for this page and the result of the audit was:

36 requests  ❘  138.40KB transferred  ❘  27.57s (onload: 27.27s, DOMContentLoaded: 25.58s)

I edit my post and follow the trick that gave me H.NiK and i have impressive result for now

38 requests  ❘  17.09KB transferred  ❘  2.34s (onload: 1.76s, DOMContentLoaded: 1.42s

I have a lot of fields on the permission page more than 150 i think (because of the module fields permissions).

I watch the log of my server and i just have the same information:

Premature end of script headers: index.php, referer: http://blabla.com/admin/people/permissions

I have 25 lines of this today on this page.

Have you any idea why i have this error only appears on this page?And maybe how i can track this error and resolve my problem? Is it possible that a module or a js file trigger this error?

ps: i'm on a shared hosting, so i can't touch any configuration on my server (php.ini,my.ini)

Thanks,

Because you are on shared hosting the PHP process may not be given enough memory.  If you have a complex site or page the drupal bootstap may run out of memory and fail. I have had this problem trying to run a heavy site (one of the more Drupal complex distributions) on a shared host.  I would take a quick peak at how much memory is given to a PHP process (and Drupal) by visiting admin/reports/status and look for the "PHP Memory Limit".  I typically use 128M on a complex site.

You said also you can't edit you php.ini file - are you certain?  Many shared hosts allow you to to override the global php.ini file with one in your account.  Most will have a wiki explaining how configure such overrides.  If not you may need to move to a different host.


Proper with "Executing Custom PHP Code" Action I am trying to add an action that "Executes Custom PHP Code". I click Add a new action to the rule I have created and I choose "Execute Custom PHP Code" from the drop down the loading spinner appears for a couple of seconds and then disappear. The only thing I can do is click Continue which does nothing.
Then when i navigate to another page I receive the follow error

Value field is required.
The integrity check failed with the following error message: "Missing configuration for parameter code."

Has anybody got any idea why this is coming up.
It sounds like a box is supposed to appear but it doesn't.
As far as I can see I have all the right modules installed. (PHP filter, Rules, Rules Scheduler, Rules UI, Trigger).
Oh I am using Drupal 7.7 (I am planning on upgrading to 7.8 later today)
Thanks
Conor

Okay I solved it, It turned out to be very simple. Facepalm

I had misconfigured nodejs which was causing a javascript error. Which meant the textbox which should've appeared didn't.

I reconfigured nodejs and it worked fine :)


Displaying user related content Im trying to figure out what contextual filters to use but im getting no where, im trying to display content related to that user through an attachment on a page listing all users. So for example if I had user 1 it would display content from user 1 and if the user is user 2 and the attachment would display the content under user 2 and so on.

In the image below, I have the filters and relationships I am using on my attachment. on the page itself I have no contextual filters or relationships on it. I think that is fine since I am displaying just the users themselves, however I could be wrong.

as you can see I have no contextual filters added on to the attachment because I am not sure which one is the correct one, I have tried different combinations with User: Uid and Content: Author Uid but have had no luck.

Any help is appreciated.

You're over-complicating this with the extra relationships.

Drop everything under relationships and make sure your drop your relationship references on your fields as well.

Then just add a contextual filter for Content:Author uid and you should be all set as long as that uid is correctly getting passed to the attachment. You will want to end up with something that looks more like the attached screenshot.


Change module's description from another module How can I change a description of a module from my custom module or how can I override hook_process?

You can alter a module's information through hook_system_info_alter(). For example to change the description of the Views module:

function MYMODULE_system_info_alter(&$info, $file, $type) {
  $info['views']['description'] = 'Something else';
}


Really really need help debugging this dpm(). It's an error from trying to create a new Message | Fixed by reinstalling Reply module The Message module was working fine but I noticed one of the messages wasn't getting created by Rules. I suspect it's due to locale being enabled recently and creating with the UI gives this error.

For message types where I haven't created a different language, it seems to work fine.

2 errors in log:

Warning: array_flip(): Can only flip STRING and INTEGER values! in EntityAPIController->load() (line 219 of /usr/share/nginx/html/sites/all/modules/entity/includes/entity.controller.inc).

.

EntityMalformedException: Missing bundle property on entity of type message. in entity_extract_ids() (line 7930 of /usr/share/nginx/html/includes/common.inc).

The relevant lines in common.inc are:

// Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
        dpm($info);// My dpm
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }

You can see where I added dpm(). $entity is empty but $info gives the below screenshot.

Any pointers for someone who just isn't used to debugging things like this? I've deleted every message in on the site with VBO but the error persists.

After two and half years of dev, this site was supposed to go into a proper beta next week in a friend's business but the entire UI relies on the Message module. :/

And here is a dpm of the ids for the flipping error.

Any help appreciated. I didn't expect it to all fall apart this weekend.

Edit: Closed as it is indeed a duplicate. I don't have the skills to deal with it so will just rewrite to use node functionality instead.

Edit 2: Calmed my head today and looked at things that weren't my own code. Turns out it was the Reply module which I use on Message. Reinstalling it gets rid of the errors. I don't know why it happened. It's been a part of Message for like a year during development.

Exception EntityMalformedException is triggered, because (as you mentioned) your $entity is empty, and based on $info['entity keys']['bundle'] Entity module expects to have $entity->type property, but it doesn't exist.

You should check the backtrace and find which module is responsible for this invalid call, e.g. by adding this line instead of dpm:

var_dump(debug_backtrace()); exit; // Show the backtrace and exit.

in order to identify and fix the broken code. The most relevant part from the backtrace is function which is called, so starting from the top [0]=>, then [1]=>, so once you find the custom code or contrib module responsible for this exception. If there is no custom module apart of messages module, you should report this bug to the maintainer of this module.

Here is the related bug: Fatal errors when content types are deleted before messages are.

For further explanation, check: How to debug EntityMalformedException?


Where to place php code snippets in Drupal? Whereabouts are you meant to place a snippet of php code? I am guessing the root of site? Don't you need to have something point to it?

I am wanting to place this snippet I found to encode email http://shamsphp.blogspot.com.au/2012/11/how-to-encode-email-address.html

You should place this helper function in your custom module, so once the module get enabled the you can call this function anywhere across drupal environment.


Query does not change I've got a problem with hook_views_query_alter().
I want to override the view's query with a rather complex one. In the first step, I placed the hook in my views.inc and tested it. The hook is called. But none of my tests to alter the query worked.

function glass_lagermanagement_views_query_alter(&$view, &$query) {
  if ($view->name == 'lagerbestand') {
    $query = db_select('materials');
    $query->condition('materials.ID', 1, '==');
  }
}

To test the function, I want to show only one entry which has got the ID "1", but nothing happens at all in the view. What am I doing wrong?

I'm using Drupal 7 here. It is an old project I need to update.

I got it.
I used this code to alter the query and it worked.

$query->where[1]['conditions'][0] = array('field'=>"materials.ID","value"=>'1',"operator"=>"LIKE");


How can I programmatically get the admin theme Similar question to How can I programmatically get the theme name? and How do I programmatically change the admin theme?.

I want to simply obtain  the current admin theme machine name and human name, even when I might not be on a page where the admin theme is enabled as the active theme.

This information doesn't appear to be directly accessible via the ThemeManager class.

This is config and you can get it with the following snippet.

$admin_theme = \Drupal::config('system.theme')->get('admin');
$admin_theme_name = \Drupal::service('theme_handler')->getName($admin_theme);

Or with Drush:

drush cget system.theme admin


Update new user's profile with rules, based on his webform submitted data On my site I am using two webforms from which a user can register to the site. This feature is enabled thanks to the webform_registration module. Of course these webforms can only be submitted by anonymous users.

What I want is, on the event of a submission, to populate the profile of the user who submitted the form with some of the data that were submitted. So I created a rule catching the event of a webform submission. Now how will I update the profile? Setting a data value on a user field does not work since the user who submitted the form was anonymous! He was created after. How can I do this? All I know about the user is just his username that can be pulled from the submission data. Any way to retrieve the user entity using his username and then writing the data to his profile?

You need to create and force-save both the User and the User's Profile before you set your data values.  Your rules actions should look like the following:

Create Entity - User
Save Entity - User, Force Save
Create Entity - Profile, choose profile type.
Save Entity - Profile, Force Save
Set Data Value(s)


mvf field is not working with view dependant filter mvf field is not working with view dependant filter.

I created a mvf field .

I want its view filter with view dependent filter module .

Its filter is working fine when the field is not in dependant list .
But when i inclued it with Dependent filter its not hiding.

finally i have to change the field type .


Vote up/down module undefined constant errors I recently have been trying to create a site for people to submit encryption algorithms to be tested. I wanted to make a voting process similar to Stackoverflow.

The best looking module I found was called the vote up/down module.

I installed it on a fresh install of Drupal 7, along with the answers module and answers userpoints, however when I enable it on a question, I get the following error:

Notice: Use of undefined constant NODE_BUILD_PREVIEW - assumed 'NODE_BUILD_PREVIEW' in vud_node_node_view() (line 147 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Use of undefined constant NODE_BUILD_SEARCH_INDEX - assumed 'NODE_BUILD_SEARCH_INDEX' in vud_node_node_view() (line 148 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Use of undefined constant NODE_BUILD_SEARCH_RESULT - assumed 'NODE_BUILD_SEARCH_RESULT' in vud_node_node_view() (line 149 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Use of undefined constant NODE_BUILD_RSS - assumed 'NODE_BUILD_RSS' in vud_node_node_view() (line 150 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Undefined property: stdClass::$build_mode in vud_node_node_view() (line 152 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Undefined variable: a3 in vud_node_node_view() (line 161 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).

and, when I go into the voting details tab, I get a WSOD.

Here is a screenshot of the actual error:

Is this just because I set something up wrong? Is there a library that is missing? Is there a patch that is required to be installed?

The module page for Vote Up/Down says (emphasis mine):

  7.x (unstable, on development, do not use this version for production)

NODE_BUILD_PREVIEW was a constant in Drupal 6. I imagine that the maintainers of Vote Up/Down have branched off of the old D6 version to create the D7 version...and haven't completed the changes yet.

There's not even a dev/unstable release available for download on the module page so you definitely shouldn't be using this module for the time being.


Share nodes to Slack i want to share link of post in social media i find module addtoAny and module social media for sharing poste butI didn't find to share post to slack.

Any help?

There are two modules, I didn't try them myself and I'm not sure what is your use case:
Drupal to Slack and Slack. Are these provide the functionality you want?

Update
Ok, there are other modules for adding share buttons like Simple Addthis or the dev version of the original Addthis Module


Simplenews newsletter producing undecoded base64 email I have a client site that's running Simplenews with Mime Mail and SMTP Authentication Support. Everything works fine except when my client wants to include a link to a YouTube video (and just to be clear, this just a link to the video, not an attempt to embed a video in the newsletter). Here is an excerpt of the resulting newsletter email:

  PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvVFIvUkVDLWh0bWw0MC9sb29zZS5kdGQiPgo8aHRtbD4KPGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7nIGNoYXJzZXQ9dXRmLTgiPjwvaGVhZD4KPGJvZHkgaWQ9Im1pbWVtYWlsLWJvZHkiIHN0eWxlPSJi

. . . and so on. No other links cause this to occur. When I look at the email source, the plain text version is fine. This only happens to the HTML version. I am thoroughly stumped. Has anyone seen anything like this?

It turns out this was a bug in the SMTP Authentication Module. It uses uses 8bit encoding in the Content-Transfer-Encoding header for the base64 encoded body. I applied this patch with success:

https://www.drupal.org/node/1741082#comment-9121815


How to set an openlayers preset to full screen? I am working on one of those sites that need a fullscreen dynamic map to show up as a background. This means the preset should be set to 100% height, but I can't get this to work. Is there a module for that? A jQuery snippet?

On the OpenLayers project page, it says:

"Behaviors
Map interactions like popups, zoom controls, editing, and fullscreen can be added via the UI and extended by other modules."

I don't have a site up and running with OL or I'd check it.


How to set menu items on mobile as stacked full-width items? I am using Superfish, and my menu is perfect for normal displays.  However, for small smartphone displays, I want my menu items stacked and spanned the width of the display.  Also, when an item is clicked with child items, the top level items go away and display the child items.

I can't figure out how to do this from the SF documentation or searching on the web.

I've only used Responsive menus on one project and it seemed to work fine, outputting the mobile menus when viewed by a device, and the normal menu when viewed by computer with some margin of error but in general it seemed to work well. You can see a demo here: http://drastikbydesign.com/demo/responsive-menus-demo-1-mean-menu and how it shows on a mobile and/or computer.


How to add content filter into a content page(not in a view)? So I'm totally new with the drupal and try to wrap things around my head, which is quite overhelming at first, so my question might be a simple one for pro's.

I'm building Property Listings site where users could submit their own listings, add comments and search and view Property Listings sorted by location, type, price and etc.

So when you search the site on the Search Bar it gives you a page with all the relevant content. For example: If i search for 2bed flats at around 50k they open a page with url defined in taxonomy term"around50k". And now, i have no idea what to do to add a filter for "Location" on that page.

I could make the whole new page with a view for that exact type of listings and add whatever filters i want, however as there a hundreds of categories it would be a nightmare.

I know i could add more filters to a search bar, however i will have all Property Type menu on the site and i need *location and price* filters for each page on that menu.

Is there any functions that would create filters for content on pages or any other solution to this problem?

You probably want to add the Panels module.  There's an excellent series of screencasts on Panels/Page Manager at NodeOne.

Basically, you can use Panels and Page Manager to override paths on your site.  For example, you can override all taxonomy terms.  You can break this down however you like, such as "all taxonomy terms," "all taxonomy terms from a specific category," "one specific taxonomy term," "users with this role on a taxonomy term in this vocabulary," etc.  Then you can create Variants, which are page layouts that dictate how the content should be formatted.

Using Panels, you can take the views you make and stick them wherever you like on the site.  It will certainly take some time to learn how to set this up, but learning how views and panels work together will allow you to create very complicated sites with little duplication and certainly no "hundreds of pages" created manually.


Customized search block I have a requirement in which there are two fields for search. One is text field and other is select box. The text field is for keywords and the select field are taxonomy terms. I need to fetch the values in both fields from text file and it should be autocomplete and display the results accordingly.

Please Help.
Thanks in Advance

Riya

You can try Custom Search module. This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box.

The module adds options to select:

which content type(s) to search, which specific module search to use
(node, help, user or any module that implements search),
advanced criteria For all these choices, there are options to switch between a
select box, checkboxes or radio buttons,
You can also customize the selector label and the default - Any - text.


Cannot setup Drupal anymore Ever since I switched to a brand new retina MacBook Pro, I'm not able to setup a new Drupal installation anymore...

I use MAMP and I configure my vhosts.conf so I can work on virtual hosts (like dev.newproject.com). But whenever I try to install a new Drupal installation, it looks like the setup is confused...

Normally, you have

 1. Choose profile
 2. Choose language
 3. Verify requirements
 4. Set up database
 5. Install profile
 6. Configure site
 7. Finished

But for some reason, after step 5, het installation goes back to step 1 or 3 or whatever step... When I look in my database, it looks like Drupal has been installed and also a settings.php file was created, but I'm in an infinite set-up loop...

Has anyone ever experienced such weird behaviour? And how can I fix this?

It could be write permissions of the files - try chmod -R a+rw . command in Terminal in the root of your drupal folder. It could be a time out meaning that the database is not been written correctly (don't have a remedy for that, except for not using a native setup, but rather a Virtual Machine, VM-based setup...)

You might want to consider a VM-based setup (which would more closely resemble your production environment), see a guide I wrote to using Vagrant to automate generation of a setup here: https://stackoverflow.com/a/15067918/227926


Does Multiversion module need content migration if enabled on running site? I have Drupal 8 setup with lot of content in it. When I enable Multiversion module all the content gets disappeared. Do I have to migrate the content after installing Multiversion? Why does it deletes the content?

As mentioned in the Multiversion description on Drupal.org that it should be enabled on the fresh instance of the drupal. If you are planning to use multiversion on already established database then on enabling this module it will erase all the entities including the custom ones. It will delete
all Taxonomy Terms, Menu Items, Content, Config Entities. So that will require content migration on after install. But there is another way,
1. Install a fresh database
2. Enable the Multiversion
3. Sync the configuration.
Configration management comes really handy in this case.


How do I retrieve a menu using its link? Let say I have a menu item with these attributes

'title' => 'Menu Title',
'link' => ['uri' => 'internal:/taxonomy/term/1217'],
'menu_name' => 'my-menu',
'expanded' => TRUE,

I can find all the menus by their title, e.g.,

 $menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
                ->loadByProperties(['title' => 'Menu Title']);

if ($menu_link = reset($menu_links)) {
// Get the pid of the first menu
    $menu_pid = $menu_link->getPluginId();
}

Then I tried to retrieve menu by the link property, and I couldn't.
I tried:

 $menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
                ->loadByProperties(['link' => array('uri' => 'internal:/taxonomy/term/1217')]);

 $menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
                ->loadByProperties(['link' => ['uri' => 'internal:/taxonomy/term/1217']]);

 $menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
                ->loadByProperties(['uri' => 'internal:/taxonomy/term/1217']);

None of them worked.

Try the property link.uri:

$menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['link.uri' => 'internal:' . $path]);


Get context of overlay (get parent page information) Is it possible to get the context, like the full URL, or the containing page path, title, etc., while inside an overlay page?

For example, I have a form pop up inside an overlay, and I want to, inside that form, be able to get the context of the page that triggered the overlay popup. I can't pass any information via the URL... I'd just like to be able to do something like arg(0) for the containing page (what's faded out in the background of the overlay.

Right now, if I do arg(0), request_uri(), $_GET['q'], etc., it always returns the overlay path, like http://www.example.com/path/i/want#overlay=overlay/path

(I want the 'path/i/want' portion of the URL, somehow).

Unfortunately the PHP that's rendering the child page knows nothing about the parent page over which it's going to be placed. You could write an AJAX callback that checks window.location and reports back to the server, but that would have to run after the page was fully rendered.


How to change composer file directory after it has been set? So, I've been struggling with some problems with composer and drupal 7. I have composer and composer manager installed because of dependencies for the OpenLayers Module. I don't think I use these dependencies since the site works fine without them installed, but I've run into an issue where I need to fix a composer error in my production environment which is on a shared host and I can't install composer.
Most recently, I've just been trying to correctly install the dependencies and then move the files to my live server and hope everything works out. The issue is that when I moved the database to the development machine, the composer file directory is still set with the path from the live server. Anytime I try to navigate to Configuration => System => Composer Manager, or to Status Report, I get the following error:

RuntimeException: Error creating directory: /home/phislub9/public_html/sites/default/files/composer in composer_manager_file_dir() (line 299 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).

The issue is that this path is now effectively hard-coded, unless I alter it in the database. So, how can I fix this, and what the correct process for installing these dependencies.

RuntimeException: Error creating directory: /home/phislub9/public_html/sites/default/files/composer in composer_manager_file_dir() (line 299 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).

Is this location, sites/default/files/composer not accessible?. I think you probably need to update some permission or maybe create the file manually. This means that you can't upload files.

I think the variable is composer_manager_vendor_dir

If so, running this,

drush variable-set composer_manager_vendor_dir 'path_here'

Would update it.

If that's not the variable, running

drush variable-get

Should list all the variables and it's just searching which is the right one.

  I've run into an issue where I need to fix a composer error in my production environment

You should consider not moving your database from Development to Production for this exact reason.

Check the Features module and other ways to move configuration into production, without having to import the database.

Always move your database from Production to Development, and move code from Development to Production.

This way, if you had to change something or apply a fix, it would be on your development environment, not on production.


Automatically generate product variations I'm creating a webshop with Drupal Commerce.

I have a product variation called T-shirt. It has three product attributes, color, size and print.

My problem

Let's say I need a T-shirt with 5 different colors, 5 different sizes and 5 different prints. Then I need to enter 125 product variations manually in the Admin UI.

What I need

I need to be able to automatically generate those product variations, since it takes extremely long time to create them manually.

It should be possible to enter the default price for all the variations.

Am I the only one who has had the need to do this? I feel like this should be possible, but I can't find any help on how to do it.

I found this thread, but it says that the functionality has been made in the Commerce Bulk module. I tried to install that module, but I can't find the option to bulk generate the product variations.

Have any of you tried this before, or know how to do it?

Well, I did have a look around I could not get Commerce Bulk module to install.
Then I saw https://www.drupal.org/project/commerce/issues/2755529, which will be a sweet feature when it has been merged. I could not get the patch to apply so I ended up creating a sandbox module based on this and here we go:
https://www.drupal.org/sandbox/taggartj/3104497

Judging by your rank you will know how to get the code.

https://git.drupalcode.org/sandbox/taggartj-3104497/commit/7997ee4

This module will give you a route (no link yet):

You need to create at least one Product variation manually, then go to:

"/product/PRODUCTID/variations/VARIATIONID/bulk-generate"

or example /product/331/variations/1/bulk-generate, for it to allow you to bulk generate your variations.


Can fields validation errors be displayed below the fields? Can field validation errors be displayed below the fields instead of as a list at the top of the form?

I think you are looking for something like the Inline Form Errors Module. Here is a quote about it (from the module's project page):

... allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
IFE provides three behaviors for the configured forms

Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place
Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements
Remove all messages, this option will remove all error messages and place them inline with the form element

In all cases only the messages related to the form will be touched. All other messages will remain in tact.


How to sort drush status messages in test scripts? I'm using drush to run test scripts agains my drupal 7 installation. Simply calling:

$ drush scr path/to/myScript.php

My script is using drupal_set_message() to output status of my test scripts.

My problem is the output is sorted by importance, like that:

Test 1339 failed.                [error]
Test 1338 failed.                [error]
Something strange happened!      [warning]
Test 1337 successful.            [status]
Script starting.                 [notice]
Script finished after 1234ms.    [notice]

Is there any way to sort the output of the messages by the time they get called in my script, it would look much more logical like that:

Script starting.                 [notice]
Test 1337 successful.            [status]
Test 1338 failed.                [error]
Something strange happened!      [warning]
Test 1339 failed.                [error]
Script finished after 1234ms.    [notice]

Is that possible somehow? Is drupal_set_message() the wrong approach? Any suggestions?

You can log your debugging messages in database using watchdog
 and you will find the logged message in order at "admin/reports/dtblog"

Updated:
Check the document page, as for [status] , watchdog has $severity parameter to set the status for your message.Following values can be set as status for the logged message.

WATCHDOG_EMERGENCY: Emergency, system is unusable.
WATCHDOG_ALERT: Alert, action must be taken immediately.
WATCHDOG_CRITICAL: Critical conditions.
WATCHDOG_ERROR: Error conditions.
WATCHDOG_WARNING: Warning conditions.
WATCHDOG_NOTICE: (default) Normal but significant conditions.
WATCHDOG_INFO: Informational messages.
WATCHDOG_DEBUG: Debug-level messages.

As a simple example, check this

 watchdog('your_script_name', '!message', array('!message' => "something_happened"), WATCHDOG_ERROR);

the above will log message when called keeping severity as "error".


Limit OG available on registration form I want to let my user to request membership to an OG through the user registration form (they should select the company you belong too). I found how to

I have two content type set as OG (company and committee). When I enable group audience selection in the registration form all my OG are displayed. I want to display only value related to the company OG.

Is this achievable?

This can be done with https://drupal.org/project/entityreference_prepopulate.

You should create registrationlinks like this for it to work auto: /user/register?og_user_node=X where X is the groupid.


How to sort randomly two or more nodequeues in Views but keeping nodes position? I've got 3 nodequeues:

Nodequeue A

Item 1
Item 2
Item 3

Nodequeue B

Item 4
Item 5
Item 6

Nodequeue C

Item 7
Item 8
Item 9

Does anyone know how to sort these nodequeues in Views (randomly) but keeping the nodequeue position of every node within its nodequeue?

For example:

Nodequeue A, Nodequeue C, Nodequeue B
Nodequeue B, Nodequeue C, Nodequeue A

But items inside every nodequeue stay, based on its original position.

I finally got the solution. It's just about grouping nodequeues.

At fields, select "Nodequeue ID" field. Then you can group by this field at Format options.

To mix nodequeues without altering the nodes sorting within the queue just sort by:

Nodequeue: Position (to keep queue order)
Global random (only nodequeues blocks will be mixed)

I hope this helps.


Drupal views grouping: amount by grouping I have created a view, I have two separate tables based on this view.  I used "grouping" to get these two tables.  For the pager its asks how many items I want to display.  I want 10 total, the 5 most recent from each grouping.  What it ends up doing is giving me the 10 most recent between the two groupings.  So its uneven.  I wanted 5 and 5, but Im getting 7 and 3 based on published date.  Can I get 5 for each grouping?

thanks, M

The Views Grouping Row Limit module allows you to specify how many rows you want to display in each group, maybe it can help you.


When creating a view based on order products in ubercart, only people with access to all orders can see it I've created a view based on order products in ubercart, but only those with admin role, who have permissions to see all orders can see the view.

Now this is problematic, as the view is a most popular products grid, which is meant for anonymous users who visit the webshop.

My question is: can I somehow restrict access to anonymous and authenticated users to see all the orders but at the same time allow them to see that one view, based on order products?

Hope my question was clear, and thanks in advance,

Huba

In the view's advanced settings, go to 'SQL Settings', and check 'Disable SQL rewriting'.

Drupal modules can hook in to SQL queries and alter them before they are executed. The Ubercart module automatically adds a permission check to queries that touch the Order table, to implement the 'view own orders' permission. Individual views can opt out of this rewriting mechanism, but that will prevent any module from altering the query. Be sure to thoroughly test that the view does not leak any sensitive information.


Drupal content slider like ImageFlow and GalleryFormatter I am looking for Drupal modules that allows to create content sliders (img,audio,video) like ImageFlow and GalleryFormatter.

But those modules supports only images.

Are there any modules for creating content sliders like above?

Views slideshow will do the job for you:

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View. Powered by jQuery, it is
  heavily customizable: you may choose slideshow settings for each View
  you create.


What are some drupal 7 mega menus that allows view blocks to be inserted? I was wondering what mega menu's for drupal 7 that allow view blocks to be inserted? Currently I only know about xo mega menu, but i was wondering what other ones do people use or other workarounds you might have for putting in view blocks into drop down menus.

You can use Menu Attach Block module to render block as menu.

  Menu Attach Block allows you to attach blocks to standard core Drupal
  menu items. This is especially useful for creating complex dropdown
  menus and mega menus.

  Any block can be used, including blocks generated by other modules.
  Blocks generated by Views are particularly good candidates for
  embedding.


The page isn’t redirecting properly I have been trying to intercept a page request from /node/nid which is of type the_content_type and then appending some facet query parameters to it which is something like this

?f[0]=city%3A160&f[1]=country%3A48.

The purpose is to preselect the facet options from that page.

Here is the subscriber class I have written so far

<?php

namespace Drupal\custom_module\EventSubscriber;

use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Routing\TrustedRedirectResponse;

class RedirectWithFilterSubscriber implements EventSubscriberInterface {
  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // This announces which events you want to subscribe to.
    // We only need the request event for this example.  Pass
    // this an array of method names
    return([
      KernelEvents::REQUEST => [
        ['redirectWithFilter'],
      ]
    ]);
  }

  /**
   * Redirect requests for my_content_type node detail pages to node/123.
   *
   * @param GetResponseEvent $event
   * @return void
   */
  public function redirectWithFilter(GetResponseEvent $event) {
    $request = $event->getRequest();

    // This is necessary because this also gets called on
    // node sub-tabs such as "edit", "revisions", etc.  This
    // prevents those pages from redirected.
    if ($request->attributes->get('_route') !== 'entity.node.canonical') {
      return;
    }

    // Only redirect a certain content type.
    if ($request->attributes->get('node')->getType() !== 'the_content_type') {
      return;
    }

    $node = $request->attributes->get('node');
    $node_id = $node->id();
    $node_url = $node->url();
    $country = $node->field_country->getValue();
    $city = $node->field_city->getValue();
    $country_target_id = $country[0]['target_id'];
    $city_target_id = $city[0]['target_id'];

    if (empty($country) && empty($city)) {
      return;
    }

    // This is where you set the destination.
    $option = [
      "query" => [
        "f" => [
          "city:$city_target_id",
          "country:$country_target_id"
        ]
      ],
    ];

    $redirect_url = Url::fromUri("entity:node/$node_id", $option);
    $response = new RedirectResponse($redirect_url->toString(), 301);
    $event->setResponse($response);
  }
}

The resulting url looks fine though

http://project.dev/some-custom-page?f%5B0%5D=city%3A160&f%5B1%5D=country%3A48

But the problem is, the page always shows

The page isn’t redirecting properly

on my browser. I've been figuring this out for almost 3 days now and I can't seem to find a way through it. I've been wanting someone to have a fresh look into it. Maybe I am doing something wrong. Is there somebody can lend me a help please? Or maybe, a different way other than this? Thank you in advance.

Could be a redirect loop. You have to check whether the query string is already present and then stop redirecting again:

  public function redirectWithFilter(GetResponseEvent $event) {
    $request = $event->getRequest();
    if ($request->query->has('city')) {
      return;
    }
    ...
  }


HTML markup is still stripped out, even if I am using the mimemail-message.tpl.php template I'm having an issue where confirmation emails from Ubercart seem to have  HTML markup removed. In my setup somehow the HTML markup in the Ubercart email template is being stripped when it reaches the mimemail template. A view of the source for emails sent shows that the HTML markup Mimemail puts into the message is there. It's just everything coming from Ubercart that is stripped out.
The line 35 of the mimemail-message.tpl.php template file is the following one
<?php print $body ?>

This is where the problem lies. All the HTML markup above and below this makes it into the email. However, the HTML markup that should be in the $body variable is stripped out.
Is there something I could be missing in my settings?

I added the htmlmail module and this fixed the problem.


Redirect for single page with htaccess file not working when url has spaces Im trying to add a redirect to my site from one page to annother using the .htaccess file. From the documentation at http://drupal.org/node/38960 I tried the following but it doesnt appear to do anything. Thanks

# RewriteBase /

#custom redirects (this is where the code ive added begins)

RewriteRule http://mysite.com/one http://mysite.com/two [R=301,L]

#end custom redirects (this is where the code ive added ends)

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

In the end the issue was spaces in the url. Working with this:

# RewriteBase /

RewriteRule ^taxonomy\/term\/6\ 7\ 8\ 9$ /taxonomy/term/all [L,R=301]


How to add new values to a custom field I can't seem to find the answer to this anywhere.

Programmatically, I need to add new values to a custom field of a new node instance I just created via API.  I am taking input via a form and want to add that data to the custom field in the new node.  I know the columns of the custom field.

How can I do that, or where is a good reference?

(the custom field type is address, if that matters)

If you are using a custom form which is invoked by a menu callback, you could try this.

Assuming that you have a postal address field type (provided by the addressfield module) which as 5 sub-fields - country, address 1, address 2, city and postal code in your content type.

/**
 * This will be invokded by a menu callback
*/
function yourmodule_custom_form($form, &$form_state){

    /* your form elements definition here */

    $form['#validate'][] = 'yourmodule_custom_form_validate';
    $form['#submit'][] = 'yourmodule_custom_form_submit';

    return $form;
}
/**
 * Validation attached to the form
*/
function yourmodule_custom_form_validate($form, &$form_state){
    // do validation here
}
/**
 * Submit handler attached to the form
*/
function yourmodule_custom_form_submit($form, &$form_state){
    global $user;
    $values = $form_state['values'];

    # Create a node object, and add node properties.
    $node = new stdClass();
    $node->type = 'your_content_type';
    $node->uid = $user->uid;
    $node->created = strtotime("now");
    $node->changed = strtotime("now");
    $node->status = 1;
    $node->comment = 0;
    $node->promote = 0;
    $node->moderate = 0;
    $node->sticky = 0;
    $node->language = LANGUAGE_NONE;

    $field_address = $values['field_address'][LANGUAGE_NONE][0];

    $node->field_address_country = $field_address['country'];
    $node->field_address_thoroughfare = $field_address['thoroughfare'];
    $node->field_address_premise = $field_address['premise'];
    $node->field_address_locality = $field_address['locality'];
    $node->field_address_postal_code = $field_address['postal_code'];

    node_object_prepare($node);
    # Save the node.
    # The node will also get published, if $node->status was set to 1.
    node_save($node);
    $nid = $node->nid;
    # if you want to redirect to a page after submission, use this
    $form_state['redirect'] = 'path/to/redirect';
    drupal_redirect_form($form_state);
}

I did not test the code. It is just for example. You may need to amend it by yourself.
You can inspect your address field name by printing out $form.

dpm($form); // if you have devel module enabled
echo '<pre>'; print_r($form); echo '</pre>'; // if you don't have devel moduel

Also note that when you create a new field, Drupal creates two new tables starting with field_data_field and field_revision_field. If you name the field "address", you will see two new tables field_data_field_address and field_revision_field_address, you could look up into those tables.


How do I edit the format of things published to the front page? How do I change the way info is published to the front page?

For example, it gives me a title, 1 paragraph of body, date, tags and a read more button.  I need to set it so that it also gives me a particular image field from a custom content type on top of the body content.

Where do I make this correction?  I don't see it anywhere in views and I don't want to redesign my front-page around a different block / new view.

It also possible with Views, if you set the Style (listed in the Basic Settings section) to Fields. You can then choose whatever Fields you like to be displayed.

Like you already mention yourself, it is possible with Display Suite. If you choose to work with Display Suite, you can select a Display Suite build mode in the Style option of a View.


Migrating dates in the same timezone: convert arguments to subfields? I have a migration that is successful except for the timezone.

$this->addFieldMapping('dest_date', 'source_date');

For some reason the above code causes a timezone conversion to happen between the source date and the destination timezone. The migration seems to assume the source is in UTC and needs converted to Chicago time, giving me a result that's six hours later than it should be. The source date is in fact from the same timezone, so I want to avoid converting it.

$this->addFieldMapping('dest_date', 'source_date')
  ->arguments(DateMigrateFieldHandler::arguments('America/Chicago', 'America/Chicago'));

The above code works perfectly, but when I run my migration I get this error:

  The field mapping arguments() method is now deprecated - please use subfield notation instead.

However when I try to use subfield notation, I end up with the same problem again that I did when I had no arguments/subfields at all:

$this->addFieldMapping('dest_date', 'source_date');
$this->addFieldMapping('dest_date:timezone', 'source_date:timezone');

The above code doesn't seem to help at all, (edit: This is not surprising, as my field doesn't seem to have "timezone" as a subfield.) and the migration still seems to assume the source is in UTC and needs converted to Chicago time.

How do I convert my arguments to subfield notation without breaking them?

You can use it like:

$this->addFieldMapping('dest_date:timezone')
->defaultValue('America/Chicago');


How to automatically install civicrm extensions in drupal+civicrm installation profile? We are building a Drupal distribution / installation profile similar to CiviCRM Starter Kit. This will install Drupal 7 and CiviCRM 4.3 while installing the distribution.

We want to add some CiviCRM Extensions like "Extended Reports for CiviCRM" etc. in our distribution so that whenever user will install the distribution, these CiviCRM Extensions also gets installed by default.

We have added these CiviCRM Extensions in drupal-org.make file like below,

libraries[nz.co.fuzion.extendedreport][download][type] = get
libraries[nz.co.fuzion.extendedreport][download][url] = "https://github.com/eileenmcnaughton/nz.co.fuzion.extendedreport/archive/master.zip"
libraries[nz.co.fuzion.extendedreport][destination] = "extensions"

and these get downloaded/unzipped when we run drupal packaging script (drush make). But we are not sure how to enable them as part of the distribution installation.

We know we can add the Drupal modules in profile.info file like below,

dependencies[] = civicrm

but don't know how and where to add CiviCRM Extensions so that they get installed as part of distribution / installation profile setup.

Please suggest how can we install CiviCRM Extensions automatically as part of installation profile setup.

The current API call requires more than just the key. To enable modules as part of an install profile, you simply need to include this code somewhere in the process when it's possible to initialize CiviCRM...

  if (!civicrm_initialize()) {
    drupal_set_message(t('Failed to initialize CiviCRM'));
    return;
  }

  require_once 'CRM/Extension/Manager.php';

  $params = array(
    'version' => 3,
    'sequential' => 1,
    'key' => 'org.civicrm.volunteer',
  );

  $result = civicrm_api('Extension', 'install', $params);

As long as the Extensions Directory and ResourceURL are set in the civicrm.settings.php, you should be set.  I've been setting the Extensions Directory for Pantheon users, but still need to dynamically configure the ResourceURL https://drupal.org/node/1980088.

Rather than create a "Drupal distribution / installation profile similar to CiviCRM Starter Kit", PLEASE consider building on the CiviCRM Starter Kit by using it as the base distribution and contribute to maintaining it.  Take a look at this patch and how the latest version of OpenAtrium builds on Panopoly.

https://drupal.org/comment/6117722#comment-6117722

http://drupalcode.org/project/openatrium.git/blob/refs/heads/7.x-2.x:/drupal-org-core.make

We really need more developers working to push the patches that are still requires back into CiviCRM to keep this stable.  I hardly have time to figure out the changes with each CiviCRM release.  It has taken several years to get to the point we can install and run CiviCRM from the /profiles directory, package CiviCRM w/ drush make, and rebuild the required libraries.

The CiviCRM Starter Kit was always designed to remain a base install to build other use case specific distributions on, but I've really been maintaining this on my own so far and would love some help.

UPDATE:  I went ahead and created https://drupal.org/project/civicrm_extension_enabler since troubleshooting code in this queue is difficult.  That module enables the CiviVolunteer extensions and works a site running https://dashboard.getpantheon.com/products/civicrm_starterkit/spinup once CiviVolunteer is uploaded to sites/all/extensions

I've started an issue to change the specific extensions hard coded in the .install to be an array of extensions populated by the distribution https://drupal.org/node/2159317


How do I better play nice with weights, when overriding a form? I'm attempting to use the Constant Contact module.
One of the features of this module is that it inserts a check-box into the user registration form. The problem is that it seems to set weights in a way that it interferers with my own  implementation of hook_form_alter(), on the registration form. The field order is a mess now: the field for the confirmation of the email address is now the first one.

The Constant Contact module is specifying a weight for the checkbox:

'#weight' => 11,

My implementation of hook_form_alter(), just left my new form element weights blank. I could just massage my functions form weights such that it didn't have the fields out of order, but then I risk to do it again the next time I need to add something to the form or use another module that does likewise.

Is there a 'best practice' way to handle form weights assuming multiple override sources?

The only thing I usually do and can recommend is to leave "gaps" between your weigts. So instead of 1, 2, 3, 4, 5 or so, I use for example 5, 10, 15, 20, 25.

The idea is that it makes it easier for other modules to move a field to a different place, or move new fields in-between.


Drupal 8 status code set 301 instead of 302 for urls with out lang code I have an article with url alias '/gettting-started' and it is translated in several languages.

Lang codes for other languages is set like the following.

For German:de-de, English: en-us.

In 'admin/config/regional/language/detection' Detection and selection languages, priority is set to 'URL' then 'Browser'.

My browser locale set to German first,so when i try to visit the article with the /getting-started, it is redirected to /de-de/getting-started with the status 301.

The status code 301 is creating the problem for me as the response is cached at varnish cache (for 301 response codes).

The other user, with English as priority in Browser language visits /getting-started redirects to /de-de/getting-started

So, instead of sending 301, how can i send 302 redirect for urls without language code as a prefix.

That redirect isn't a drupal standard feature, it is done by the redirect.module.

It is currently using the default response header of the redirect configuration in \Drupal\redirect\EventSubscriber\RouteNormalizerRequestSubscriber::onKernelRequestRedirect(). That is a bit weird as that is the default for new manually created redirects which usually should be cached.

I think there is an issue in the redirect module to change that to a different configuration or always using 302, if not, feel free to create one.


How to add text as page variable to node add form? Or in other works print explanation/guideline text I want to include my content type's explanation/submission guideline text on node add form/page.

I need to insert it into header element and therefore a variable would be suitable.

I would assume it should already be available on page--node--add--special-content-type.tpl.php but I think it isn't.

Also, this text is automatically appended on the end of the page which is silly and why I wan't to change it.

And to mention following doesn't print it:

  <?php print render($page['help']); ?>

The core page.tpl.php template doesn't know anything about any current node object or help information from its node type. The snippet you're using is for printing a region named help, not a node type's help test.

That help information is retrieved by the System help block and is placed in whatever theme region you've configured in the block admin UI (/admin/structure/block). You're better off utilizing that block with your theme regions rather inserting a variable into your page template.

However, if you're really wanting to push this information into your template you can evoke node_help() to retrieve the information for your template variable and push in your template.php's template_preprocess_page() function:

/**
 * Override or insert variables into the page template.
 */
function MYTHEME_process_page(&$vars) {
  // $help_text will be available as printable markup with page.tpl.php
  $vars['help_text'] = node_help(current_path(), arg());
}


Running tests on fresh 8.2.x install throws "Permission Denied" for Kernel tests Under a fresh install of 8.2.x, when I run tests, only Kernel tests seem to fail with this message from the testing UI:

(path/to/test/Kernel/test.php) ... Permission denied

Pretty much any Kernel test I select exits immediately with that error. Other tests, like Unit tests, work fine. Is this a file permission issue or something I missed in config?

Looks like some tests can only be ran with the command line and will not work with the test runner UI.