Schedule a mail on the 1st day of the following month I currently have a rule set up using scheduler which - when a user logs in, a rule component is scheduled to send a mail '+1 week' from this time.  This works fine.

However, I need to alter this so when the user logs in - the component mail is scheduled for the 1st of the following month.

Essentially, for example: if a user logs in today 16-06-14 - the component is scheduled to be executed on the 01-07-14.

Any ideas? Not sure how to set the offset. Would this be better via cron instead?

Try "first day of +1 month" as your scheduled date.


How to use an omega template with hook_theme I'm using page callback function to display a page. How would I change this to use an omega template? I've tried adding a vis.tpl.php to the omega templates function but to no avail. I don't understand how to declare a omega template for use with a particular page.

<?php

function vis_menu() {

  $items['images'] = array(
    'title' => 'Images',
    'page callback' => 'image_page',
    'access callback' => TRUE,
  );
  return $items;
}

function image_page() {
  return 'hello';
}

Any help would be much appreciated.

I solved this using this question as a basis to work from https://stackoverflow.com/questions/4100485/register-your-theme-functions-in-drupal.

The template (.tpl.php file) goes in the omega template directory. You then use a hook_theme function to define the theme with the template key in the array pointing to the name of your template file.

The theme is then called with theme(your-theme-name)

Here's my working example for my module called vis:

function vis_menu() {

  $items['images'] = array(
    'title' => 'Images',
    'page callback' => 'image_page',
    'access callback' => TRUE,
  );
  return $items;
}

function image_page() {
  return theme('images');
}

function vis_theme() {
  return array(
    'images' => array(
      'variables' => array(),
      'template' => 'vis',
    ),
  );
}


Adding a custom Token so i can use in Webforms I am having the smart-ip module installed. It allows me to get User country, city etc very easily like this:

echo $_SESSION['smart_ip']['location']['country_code'];

I want to use this as a token replacement in webforms field. But I have no idea how to do it.
Got confused after googling. I should do the hooking in template.php? How do i do it? :/

Create your own tokens!

You could create a small module that implements the token hooks (D6, but D7 should be similar), like so:

function YOURMODULE_token_list($type = 'all') {
  $list = array();

  $list['smart-ip']['smart-ip-country-code'] = t("The Country code");
  // ...etc

  return $list;
}

function YOURMODULE_token_values($type, $object = NULL, $options = array()) {
  $tokens = array();

  $tokens['smart-ip-country-code'] = $_SESSION['smart_ip']['location']['country_code'];
  // ...etc

  return $tokens;
}

Or, even better, add these hooks to the smart_ip.module file and submit a patch to the module maintainer :-). Tokens are really great, and it would certainly be a good addition to the smart_ip module.


Create a custom Link to a File-Field in Twig I'm trying to customize a download-link for a file-field in my entity.
In a similar setup, i was able to customize a link-field in the following way:

 Link

So, for the file-field, i tried something similar:

 Download

However, there is no such thing as a uri field available. I have a hard time figuring out which fields actually are available for me to use in the template. I found kint to be way too noisy, i had to restrict memory consumption and still have no clue which fields are usable.

Alternatively, i tried to create a custom template for the specific file field, called field--field-publication-file.html.twig. The debug info tells me that it is used for rendering.
I had a look at the field that my theme (bootstrap) normally uses and tried to mimick its behavior. Specifically, i wanted to use the field link, which is also used in the bootstrap version. However, this field is always empty when using my version.

What more could i try?

After more research, i found the answer by accident on this page. One can refer to the link by using:

<a href="{{ file_url (node.field_publication_file.entity.uri.value) }}">
  Download
</a>

The fields that were defined in the bootstrap theme don't seem to be accessible in a sub-theme of bootstrap. I'm sure I could have written a custom preprocessor to do the same thing, but this solution works for me and I don't have to write PHP code.


How to bulk update existing path alias after changing the URL alias pattern? How to bulk update existing URL alias?

I have Path auto module add path alias to URLs. I have changed the URL alias pattern. Now I want to update the pattern of old URLs also.

How can I achieve this?

it works only to URL which does not have path alias – Vamsi

Then first go to /admin/config/search/path/delete_bulk and delete the aliases
in question.

Then update /admin/config/search/path/update_bulk


How to add Specific Class to Each Drupal Menu Anchor I am developing a website using drupal and i need to know about how to add link to drupal menu anchor.

For example:

i have a drupal menu: user menu. Within user menu, i have several list of links, let's say: A, B, C, D.

Then, i want to add class/id for each of the anchor, such as: A

Thank you.

You can do that by using Menu Attributes module.

  This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.


How to make an existing content type a product in Ubercart 3 and Drupal 7? This is a follow up to this question. If I go to admin/store/products/classes, then I can only create new content types:

The problem is, I have another content type, called "product", which I need to set as an UberCart product. And I create this class in ubercart that has now resulted in a new content typed called "Basic Product". When all I really want is for the existing product to be considered as an actual product.

When I edit the "product" content type, I can see it doesn't have the same options as the "basic product" content type:

So the question is: how do I make my EXISTING "product" content type an Uber Cart product? I checked under classes and that only seems to work if you want to create a NEW content type.

Have you simply tried to put the machine name of your existing content type in Class ID, and its human name in NAME ?

I've had such problem 3 years ago, and I solved it so. More, for tests purpose I've just created a foo content type. Then I added the Class ID foo, and it has been mapped with foo content type.


How are drush and jenkins used together for continuous integration? I hear the buzz words, "continuous integration", "drush" and "jenkins" often. Thus, sparking my interest.

How are drush and jenkins used together for continuous integration?

Also, why would you want to use drush and jenkins together?

For my projects, I use a build script made of Drush commands in a Jenkins job. I use my Phing Drush Task project to run Drush from a Phing build script. This allow me to leverage the existing Phing tasks (eg. files copy, phplint, etc.). With the help of Drush, this build script

Downloads all non-custom code (ie. Drupal core and contribs module and themes) with Drush Make to ./dist
Expands placeholders in a versioned settings.php (ie. replace ${db_host} with the actual DB hostname) while copying it to the freshly downloaded ./dist/sites/default folder.
Copy custom modules and themes to ./dist/sites/all/modules/custom and ./dist/sites/all/themes/custom
Run phplint for all files from my custom modules and themes.
Copy everything under ./dist to a pre-configured webroot.
Run drush site-install testing and drush pm-enable simpletest to install a fresh site using the build code base and able to run SimpleTest.
Run drush test-run to run my custom module test suites.
Run drush coder-review.

Here is a commented build.xml template for Drush usage in Jenkins.


How exactly do I create a variation of a .tpl file? I am new to Drupal and am working on a partially complete site. There's a .tpl file I wish to duplicate and alter and have only be used with a certain Panel Page type ('Product Page').

I've read Drupal's documentation about template suggestions, but am not sure what to actually do.

I've placed the following in my template.php file:

function mytheme_preprocess_node(&$variables) {
  if ($variables['???']) {
    $variables['theme_hook_suggestions'] = 'new_tpl_file';
  }
}

But I've got no idea what to put in $variables[''] so that the suggestion appears on my pages. I know my Panels page is called 'Product Pages' but that's it. Is there a machine name for that I can use as a variable? Would it work if it was something like:

      if ($variables['product_pages']) {

Does anyone know of a tutorial or guide out there? Im pretty lost here. Any help is appreciated!

If you are trying to override panel page template then I am afraid you are using the wrong hook, hook_preprocess_node works for node pages only.

However panel page goes through hook_preprocess_page, so you can add custom template suggestion in following way.

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

Then create custom-panel.tpl.php

Reference:
page.tpl.php override for Panels Pages?


AJAX dropbutton link I have a dropbutton in an admin view. It's currently got links built using URL::fromRoute

I want one of these links/buttons to work asynchronously.

This is what I currently have:

$dropdownButtons = [
    '#type' => 'dropbutton',
    '#links' => [
      'a' => [
        'title' => $send_verification_link_text,
        'url' => $send_verification_email_url,
      ],
      'b' => [
        'title' => $this->t('Remove person'),
        'url' => $remove_person_url,
      ],
    ],
  ];

I assume these are links to Ajax enabled route yes ?? i hope so lol any way heres is how ... see this example from a list builder:

$parent['operations']['data']['#links']['clone'] = [
  'title' => $this->t('AJAX!!!'),
  'weight' => 2,
  'url' => Url::fromRoute('someroute_name', ['id' => $entity->id]),
  'attributes'=> [
    'class' => 'use-ajax'
  ]
];

all you need to do is add
'attributes'=> ['class' => 'use-ajax']
more info see my old comment ... https://api.drupal.org/comment/62725#comment-62725


Anonymous user access I want all the users to access the custom defined url. But now I got error message as Access Denied, my code is as follows, I tried clearing both drupal and browser cache. Please help me,

function hbrowse_menu() {
  $items = array();
  $items['browse/restaurants'] = array(
    'title' => t('Browse Restaurants'),
    'page callback' => 'list_restaurants',
    'access arguments' => array('access content'),
    'access callback' => TRUE
  );
  $items['browse/cuisines'] = array(
    'title' => t('Browse Cuisines'),
    'page callback' => 'list_cuisines',
    'access arguments' => array('access content'),
    'access callback' => TRUE
  );
  return $items;
}

hbrowse is my module name.

Just remove access arguments, when the callback is set to TRUE you dont need any parameters:

$items['browse/restaurants'] = array(
  'title' => t('Browse Restaurants'),
  'page callback' => 'list_restaurants',
  'access callback' => TRUE,
);


Why isn't a PDO driver detected on the install page? I have an old Drupal 7 project and I need to set it up on my localhost.
I have Ubuntu 16.04, Apache 2, php 7.0, and MySQL 5.7 installed.
Everything is working fine for other PHP scripts, But when I tried to install Drupal 7 project, I got this error.

Your web server does not appear to support any common PDO database extensions. Check with your hosting provider to see if they support PDO (PHP Data Objects) and offer any databases that Drupal supports.

I could not figure it out why Drupal doesn't detect PDO. How can I fix this issue?

The error could be thrown for three different reasons.

Some of the Drupal core files in the includes/database directory are missing
There isn't any extension implementing the necessary PDO drivers
The extension implementing the necessary PDO driver isn't enabled in the php.ini file or other .ini files used from PHP

To check which database driver is available, Drupal first looks for its own files in the includes/database directory, initializes an instance of a class that extends DatabaseTasks (for example DatabaseTasks_mysql for MySQL) and calls its installable() method.
public function installable() {
  return $this->hasPdoDriver() && empty($this->error);
}

protected function hasPdoDriver() {
  return in_array($this->pdoDriver, PDO::getAvailableDrivers());
}

If the method returns FALSE, the PDO driver is considered not available. (See drupal_get_database_types() for details.)
Notice that, if the PDO extension (not a PDO driver) isn't available, the error shown from Drupal is the following one.

'Your web server does not appear to support PDO (PHP Data Objects). Ask your hosting provider if they support the native PDO extension.

In that case, Drupal would also show the following message, followed by a list of one or more missing PHP extensions.

Drupal requires you to enable the PHP extensions in the following list (see the system requirements page for more information)


3 reset button with auto submit for each and reset all I created a view page with exposed filters in a block. I have three exposed filters in a view, with apply and reset button for each one.

It shows results based on the filters. It is working fine. But I need these filters each having its own reset button and reset all button resetting all three.

Can it be done through views? Should I handle through code? If so where I need to write the code?

This following post has a nice hook_alter function that adds a reset button to exposed filters on views. It lists both code for 6 and 7.

http://fleetthought.com/blog-post/adding-reset-button-exposed-views-filters


Hiding Email Address Form Alter I'm trying to hide non-admin users to view the email address field in the user section. I have the following hook. Right now, I have the current password hidden, but the email sends back a naughty validation requiring email to be added.

You can use similar code as below to hide pass and mail field with optional value.

//drupal_set_message('not admin!');
$form['account']['current_pass']['#required'] = FALSE;
$form['account']['current_pass']['#access'] = FALSE;
$form['account']['mail']['#required'] = FALSE;
$form['account']['mail']['#access'] = FALSE;

$form['#validate'] = array_diff($form['#validate'], array('user_validate_current_pass'));
$form['#validate'] = array_diff($form['#validate'], array('user_validate_mail'));


form auto complete how to restrict results by previous drop down Hi I have a select field on a form which contains countries. The next field is a text box  which is driven by an autocomplete function. The autocomplete function returns cities from a database table.

I want to restrict the cities that the autocomplete will return based on the country value selected in the dropdown. How do I do this?

if it helps here is my form

 $country_list = _get_country_list();
    $form['country'] = array(
            '#type'=>'select',
            '#title'=>'Select Country',
            '#description'=>'Select the country where you want to collect the car',
            '#options'=>$country_list,
    );
$form['officename'] = array(
    '#type'=>'textfield',
    '#title'=> t('Location'),
    '#default_value'=>$form_state['officename'],
    '#size'=>20,
    '#maxlength' => 50,
    '#description' => t('Select the country where you want to pick up the car'),
    '#attributes' => null,
    '#required' => TRUE,
            '#autocomplete_path'=>'location-autocomplete'
);

$form['submit'] = array(
'#type'=>'submit',
'#value'=>'Search Now',
'#submit'=>array('HolidayAutosXML_carsearch_form_submit'),
);

and here is my autocomplete function. I want to restrict the sql with a where country = {country selected in Drop Down List}

function location_autocomplete($string){
$matches = array();
$result = db_query("select officename from {holidayautos_country_list} where officename like :keyword limit 0, 10", array(':keyword'=>"%" . db_like($string) . "%"));
 foreach($result as $row) {
    $matches[$row->officename] = check_plain($row->officename);
  }
drupal_json_output($matches);
}

Many Thanks
Simon

Using the links suggested from Anil Sagar, I put together this solution using Ajax.

function HolidayAutosXML_carsearch_form($node, &$form_state) {
  $country_list = _get_country_list();
  $form['country'] = array(
    '#type' => 'select',
    '#title' => 'Select Country',
    '#description' => 'Select the country where you want to collect the car',
    '#options' => $country_list,
    '#ajax' => array(
      'callback' => 'update_officename_autocomplete',
      'wrapper' => 'haofficename',
    ),
  );

  $form['officename'] = array(
'#type' => 'textfield',
'#title' => t('Location'),
'#default_value' => $form_state['office name'],
'#size' => 20,
'#maxlength' => 50,
'#description' => t('Select the location where you want to pick up the car'),
'#attributes' => NULL,
'#required' => TRUE,
    '#autocomplete_path' => 'location-autocomplete',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  if (!empty($form_state['values']['country'])) {
    $form['officename']['#autocomplete_path'] = "location-autocomplete/{$form_state['values']['country']}";
  }

  $form['submit'] = array(
    '#type'=>'submit',
    '#value'=>'Search Now',
    '#submit'=>array('HolidayAutosXML_carsearch_form_submit'),
  );

  return $form;
}

I added an Ajax element to the country drop down, telling it to look for a
 with an ID equal to "haofficename" and calling a function named update_officename_autocomplete().
I used a prefix and suffix element in the office name element to wrap it in a
 element with the ID haofficename, which Ajax is going to look for.
update_officename_autocomplete() simply returns the altered office name element of the form. if you look inside the if statement you will see that it is adding to the #autocomplete_path property. So I had to add a second parameter to my autocomplete function. This function now takes $country and $officename.

function location_autocomplete($country,$string){
   $matches = array();
   $result = db_query("select officename from {holidayautos_country_list}        where officename like :keyword and country = :country limit 0, 10",  array(':keyword'=>"%" . db_like($string) . "%",':country'=>$country));
  foreach($result as $row) {
  $matches[$row->officename] = check_plain($row->officename);
  }
  drupal_json_output($matches);
  }

It works like a charm.


Add message to Add Article page In the Add Article page (while editing), how do I add a custom message right above or below the Save/Preview buttons?

You can use markup module to add html text as fields to the article content type.

If you want to show the html text only in edit page then you need to use hook form alter

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' && arg(2) == "edit") {
    $form['contact_information'] = array(
      '#markup' => 'Your message goes here !',
    );
  }
}


Prevent "AJAX HTTP request terminated" error on early form submit I'm doing an ajax validation for duplicate check on link field in node form. When the link field is edited, an ajax call is triggered as programmed (using form api #ajax default blur event), it  takes a while for the ajax response to reach browser, in the meantime the form gets almost ready to submit by user. Doing an early form submit (i.e before the receipt of ajax response) Drupal ajax API throws below error message in JavaScript alert box,

An AJAX HTTP request terminated unexpectedly
Debug information follows.
Path: /system/ajax
Status text:
Answer Text:
Ready State: 4

I have noticed this issue in a few contrib modules as well. I think the fix is to prevent submitting the form to server until the ajax request completes. Wondering to know if there is any way to set client side callback function in form api that I can use to stop form submit.

This might help you.

Drupal.behaviors.merchant = {
  attach: function(context, settings) {
    jQuery('form.node-form')
      .ajaxStart( function() {
          jQuery(this).submit(function() {
            return false;
          });
        })
       .ajaxStop( function() {
          jQuery(this).unbind('submit');
          jQuery(this).submit(function() {
            return true;
          });
        });
  }
}


View showing ONLY taxonomy children terms and NO parents I've managed to got my view working but my worry is that this method is not dynamic.

What I want to achieve?
To have a list of articles tagged with terms that are one level deep (children) but not their parent terms.

E.g.: assuming a taxonomy looks like this:

A
  A1
  A2
B
  B1
  B2

I want to be able to go to the URL mysite.com/A/A1 or mysite.com/B/B2 and retrieve a list of articles with ONLY content tagged with A1 or B2 (in this example)

For that I added a filter and manually selected the parent terms I don't want to list:

Is there a better solution to achieve this?

Thanks!

Super simple but impossible to guess solution :

With a normal filter set the "Parent term" filter not equal to "0".

This will filter parents


Replace username with unique hash when users delete their own accounts When users delete their own accounts (with the core function), I don't want the username to be replaced by anonymous, but with a hash string, for example anonymous-dhjf4ued.

I tried doing it with the Rules module, and I looked for modules that could do it, but I couldn't figure it out.

The reason this would be useful is because I have sites with a forum and threads are much more readable if you can still identify which users are the same (who responds to who) if there are two cancelled user accounts in a single thread.

You can use hook_user_cancel() like below:

  /**
   * Implements hook_user_cancel()
   */
    function example_user_cancel($edit, $account, $method) {
      // Define in which method you are canceling the account, else remove it and
      // proceed with below code by removing this if condition.
      if ($method == 'user_cancel_block') {
        $user_load = user_load($account->uid);
        $user_load->name = 'anonymous-'.time();// Here you can add your random number.
        user_save($user_load);
      }
    }


Use entity relationship to exclude records on view I have a content type, lets say PRODUCT
I have another type, PURCHASE, which points to PRODUCT with an entity reference

It is simple using views relationships to get PRODUCTS that have PURCHASE relationships, get totals, all kind of groovy things...

BUT

How do I get all PRODUCTS without any PURCHASEs? So create a view with a relationship "Entity Reference: Referencing entity" but exclude all those that are referenced by a PURCHASE?

Contextual filters have that nice negate checkbox, but that does not help me under relationships.

You should be able to add a contextual filter, negated, that uses the relationship that you want.


Easy steps for adding the imported content on one single page for display I have imported the data using the Feeds module from an Excel file.

But as I am new it has created multiple article nodes. I want all these articles to be shown under one article list page. Please explain step by step how can I move forward.

You can use Views module to do it. Follow these steps, to set a page listing all articles--

Download views & keep it in sites/all/modules folder.
Enable Views & Views UI from your module list.
Under Structure click View & Add a new View.
Select Content under show & Article of type.
Give a name to it & check Create a page.
Save & continue.
Give a path to the created view page.
Now you can access your path like $basth_url/(your given path).

Thats it.


How to clone a content type and all nodes related My site is using Ubercart, so now I want to use Commerce module instead, the problem now is Product content type, when I turn off all Ubercart modules, Product content type will be disabled.

I have more than 1000 nodes (Product content type), so now how to clone Product content type and moving all nodes to new content type?

Thank so much.

Drupal commerce stores product in a different way than ubercart. You best bet would be to export product in CSV format using something like Views data export and reimport it to Drupal commerce using Feeds and Commerce feeds


Profiler builder with custom modules First things first: happy 2015 to everybody. :-)

Now, I am quite new with Drupal distributions and profiles and here is my situation: I have a running site where I have contributed modules and custom modules. I've installed profiler builder module. When I use drush distro to create a distribution, it generates 2 make files: drupal-org.make and local.make.example. The last one "contains" the first one and it contains the custom modules as well.

When I run drush make local.make.example ./destfolder, it throws some errors. It says "non-existent project type on custom-module". So after a bit of research I've been able to make it work adding some information to the local.make.example, and adding the custom modules in a zip format.

My question is, why does drush distro generates a useless folder structure (i.e. modules, themes, libraries)? Am I able to put something there to make drush-make work on local.make.example without needing to add extra information? Am I missing something?

The extra lines of code I added in each custom module to the local.make.example was:

projects[custom_module_name][type] = "module"
projects[custom_module_name][download][type] = "file"
projects[custom_module_name][download][url] = localurl

Thanks very much for your time and let me know if you need further information.

EDIT

I'm going a bit crazy about this… I've just found out that drush make creates the custom modules' folders but they are empty. Nothing inside… So basically, I just don't know how to tell drush-make to build the initial drupal folder's architecture when custom modules are stored on the same computer I'm executing drupal-make…

I've seen most of the examples that evolves custom modules use git, but I'd just like to know how to make it work with custom modules stored on my machine, if possible.

In my experience, Profiler Builder has problem with modules, that are not full projects on drupal.org. I tried to use a module, that is hosted in GIT repository and the output was similar to yours. But it worked fine with drush generate-makefile, where generated output was like:

projects[svg][type] = "module"
projects[svg][download][type] = "git"
projects[svg][download][url] = "http://git.drupal.org/sandbox/josegaert/1511596.git"
projects[svg][download][branch] = "7.x-1.x-dev"
projects[svg][download][revision] = "04db94c4dc2bf5c8c9a2a0da5452c4a79d26d863"

I created an issue for Profiler Builder describing this at https://www.drupal.org/node/2479185. You may also want to look at https://www.drupal.org/project/make_local


How to display custom data array via Twig I've created service which gets the raw data from custom content type. It looks like this :

  Array
(
    [front_page_slider] => Array
        (
            [1] => Array
                (
                    [title] => Lorem ipsum dolor sit amet
                    [body] =>Some example slider text up here
                    [field_image] => http://localhost/drupal8/sites/default/files/2016-05/slider1.png
                    [field_link_uri] => http://example.com
                    [field_link_title] => see more
                )

        )

)

After that i use array_push function to add this array $variables global variable.

I've tried to display any of this fields like this:

{{ dump(front_page_slider[1].title) }}

or this:
  {{ dump(front_page_slider) }}

But both return NULL. What I do wrong ?

Have you added 'front_page_slider to the variables array in your twig template definition?

File...module_name.module

function hook_theme(array $existing, $type, $theme, $path) {
  return [
    'template_name' => [
          'variables' => [
           'front_page_slider' => [],
      ],
    ],
  ];
}


Attributes are not changing in the placed order I have a commerce site with T-shirts as products. I have added custom attributes of size and type.

By default L Size is selected. But even if the user changes the size to something else say M or S, in the order that is placed the size is still being shown as L.

I am assuming that this is because of caching. I currently have authcache enabled with Mem-cache in the backend.

I checked the XHR call that is being made. I see that the size that is being sent in the call is the one selected by the user. But however when the order is placed it still says L. Any help where to start debugging would be greatly appreciated.

This is a known issue with page level caching system for anonymous users in Drupal. Please subscribe to the open issue on the authcache issue tracker, then you will be notified as soon as this is fixed. There is also a report in the Drupal Commerce Queue


8 - Register form automatically fills in input fields I am using the core user-register-form to let users register to my site. When I first want to register a new account the form is displayed as followed:

Now, when I enter credentials and submit the form, the user is created. I can login and out with the created user.

However, if I want to register ANOTHER new account the form automatically fills in the e-mail and username of the user I just created.

I have tried several things that did not solve the problem:

Clear Drupal cache
Close browser and re-open
Kill browser and re-open
Open incognito browser
Clear browser cache
Disabled browser auto-fill

I also tried clearing the inputs using jQuery val(''); but then the form doesn't submit properly.

I assume this has something to do with drupal core? Please advice!

I found a solution thanks to the Drupal Community

Apparently this is defined in the core of Drupal: core/modules/user/src/RegisterForm.php

The following should be set to FALSE

// For non-admin users, populate the form fields using data from the browser.
    if (!$admin) {
      $form['#attributes']['data-user-info-from-browser'] = TRUE;
    }

However it would be better to not mess with the core values and write a form_hook_alter instead in your theme file:

function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
    $form['#attributes']['data-user-info-from-browser'] = FALSE;
  }
}

This solved the problem.


How to define an internal link as parent in mymodule.links.menu.yml? How do I create a menu link programmatically to a node that I can use as a parent for other links?
In MYMODULE.links.module, I defined some links for my navbar:
MYMODULE.parent-fruits:
  title: 'Fruits'
  url: internal:/fruits
  weight: 0
  menu_name: food
MYMODULE.fruits-apple:
  title: 'Apple'
  parent: MYMODULE.parent-fruits
  route_name: view.fruits.apple
  weight: 5
  menu_name: food
MYMODULE.parent-vegetables:
  route_name: view.vegetables.page-main
  weight: 10
  menu_name: food
MYMODULE.vegetables-asparagus:
  parent: MYMODULE.parent-vegetables
  title: 'Asparagus'
  url: internal:/admin/structure/taxonomy/manage/card_group_private/add
  weight: 5
  menu_name: food

In this case, I expect to have a menu that looks like this:

Fruits (child-> Apple)
Vegetables (child-> asparagus)

When I go to the parent page, the link to the child should appear in the navbar menu (the parent tree should be expanded).
But what I actually get is:

Fruits (no children)
Vegetables (child-> asparagus)

The problem is caused by defining the menu link with url instead of route_name.  I know this because when I change the parent of fruits-apple to parent: MYMODULE.parent-vegetables, then I see Apple as a child of Vegetables.
When I remove parent from Apple, then it appears in the menu (without a parent), so I know the link is defined correctly.
I can also create the Fruits / Apple links in the menu UI, and those work correctly.
Regarding parent: the documentation says this:

Determining the parent menu_link name can be a little tricky at first.
If you know the path of the parent menu item, you would need to search
for it in all available *.routing.yml files (most text editors and
IDEs should allow you to search all files in a project) and find the
route name for that path. Then, you would need to search for the route
name in all available *.links.menu.yml files. The menu_link whose
route_name matches is your link. Alternatively, if you know which
module is defining the parent menu link (or one of the parent menu
link's children), you can go straight to that module and perform your
search.

Since these are node links, I checked node.routing.yml in the core node module, but I couldn't find the route to node pages.
So: how do I create a menu link programmatically to a node that I can use as a parent for other links?

I think changing from url to route_name is the solution, you normally use url only for external links.
You don't find entity routes in static yml files because they are created dynamically. You could use the Devel module and visit
/devel/routes

or from the command line with Drupal Console:
drupal debug:router

See https://drupalconsole.com/docs/en/commands/debug-router
Then when you have found the route name you have to add the entity id as route parameter.
Example:
mymodule.links.menu.yml
mymodule.node7:
  title: 'Node 7'
  route_name: 'entity.node.canonical'
  route_parameters: { node: '7' }


How access term name by object? I want to load parent term name by tid .I am using this

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);
kint($term);

This return a object which is my parent term but I am not able to access term name by this object. Please check attached screenshot of kint($term).

You should get the name with the getName method.
In your case :

$term[1]->getName();
$term->getName();

If not, you can load the term and after get the name:

$term = Term::load($term[1]->id());
$term->getName();


Is there a module/hook for permissions for list values? Say I have a text list field attached to a node with the following values:

Apples
Oranges
Grapes
Kiwi
Strawberries
Pears
Bananas

But I want to give some options only to some roles, for example:

Only Administrators can select Strawberries.
Only Anonymous can select Kiwi.
Only Role C can select Pears.

Is there a module for this?  Or, if I was going to code it myself, is there a hook to start from?

This is for Drupal 8 but if there was a solution only for 7, that would be interesting to look at too.

This is Drupal 7 solution

Using hook_form_alter, you can unset some of the options based on the user role.
For example look at this list of article content type  (field_list)

It is the result of kpr() on its form

simply use this code

function THEME_form_alter(&$form, &$form_state, $form_id){
    global $user;
    if($form_id == "article_node_form"){
        //kpr($form);
        if(in_array('SOME_ROLE', $user->roles))
            unset($form['field_list']['und']['#options'][2]);
   }
}

This is the result


Conditionally apply CSS class to a conditionally-rewritten View field? [This will require some background explanation.] We have a View (D7) displaying a custom content type. Flag Lists provides the option to select items via checkboxes and add them to a personal list. However some items are excluded from being available to add to such lists, and that it established by a boolean checkbox ("allowed" if checked) in the creation of the node. If NOT checked, the Flag List Operations checkbox in the View is rewritten by something else – currently, replaced by a simple text "X".

Now we want to provide a tooltip message explaining why this item is not available to be selected – using Tipsy, Q-tips or something like that. To display such a message only for the ones where the checkbox has been rewritten with X or something else, I believe it needs to have a unique class that also applies to all other such instances. SO: Is there a way to make those instances have a unique class so they can trigger the tooltip message only when it's relevant?

Generally, every field has a unique selector already. If the defaults are not giving you enough control, I would recommend the Display Suite module which will allow to you add classes (and many other things) to individual fields.

You might also be able add the tip with the same method that you are using to rewrite with the X right now.


Configure web.config to redirect non-www requests to www for multi-site Drupal 7 Install I have a multi-site Drupal 7 install running on Azure that I would like to force all non-www traffic to the www address for all sites.

I have tried a number of examples from around the web but none of them seem to work.

Here is my current implementation, which looks like it should work, but does nothing.

<rule name="Redirect to www">
  <match url=".*" />
  <conditions logicalGrouping="MatchAny">
    <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
  </conditions>
  <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
</rule>

To clarify, yes, the above rule is nested inside <configuration> <system.webServer> <rewrite>

I've read about doing the redirect in settings.php but that seems kludgy to me and I'd rather do it right.

Any help would be greatly appreciated.

Some subtle differences between this and the rule above, but this officially works for my multi-site Drupal install on Azure IIS.

<rule name="WWW Rewrite" enabled="true">
          <match url="(.*)" />
            <conditions>
                <add input="{HTTP_HOST}" negate="true" pattern="^www\.(.*)$" />
            </conditions>
            <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>


Default language for role I'm building a website in French as default and only front language but I have to figure out how to do this:

I have administrator and manager roles, both are ok using the french language for both front UI and Admin panels but I also have a role "normal-users" for wich I want to set the default front UI and Admin panels to english by default at registration. How can I do this ?

Take a look in this topic below

How to set the language for the user while it is created?

Just read it quickly, this seems  to be what you need?


Adjust number of posts that appear on front page I currently only have one story that posts to the front page. How do I add more?

I know it's a really n00by question but I have google and visited many different links and they all say to go to the content administration page... but then where?

On Drupal 7: mysite.com/admin/config/system/site-information

Set the Number of posts on front page option to your liking.


How can I get the machine name of a taxonomy term knowing its tid? Is there any table in the database that shows the relationship between vocabulary and taxonomy, or is there any way to find out the vocabulary name of a particular taxonomy from its tid?

The table taxonomy_term_data lists the terms, and taxonomy_vocabulary lists the vocabularies.

In the table taxonomy_term_data, the term string is found in the name field. The field vid identifies the vocabulary assocaiated with the term. And the field tid is the numeric taxonomy id.

So you can look up the relationship between the term name, tid and vid directly from the this table.

Then, to determine the vocabulary name string associated with the term, you need to left join the taxonomy_vocabulary.name field, where taxonomy_vocabulary.vid = taxonomy_term_data.vid.


How to show a Select list (dropdown) for state and dependent cities of India? I want to show the list of state and city of particular state in dropdown.

I have done it using the Conditional Fields module but not helpful as I have to show the filter for cities in view.

Any suggestions?

If you have City and State list in CSV, you can import to taxonomy using Taxonomy CSV import/export module.

  This module allows you to import or export taxonomy from or to a CSV
  (comma-separated values) file or with a copy-and-paste text.

you can use Hierarchical Select Module to list it in content type

you can find Indian states and city list in xlsx format here


Rules > Send mail to product's creator? I tried to use a rule found in another topic (https://www.drupal.org/node/2050565), but it doesn't work. I want to send an automatic email to the product's creator, when the product is sold.

{ "rules_send_email_to_product_owner" : {
"LABEL" : "Send email to product owner",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "data_is" : {
      "data" : [ "commerce-order:commerce-line-items:0:type" ],
      "value" : "product"
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : [ "commerce-order:commerce-line-items:0:commerce-product:creator:mail" ],
      "subject" : "Test mail",
      "message" : "Test mail nr 1",
      "from" : "Sender",
      "language" : [ "commerce-order:state" ]
    }
  }
]

}
}

Any help would be greatly appreciated :)

You need to debug the rule!

This is not a direct answer but can help you find the problem. And it is too long to post as a comment. You should follow these steps regardless of other similar rules working (a teeny tiny difference can be causing the rule to fail).

Required tools

Install the devel module. but NOT on production site, only on your development site. It will add an extra action to rules debug a value under devel section.

Is the rule actually triggered?

Method 1:
Add a simple action, display a message and enter a simple text. Do the required actions actually needed to fire the rule (buy a sample product). Is the message displayed or not?
Drawback: If the message is not displayed, you wont actually know if the action is not triggered OR there is some error in rule definition, preventing the rule engine from executing it.

Method 2: Go to admin/config/workflow/rules/settings On your site, there is a checkbox to enable rules debugging. It's something like dpm() but for rules only with helpful information. Whenever a rule is triggered, all the thing happening (or failing) will show up in the debugging area. If something has failed it will be printed in red so you can easily find it.
Drawback: Can get annoying going through the rule stacktrace :|

If it's not firing:
There should be something wrong with the event/conditions you have set, Or a fatal error in the rule action definition. If the later find it with method 2 above.

Are the data you are using not null and valid?

Temporarily remove the condition commerce-order:commerce-line-items:0:type. Since you are working on development site this should not be a problem. In the actions (Important: In the beginning, as the first action) add the action debug a value. the value to debug would be "commerce-order:commerce-line-items:0:type. Go and buy the sample product, the rule should fire, and devel's debug a value would print the type. Check if it is set and is what you want it to be.
Do the same for commerce-order:commerce-line-items:0:commerce-product:creator:mail.
Do the same for "language" : [ "commerce-order:state" ] --> However this sounds fishy! why would you set the language as the state?!! You should read the language from user entity (the creator).

Have fun debugging rules!


How to alert users when new content is added via email and/or text message? I have a membership Drupal 7 website and I'd like to automatically alert users via their email address and/or text message to their cell phone when new content is added? I'd also like to give registered users the ability to select/change these communication preferences.

Is there any Drupal way/technique that can provide this functionality?

Have a look at my answer to "How to send an SMS message when a Webform is submitted?", which is a variation of your question here. It describes how you can use the Rules module to get this to work. In your case just use a Rules Event like "after saving new content", and optionally add some appropriate Rules Conditions to better fit your exact needs.


What license can I apply for a theme I sell? I'm interested in creating a premium theme to sell online; I've heard a lot about the Drupal GPL licensing and wanted to make sure I've got my facts right.

If I understand it correctly, everything that works with Drupal, such as the template files and any Drupal related JavaScript counts as "derivative works", so those bits I will have to distribute as GPL.

However, things like the CSS and Images that make up most of the "design" of my theme I can distribute under my own licence, and therefore charge for.

I used the Collective Mind's End User License Agreement (EULA) as a guide.

Is this correct? Does this change if I use one of the many base themes in Drupal? Are there any practical consideration?

One technique you might consider is committing your basic theme to a project on drupal.org, distributed under the GPL.  Then, develop premium css and graphics that can be installed over your basic theme using instructions that you provide. The later package could be distributed under a license of your choice.

It is okay to use a separate license for the css and graphics files because they can be considered separate works that stand on their own. To make it more clear that the css and graphics are separate works, you could distribute them with a static html file that shows what the final theme should look like. Your customer has the right under the GPL to combine the css and graphics with his GPL theme; tt would be a violation of the GPL to distribute the combined works, but they can be used by the licensee of the separate works (your theme).

Finally, regarding the "basic theme", note that there is nothing special about css and graphics vis-a-vis the GPL; it is still necessary to deliver the "source" of your works along with the "binaries" when they are included in a GPL-licensed distribution. If you built the css using some tool, then you must deliver the source files that were used to produce that css. If you created the graphics in photoshop with layered psd files, then you must also distribute those files with your theme, and so on.

Edit Edit Edit: Reworked my prior answer(s) for clarity, and to remove a mistake.

Postscript: I believe that the FAQ referenced below is partially incorrect; graphics and css are not excluded from the GPL because they are "data"; if they are an integral part of the work being distributed, then they are covered by the GPL as much as the code is.


How can I show/hide a block on specific taxonomy URLs depending on term depth? I need to show blocks on different url's.

Block1
Should be displayed on:
branches/taxonomytermlevel1
But not on
branches/taxonomytermlevel1/taxonomytermlevel2

Block2
Should be displayed on
branches/taxonomytermlevel1/taxonomytermlevel2
But not on
branches/taxonomytermlevel1

The terms
/taxonomytermlevel1/taxonomytermlevel2 are variables (elements in some taxonomy list)

What is the most easiest way to do this? I think a php script in the block display visibility setting would be the trick and so I tried some code there but I did not succeed.

Some code I have now is e.g.:

<?php
if (empty(arg(3))) {
  return TRUE;
}else {
  return FALSE;
}
?>

Any suggestions?

There is another way to answer your question, without PHP in the block settings: you can use the Rules block visibility module for this. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the appropriate menu block is shown on the appropriate pages).

For an illustration of how to use this module, refer to my answer to "How to show blocks by url, when nodes have multiple paths?". It includes some Rules Components (in Rules export format), which you should replace by the your variations to make it match your specific question.

So with 2 (similar) rules, 1 for each of both blocks, you should be able to get this to work.

To actually "determine the path structure in rules" (as in your extra comment below this answer), you might want to use a Rules Condition using a regular expression. Similar to the Rules Condition in the rule I included in my answer to "How to automatically skip intermediate redirects?".

Using regular expressions opens up many more situations (on top of the Rules block visibility module) where this solution can work. If you're not familiar with Regular Expressions (not obvious ...), then maybe you also want to look at my answer to "How to suppress a core Drupal warning or error message set with drupal_set_message for site users?".

Bonus:

This approach does NOT require the PHP filter to be enabled either (which you should try to avoid whenever possible) ...


Up-to-date solution for cloning commerce product-variation types and their product displays I am using Drupal 7 with commerce module. There are a lot of product-types with a plethora of fields – but in general, only a few fields differ, the vocabularies attached to the product for example. So I would like to stubbornly clone the product-variants and their product-display and make some minor changes manually afterwards. It's important, that the display settings are cloned, too.
While researching, I found a confusing amount of modules that seem to offer that kind of functionality:

replicate_commerce
bundle_copy_commerce
bundle_inherit
field_tools
features_clone
https://www.drupal.org/sandbox/davidfiaty/2745827

I would be glad to hear advices from savvy people for modules and appropriate workflows.

After trying out all above modules, I can clearly say for my usecase the winner is:
bundle_copy for cloning product displays in combination with bundle_copy_commerce for the product variations.
Cave: I didn't use the clone/copy feature of both moduls because of errors and poor cloning (fieldgroups weren't copied) – instead I used the export/import feature:

Export the entity
Replace in the code from step 1 all occurences of the bundle name with a new name
Import the code from step 2 again.
When using fieldgroups you have to make sure, you rename the fieldgroups in step 4 with a unique name (add the bundle name as a suffix, for example).


Filter condition for entity reference field I am trying to create filter condition for  entity reference field added, but i am unable see the data when i give input in created filter condition text, i am trying from long ago searching in all possible way but dint got the reason please let me know what could be the issue,i will be very thankful.

you can use Views Reference Filter Veiw Reference Filter Module for reference fileds.


Clear data stored with drupal_static() and cache_set() I have a custom module in Drupal 7 where I am caching data from REST calls using drupal_static() and cache_set().

function _mymodule_call() {
  $data = &drupal_static(__FUNCTION__);
  if ( ! isset($data) ) {
    if ($cache = cache_get(__FUNCTION__)) {
      $data = $cache->data;
    }
    else {
      $data = my_api_call();

      if ( is_object($lists) ) {
        // cache for one hour
        cache_set(__FUNCTION__, $data, 'cache', time() + 3600);
      }
    }
  }
  return $data;
}

I want to make an admin feature where we can specifically clear these cached values. I suppose the cache key would be _mymodule_call. How do I clear them from the cache?

The Drupal way is to have a $reset parameter to your function.  It would look something like:

function _mymodule_call($reset = FALSE) {
  if ($reset) {
    // do stuff
  }
  // ...
}

node_load() is probably the best example of this.

In your specific case, you can pass the $reset parameter to drupal_static() or explicitly call drupal_static_reset().  For the cache backend, you need to think whether you want to just rework the logic and just do the cache_set() or explicitly call cache_clear_all($cid) (my guess is the former).

And remember, that drupal_static() is only effective when you need the value multiple times during the same request.  This does not persist between page loads (or any other HTTP request that get handled by Drupal).


How to create a custom Date Formatter for grouping in Views? I have a view of content type "event". One of the fields is a category of the event which is a taxonomy list and i have a field for the date and time the event takes place.

Now i have set up the view showing the events in a time period i can set through an exposed filter, grouping the events by their date-field (nr.1) and as a second group field by the category (nr.2).

I am sorting this view with the event-field (ascending) as the first sort criteria and Taxonomy term: Weight as the second sort criteria.

It works as designed, but every event that shares the same time on a given date creates an own group row:

Like this:

Category-Name

4/12/2013

Event1 12.00h
Event2 12.00h

4/12/2013

Event3 13.00h

4/12/2013

Event5 14.00h
Event6 14.00h

What i want to achieve is this:

Category-Name

4/12/2013

Event1 12.00h
Event2 12.00h
Event3 13.00h
Event5 14.00h
Event6 14.00h

Question: is it possible to have a formatter that has stripped out the time, so i can group by date only?

Of course i tried a custom display formats for the date beforehand, but this doesn't affect the grouping.

EDIT: the hint about the RDF module helped partly with this issue. I could remove the extra markup in the date field. Nevertheless the sorting of the date field still takes the time of the event into account. There's another sorting i didn't mentioned in the first place, cause I didn't expect it to be relevant.

The location of an events is referenced as entity and also added to a row of an event and sortet by title (asc). Now the date-field is superceding the title of the location, because the event-time is still taken into account.

I had started another question on this other issue, but actually think it belongs here. I still need to strip out the time somehow...

Views uses the rendered value for the field, including the field wrappers to do grouping. In your case, views is treating each date field differently.

There are 3 ways this can be fixed. One of the following methods should do it.

Remove the tags from the rendered output.

Using a custom template and a preprocess function, you can strip all markup and print the output only.

views-view-fields.tpl.php
template_preprocess_views_view_field

Turn off the RDF module. Views will take care of the grouping itself. The RDF module adds extra metadata to your markup, which makes views separate the grouping as shown in your example above instead of grouping the similar dates together.


How To Change The $tid to $term_name I've tried to change this code to show the term name instead of the term ID
but now no term name or term id show at all

Orginal code for term ID

function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }   } }

What I changed it too

function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $term_name = $info['term_name'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
        }
      }   } }

Many thanks for your help

To convert from $tid to term name, use  taxonomy_term_load() to load the object, and then access $term->name:

$term = taxonomy_term_load($tid);
$term_name = $term->name;

Your function should look like:

function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
      foreach ($content['field_photo_topic']['#items'] as $index => $info) {
        $tid = $info['tid'];
        $term = taxonomy_term_load($tid);
        $term_name = $term->name;
        $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
      }
    }
  }
}

Please note that this will only work the way you intend if you use PathAlias or similar to alias the path to be accessible by  term name instead of numeric $tid.


How would i redirect a user after registration to his subdomain site I want to redirect a user after successful registration maindomain.com to open his site in a new tab.

His site url will look like this newuser.maindomain.com. (username.maindomain)

Any Suggestions?

Use Rules again to do the redirect.

On Event Drupal is initializing or User has logged in add a condition if you need that (eg check that user role is not anoymous) and then add an Action of Redirect. In there use some php for the redirect path using the global variable $user (you may need some formation also if the username has spaces).

Notice that you must run this Rule after the rule that creates the subdomain. Or you can simply add the redirect action on the same domain_rules rule after the component that creates the subdomain.

You must also have a common user database along sites (domain and subdomain). The Bakery module is a good option here.


How can I remove everything from a Commerce cart if a certain product is added, except that product? I'm sure this is pretty simple to do but I'm spacing out on it.

If a product of a certain type is added to the cart, I want to remove everything in the cart , regardless of its type, except for that product. At the same time I need to make sure that the quantity for that product will never exceed 1.

I've started a hook_commerce_cart_product_add() implementation but I haven't got very far with it:

function MYMODULE_commerce_cart_product_add($order, $product, $quantity, $line_item) {
  if ($product->type == 'the_product_type') {
    // Now what?!
  }
}

I'm more than happy to use Rules instead of custom code for this, but again I haven't got very far trying it that way.

Any pointers would be greatly appreciated.

This is the code I ended up using:

function MYMODULE_commerce_cart_product_add($order, $product, $quantity, $line_item) {
  if ($product->type == 'directory_subscription') {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

    // Loop through the line items
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
      // If this is the product we're keeping, make sure the quantity is always 1.
      if ($line_item_wrapper->commerce_product->product_id->value() == $product->product_id) {
        $line_item_wrapper->quantity->set(1);
        $line_item_wrapper->save();
      }
      else {
        // Remove any other product from the order
        commerce_cart_order_product_line_item_delete($order, $line_item_wrapper->line_item_id->value());
      }
    }
  }
}

If anyone has any suggestions on how to improve the above I'd be grateful.


Programmatically change import URL of reference node My question is similar to this guy's from drupal.org:
https://www.drupal.org/node/2283931

But, I have reference nodes that import content from various URLs and I want after each import, to change the (feeds source) URL of the reference node.
I guess I will use hook_feeds_after_import() but how am I going to target the reference node instead of the importer and run a function on that source?

Answering my own question, it's basically the same. The $source object is the node itself, so in my module I called a hook like this:

function MYMODULE_feeds_after_import(FeedsSource $source) {

    //Get the config
    $config = $source->getConfig();

    //Save the current URL
    $url = $config['FeedsHTTPFetcher']['source'];

    //Run a basic check
    if(strstr($url, 'since')){

        //Do some fancy stuff with it and create a new one

        $newurl = 'http://foo';

        //Save the new configuration in the source node
        $config['FeedsHTTPFetcher']['source'] = $newurl;
        $source->setConfig($config);
        $source->save();
    }

}


HTML isn't rendering, HTML tags are being printed I added a view template views-view-fields--nieuws--page.html.twig to my theme.

The template is correct, when I edit it I see the results on my website.

{% for field in fields %}
  {{ field.separator }}
  {{ field.wrapper_prefix }}
    {{ field.label_html }}
    {{ field.content }}
  {{ field.wrapper_suffix }}
{% endfor %}

In page.html.twig I print the region like this:

{{ page.content }}

But my output has HTML tags in it, any idea how I can solve this?

EDIT: It appears my HTML is rendering at all through Twig

{% set hello = 'Hello' %}
{{ hello }}

outputs the  tags, too.

This is currently a known bug with the views-view-fields.html.twig template: https://www.drupal.org/node/2363423


How can I rearrange taxonomy weights for terms with two-deep hierarchies? I have a taxonomy vocabulary on my site of user ages.

It looks like this:

However, I want to change the weight so that 20s is -19, Late Teens is -18, Early 20s is -17, etc.  In other words, I want to change the weight so that when I sort by weight in Views, the terms appear in exactly the same order as shown on the screen above.

However, when I manually adjust the weights to -19, -18, -17, etc., upon saving the list of terms the weights are reverted to those listed above.

I tried individually dragging and dropping each term to change the order, but again when I saved the list, the weights had returned to this pattern:

Parent A 0
A Child A 0
A Child B 1
A Child C 2
A Child D 3
Parent B 1
B Child A 0
B Child B 1
B Child C 2
Parent C 2
Parent D 3

etc.

However, when sorting by weight in Views, this then gives a list like:

Parent A
A Child A
B Child A
C Child A
A Child B
Parent B
B Child B
C Child B
A Child C
B Child C
Parent C
C Child C

which looks terrible and makes no sense.

How can I manually control the weights and override whatever processing Drupal is applying to them?

For such small taxonomies (large and frequently changing ones will be a pain) you may create special custom field for flat sorting order, since weights are meant to be used on a certain hierarchy level:

Then you just add some sort criteria to your views:

Considering this terms structure:

you will get this output:

Good thing: this requires no code hacking at all, yet supports all Views features like caching.

Bad thing: you will go mad with setting this field values for large vocabularies.


How do I add a clearing DIV to the bottom of a region? In the eternal mission to care about Internet Explorer, I have a template region which needs a clearing <div<, since I think that ":after" and "overflow:hidden" tricks don't work so well in IE. (I'm currently not able to test this as I'm on a Mac without a virtual machine.)

Is there any region preprocess trick, or anything equally clean, in order of adding a clearing <div>? I'd prefer not to use Javascript, or add an entire block for this purpose, if it is possible.

I would find a common class for your region(s), and add in the clearfix rules.  With kosher HTML and CSS, I don't recall the last time this didn't work in IE for me.


Add classes to login form fields D 7 I ma trying to add foundation classes to my #user-register-form fields in D7

  Username *
 <input class="username form-text required" type="text" id="edit-name" name="name" value="" size="60" maxlength="60">

Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.

I have tried using template overrides like I have with my other custom fields

field--field_homepage_body.tpl.php

But with no luck any help would be appreciated.

You can do this by altering the form in your custom module hook_form_alter(){} or
in template.php of your active theme.

Just add the classes in the attributes array().

Or you can create a user-login.tpl.php file following this link, Its already answered here with this code.

<?php
    function operationscheck_theme_theme() {
    $items = array();
    $items['user_login'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
   'template' => 'user-login',

    'preprocess functions' => array(
   'operationscheck_theme_preprocess_user_login'
   ),
);
    $items['user_pass'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
   'template' => 'user-pass',
   'preprocess functions' => array(
   'operationscheck_theme_preprocess_user_pass'
  ),
);
 $items['user_register_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
'template' => 'user-register-form',
'preprocess functions' => array(
'operationscheck_theme_preprocess_user_register_form'
 ),
);

return $items;
}
?>

<?php
   function operationscheck_theme_preprocess_user_login(&$vars) {
      $vars['intro_text'] = t('This is my awesome login form');
    }
   function operationscheck_theme_preprocess_user_login(&$vars) {
     $vars['intro_text'] = t('This is my awesome pass form');
   }

function operationscheck_theme_preprocess_user_register_form(&$vars) {
    $vars['intro_text'] = t('This is my super awesome reg form');
   }

 function operationscheck_theme_theme(&$existing, $type, $theme, $path) {
  $hooks = operationscheck_theme_theme($existing, $type, $theme, $path)

  $hooks['user_login_block'] = array(
 'template' => 'user-login',
 'arguments' => array('form' => NULL)
 );

// @TODO: Needs detailed comments. Patches welcome!
return $hooks;

}

function operationscheck_theme_preprocess_user_login_block(&$variables) {
  $variables['intro_text'] = t('This is my awesome login formX');
  $variables['rendered'] = drupal_render($variables['form']);
}
 ?>

Please check if it is the code snippet you were looking for.


How to expose the user's email on the user's detail page? Currently in the manage display page there is no way to display the email field in the manage display page. How do you expose this in Drupal 8 contacts details page?

There can be a work around for this as in user template or views-block rendering on profile page.

By default the mail field is not configurable in view modes.

You can change this in a custom module. Place this hook in mymodule.module

function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'user') {
    if (isset($fields['mail'])) {
      $fields['mail']->setDisplayConfigurable('view', TRUE);
    }
  }
}

and you'll find the mail field in the Manage Display page.


Validate a file extension using getMimeType I want to create a hook that will validate a file upload and only allow jpg extension or a multiple array jpg, gif. I am not sure how to do this. If this  below can validate the length of the file title.

if (strlen($file
 ->getFilename()) > 100) {
    $errors[] = t("The file's name exceeds the 100 characters limit.");
 }

Then can something simular to this work?

use Drupal\Core\Form\FormStateInterface;
 function blank_moda_file_validate(Drupal\file\FileInterface $file) {
   $errors = array();

if ($file
 ->getMimeType()) !== jpg, gif) {
   $errors[] = t("The file is not a jpg or gif.");
}

You can use file_validate_extensions() for this


Prevent drupal_messages in drush I am creating a bash script to automate some stuff including drush commands. When using drush vget I always get Drupal messages, but I only want the value of the variable. This prevents me from correctly using the drush vget output. I already tried with output formats etc. but I always get the messages. How to prevent the Drupal messages to use the output of drush vget in my shell script?

I just realized they are just printed to the command line and are not contained in the return value itself. So it is actually working. Since I was printing my variable directly for debugging it looked like it contained the messages as well.


Distributed Solr Indexing from Drupal I want a sharded Solr environment so that I can distribute data and query accordingly. Started two solr instances as described here.

Since Solr doesn't support (fully yet) writing automatically into different Solr instances, I have to do it manually.

I'm trying to do it in the following hook:

/* "node" is the module name. */
function node_apachesolr_index_document_build($document, $entity, $entity_type, &$env_id)
{
}

Note that I'm trying to change the $env_id by making it a reference parameter, since that's what I want to change based on certain logic. When the cron is run, I get the error:

  Warning: Parameter 4 to node_apachesolr_index_document_build() expected to be a reference, value given in module_invoke_all() (line 857 of /var/www/drupal-7.17/includes/module.inc)

since it messes up with existing calls.

Any idea how to workaround this? Thanks.

According to the documentation, the function hook_apachesolr_index_document_build(), on line 373 of file apachesolr.api.php, is not a reference value, instead directly a variable. So, the code should be:

function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

Also, from the code you use, I suspect the following possibilities:

You are adding the code to the core node module, which is never recommended, as one should never hack core.
If you are adding this code to a custom module, and name that module node (as you mentioned in the comment of the code), that will conflict with the core node module, and might cause conflicts and break down your code.
If you add this code to a custom module (with a different name), then it is a wrong way to implement a hook in custom module. Follow this guide to get started with module development.
Lets say, if you name your module "custom_search", then you should place this code in the file custom_search.module, and implement it in the following way:

function custom_search_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

Note that, I've replace the hook in the function name with the module name "custom_search"


How to get the inreverse selection of a Views query? Imagine that you can easily create a view that gives you a subset of some content on my site. However, you want the opposite view - all the content minus that subset - and that view is very hard or impossible to create.

The question then becomes: Is it possible to invert the result/selection of a Views query?

NB! Sorting is irrelevant for this question: It's all about the returned selection of items, not the order of the items.

It is simple. Go back in your Views Settings and find Sort criteria. There you can either reversely sort bu date: Content: Post date (desc) or by alphabetic order. It depends what field you take as sorting criteria.


Export data to CSV programmatically in drupal 7 I am using the following code to extract all the users belonging to a group:

// Send response headers to the browser.
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->mail . "\n";
}
print $output;
exit;
}

Even though I load all the users correctly the output I get is in Chinese. That means something is breaking the CSV format. Any ideas how to export data to CSV in Drupal 7?

@potney i have updated your code.Please check

drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->mail . "\n";
}
ob_clean();
print $output;
exit;
}

I have used this code it works for me

            $filename='filename.csv';
            ob_clean();
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');

        $contents="Date  \n ";
$contents.='11/05/2014';

echo $contents;

Please check this.Hope this will work


Aegir fails on verify task after import task (Import an existing not aegir site) i'm having many problems with importing sites into aegir hosting system:
here is what i do to import a web site into Aegir:

import the directory of the web site into platforms dir
import the DB into the db of Aegir
create a dir in the sites dir calling it with the domain of the site.
cp -r sites/default/* sites/
cp -r sites/all/* sites/
from Aegir fron-end create the platform giving it the path of the root website dir
Aegir verify plaform and detect the site to be imported.
Execute the import task with success(i think here is the problem)
The task import has a success result (but i think is did not work because the scope is a wrong scope, it takes the main scope of aegir).
then the verify task fails, did not create the vhost.d/ , it didn't create drushrc.php file under the sits/.

i think the problem is:
when drush overwrite settings.php and try to store the information of the DB access in the apache environment it fails.
i don't know why...i already made many imports (last one was one week ago), i don't think i changed any thing.

please help me!

I found the right way to make import in the docs, my problem was how to start my import site with my DB, the best way is here:
http://docs.aegirproject.org/en/3.x/usage/sites/importing/#importing-a-single-site-manually.
To load your DB you may use drush @www.site-domain.it sqlc < file-db.sql
I hope this can help others to make import files.


CSS\JS Aggregation "Shuts down" Firebug indication I have CSS\JS Aggregation on, and I've installed the AdvAgg module and set it for Development mode. The site works fine, but now I can't really use Firebug...

Firebug no longer shows me, for example "Style.css, line 50", but rather something like "fdn_jkfdk_aaahjfdh.CSS, line 500". I guess it's the aggregated file...

Anyways, Is there any way to get "Style.css, line#" appearing again without disabling aggregation? I can't sacrifice the option to make CSS edits in the site just for aggregation... I guess no one can!

Advagg has a built in feature to bypass aggregation for a single request.  You can append ?advagg=0 to the query string to load the page without aggregation.  I haven't personally used this feature, but it seems it could be useful in your situation.

From the module description:

  Url query string to turn off aggregation for that request. ?advagg=0
  will turn off file aggregation if the user has the "bypass advanced
  aggregation" permission. ?advagg=-1 will completely bypass all of
  Advanced CSS/JS Aggregations modules and submodules.

This would help with your problem of having readable css in firebug, but any changes you make to your sites css would still need a cache clear to take effect.


Where can I learn about how to create a custom exposed filter for Views 3 and D7? I am trying to learn how to create a custom exposed filter for a contributed module (select or other).  I found this tutorial for Drupal 6 but the code doesn't appear to work out-of-the-box on Drupal 7.

I also tried looking at the code in the hierarchical select module but it seems to be much more complex than what I am trying to do.

Does anyone have any suggestions for tutorials or modules that implement custom exposed filters in a relatively simple way (e.g., not a huge number of custom handlers like the location module) that I can learn from?

I was lurking around the internet trying to find answer for the same question and this is what I've got in result:

Implement several hooks in your custom module. Replace modulename and filtername with your actual names.

/**
 * Implements hook_views_api().
 */
function modulename_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'modulename') . '/inc',
  );
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function modulename_views_handlers() {
  return array(
    'info' => array(
      // path to handler files
      'path' => drupal_get_path('module', 'modulename') . '/inc',
    ),
    'handlers' => array(
      // register our custom filter, with the class/file name and parent class
      'modulename_handler_filter_filtername' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function modulename_views_data() {
  $data = array();

  $data['node']['filtername'] = array(
    'group' => t('Custom'),
    'real field' => 'my_custom_filter_field',
    'title' => t('My custom filter'),
    'help' => t('Some more detailed description if you need it.'),
    'filter' => array(
      'handler' => 'modulename_handler_filter_filtername',
    ),
  );

  return $data;
}

Create folder named inc inside your module folder and create file named modulename_handler_filter_filtername.inc there (see code above for implicit reference to this file). Don't forget to use actual module and filter names.
Paste following code into that modulename_handler_filter_filtername.inc file. The code I used for this example creates a set of radio buttons that present years. So you can filter nodes by year created, using only years in which nodes were created.

class modulename_handler_filter_filtername extends views_handler_filter {

  /**
   * Options form subform for setting exposed filter options.
   */
  function value_form(&$form, &$form_state) {
    parent::value_form($form, $form_state);

    // get list of years from database
    $query = db_select('node', 'n');
    $query->addExpression("FROM_UNIXTIME(n.created, '%Y')", 'year');
    if (isset($this->view->filter['type'])) {
      $query->condition('n.type', $this->view->filter['type']->value, 'IN');
    }
    $result = $query->orderBy('year', 'ASC')
      ->execute()
      ->fetchAllAssoc('year');

    $years = array(
      '0' => t('All'),
    );
    foreach ($result as $k => $v) {
      $years[$k] = $k;
    }

    // create form element with options retrieved from database
    $form['value']['year'] = array(
      '#type' => 'radios',
      '#options' => $years,
      '#default_value' => end($years),
    );
  }

  /**
   * Alters Views query when filter is used.
   */
  function query() {
    // make sure base table is included in the query
    $this->ensure_my_table();

    // retrieve real filter name from view options
    // this requires 'real field' filter option to be set (see code above)
    $real_field_name = $this->real_field;
    // get the value of the submitted filter
    $value = $this->view->exposed_data[$real_field_name];

    // finally, alter Views query
    if (is_numeric($value) && $value != 0) {
      /*
        Having several custom exposed filters, make sure subsitution patterns
        (e.g. :filtername_value below) don't match across different filters.
        I spent some time figuring out why all my filters had the same value.
        It looks like the query skeleton is built first and then all replacements
        are made in bulk. Prefixing value with filter name looks good imo.
      */
      $this->query->add_where_expression($this->options['group'],
        "FROM_UNIXTIME(node.created, '%Y') = :filtername_value",
        array(':filtername_value' => $value));
    }
  }
}

That's all you need to get simplest custom exposed filter working!

Note that using FROM_UNIXTIME in condition of SELECT query may slow your database.


Using drush to change options of contrib module I would like to use drush to change one of the options stored in a large options field of a contrib module configuration table.

drush vset/vget, as far as I know, only work on the options that are stored in the variables table.

Is there a way to do this using drush on the variable directly, short of retrieving the whole field (using drush sql-query), modifying it (using unix tools), and updating it (again, using drush sql-query)? It needs to be automated, as this is a frequent task.

Or can anybody suggest a different approach that is more elegant?

Check to see if the contrib module has a modulename.drush.inc file in it.  If it does, then the module provides Drush commands, and you can find out about them via drush help --filter=modulename.

If the command does not supply any Drush commands, the next thing to do is to open up the modulename.module and scan through the source code, and see if it has any API functions that perform the operation that you want to do.  This can sometimes seem intimidating, but it's worth a shot!  If you'd like to set the frobulation level of the module to 28, maybe, just maybe, you might find a line that reads function modulename_set_frobulation_level($value) ....  If you do, then you can call it with Drush like this:

drush ev 'modulename_set_frobulation_level(28);'

If you do this a lot, you could make a Bash function for it, or, better yet, create a custom Drush command and contribute it back to the contrib module.  Making a custom Drush function is really easy with the drushify command.

If you are unlucky, you will not find a nice set_frobulation_level function; sometimes, the code you want is only available in a form submit handler.  This is distressingly common in contrib modules.  Rather than try to figure out how to post a fake form submit, an even better option is to just factor out the code you'd like to call, and make the modulename_set_frobulation_level function yourself.  Then, it's easy to create a Drush command for it, and you can contribute the whole shebang back to the contrib module when you are done, helping out the next person who travels this same road.

This might sound like a bit of work, but it's no harder than reverse-engineering the sql commands you'd need to run, and the results are much more satisfying.


Images are locked by .htaccess I just uploaded a new website to a one.com hosting.
From the start I had some trouble with the .htaccess file, after I was finally able to get everything to work, I ran into another problem.

None of the images appear to be loading, when I browse directly to an image, I get this message

  Internal Server Error

  The server encountered an internal error or misconfiguration and was
  unable to complete your request.

  Please contact the server administrator, support@one.com and inform
  them of the time the error occurred, and anything you might have done
  that may have caused the error.

  More information about this error may be available in the server error
  log.

My .htaccess file is the default one with clean urls enabled.

An .htaccess can cause Internal Server Errors that are unrelated to PHP.  Bad directives in the file (eg, syntax errors) and using restricted directives (eg, doing an Option + that has been denied by the main Apache configuration) are two likely culprits.  I see the later very frequently with shared hosting.

The only way to really debug this is to find the Apache error log.  This varies from system to system.  On my CentOS machines, they are at

/var/logs/httpd/error_log

If this isn't your location, do a find error_log to track it down.  You may need to be root to read this file.


How to insert a image gallery into node body? I created a gallery using fields (gallery formatter and lightbox) but i can only add the gallery before or after the field body.

I tried the insert module but it can only add one picture and not the whole gallery.

Is there a way to insert the gallery into the field body at a specific location?

This may or may not work for you, try WYSIWYG FIELDS module. If it doesnt work, I cannot think of another turn-key solution.

  The Wysiwyg Fields module is bridge between CCK Fields and the Wysiwyg
  module, allowing most (if not all) CCK fields to be turned into a
  Wysiwyg button for a convenient inline solution.


Drupal 7: Find which user created a given user I have a number of users admins (group: "users_admin") who create users who can view content (in many groups, like "students_a", "students_b", "students_c", and so on).

Is there a way to filter the users by their creators?

Let me clarify:

User "A" from "users_admin" create a user "S1" in "students_a".
User "B" from "users_admin" creates a user "S2" in "students_a".

I would like to be able to differentiate users created by "A" and "B", has anyone done that before? Is it possible?

I hope I made myself clear enough; please tell me if you need some clarifications.

Thanks in advance for you insights!
Regards

Drupal, by default, does not keep any authoring information of users.

However, there is a module for that! Try Sub User module. It uses Relation module to maintain the relationship with parent user.


How can I display a search form with a different style from search bock, inside a node? I have a search block enabled at top side of my site. But I also need to display the same search form, but with different css class applied inside a node. How this can be done?

Since blocks can only go in a single region (without some messing about), I think you'll have to use code for this. You could add the form in a preprocess function in your theme's template.php file:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_node_type') {
    $form = drupal_get_form('search_form');

    $vars['search_form'] = render($form);
  }
}

Now in your node.tpl.php file, or node--content_type.tpl.php file, you'll be able to output the search form like this:

<?php if ($search_form): echo $search_form; endif; ?>

The default classes and ID added to the <div> surrounding the node will be be perfect for targeting that particular instance of the form with CSS. You can easily use developer tools/firebug to determine what selector to use.


Drush sql-sync not placing file in specified dump-dir I have a dev and staging alias setup for drush and they are both working correctly. I included a reference to where I want the dump file placed during a drush sql-sync using

  'path-aliases' => array(
    '%dump-dir' => '/home/.drush/db_dumps'
  )

However, when I run the command it runs successfully but it doesn't use my dump directory. Instead it uses /home/user/drush-backups. I tried changing the location of my dump-dir to a location inside of the drupal site folder, but it still doesn't work.

One of the solutions that I found was to include the --source-dump option (which points to the same location as I have in %dump-dir) when running drush sql-sync. It seems like if that's the case, then why even bother adding it in my alias file.

Another solution states to also include a reference to the actual dump file using %dumpin the path-aliases array. I tried that and it still doesn't work.

Is there a solution to this or is it not suppose to work at all?? Because the example.aliases.drushrc.php file doesn't mention dump-dir at all.

Using:
Ubuntu 14.0.4,
Drush 8.0.5,
Drupal 8 site

Thanx

I actually posted the same question in the Drush GitHub and they did in fact tell me that sql-sync was rewritten (removed in e89c7c4) and it no longer includes the option for a dump-dir.

As per GH #2125, they've said:

  It gzips and transfers the full dump every time. It uses a temp file in your specified temp dir for the transfer. Files are deleted right after rsync.

So I guess all documentation that is out there is old.


SSL Certification for Forms On my home page there are four links: Home, Contact Us, Company News, and Login.

I want Login and Company News to use SSL Certification.

How can I achieve this?

You can use Secure Pages Module to configure https pages, but before that you need to get a valid SSL Certificate and get it installed in your server.


Rewriting the output of a file download field I have a content type with two fields, one pdf field which will be downloaded using the Download File module which provides a formatter (file download) to automatically download the pdf file with one click and one image field linked to the pdf field, using the Linked Field module. This works in the node without problems.
The problem is when trying to rewrite the results of the image field in Views.
I set the file field with the "File download fomatter" and exclude it from display.
Then, I try to rewrite results of the image field like this

{{ image_field }}

or

{{ image_field }}

but this is not working.

The files are stored in the folder

[root]/file-download/download/public[node:field_file_download:entity:fid]

What am I missing?

The "File download fomatter" you're using doesn't output just the path to the file, it's a more complex formatter and you can't use it in your case as a path to download the file.

In Drupal 8 there is a separate Field in File Views called URI that you need to use.

Depending on which Drupal 8 version you're using you'll see only the formatter File URI and you need to tick the option Display the file download URI to get the link you can use in an anchor href attribute later when overriding fields.

Do not enable Link this field to the file download URL, this outputs complex anchor HTML, not just the path that you're after.

You can exclude it from display, position it above the image field and Rewrite results for the image:

{{ image_field }}

or let Drupal link it:


How can I collect data through a drupal form? I want to allow users to contribute posts to my site. Should I set up a content type that can be created by the public or set up a new user role and get people to sign up first? I want to reduce the friction of adding a post to the absolute minimum.

I'd let users login first to prevent spam. However you could simplify the registration&login process by having users authenticate with OpenID (Google, facebook ect.) Similar as what stackexchange offers.

This should get you started: https://drupal.org/project/openid_connect


How to make a panel page the default local task I've got a custom module providing local tasks like entity/%/edit and I'm trying to get entity/% to show up as the default local task. entity/% is defined as a Panel Page using the panels module. How do I do this? Whenever I change the menu type to "local task" or "menu tab" (or "default menu tab") the local tasks disappear from the display. This is in Drupal 7.14 with ctools 7/x-1/0

I was eventually able to get this to work. The page needed to be a "default menu tab" with the path entity/%/view or similar. With that, entity/% loads the path entity/%/view and all of the tabs show up as expected. This turned out to be more a problem with my understanding of default local tasks than anything else.


Remove entire column from the table programmatically in twig file In my twig file views-view-table--myview.html by default a table is coming with header and rows. And I want to remove entire column from the table programmatically in twig file.

How it can be done?

User hook_views_pre_view()checkout this code snippet.

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {

  if ($view->id() == 'view_name' && $display_id == 'page_1') {
    $view->removeHandler($display_id, 'field', 'name_of_your_column');
  }
}

Bingo!


Increasing the search query limit (Apache Solr) We want to create a search page with Apache Solr with an increased query limit. I was reading that using hook_search_execute was not a recommended way to do this.

Is this statement correct? What would be the recommended way to go about this?

Apache Solr Views module?

Some other solution?

The page absolutely has to have more than 10 search results, and no pager.

To do that programatically, you can implement hook_apachesolr_query_alter() to play with the rows parameter :

function yourmodule_apachesolr_query_alter($query) {
  // Increase the number of results per query
  $query->replaceParam('rows', 50);
}

Note : To disable the pager you can set a very very large number of rows, but it may impact performance. In this case you may prefer to bypass the pager at another level (for example in a preprocess function) and go with a more reasonable rows value.


Different urls for front page depending on language I'm using entity translation module and want to have different urls for front page in accordance with languages.

For example:
front-eng
fr/front-page-for-france
pt/front-page-for-portugal
etc.

Use this code in your template file then you can page accoding to your choose language

  function yourtheme_preprocess_page(&$vars) {
        if ($vars['is_front']) {
            $langcode = $GLOBALS['language']->language;

            if ($langcode == "en") {
                drupal_goto('home');
            } elseif ($langcode == "fr") {
                drupal_goto('front-page-for-france pt');
            }
        }


How to migrate nodes from a dev site to a production site? I have a staging site and a production site.

For an error some nodes was updated on the production site and now I have to update it but, if I will do that I will lose the production site changes.

What is the best [and faster] approach to migrate some nodes from production to staging before migrate staging to production?

Sounds like Node Export to export your nodes from dev and then re-import them on your live site.

Node Export provides several ways to export nodes:

Through a tab that appears on the node page.
Using update options on the Content page.
In a command line using Drush.
Using the Features module.
Using the Views Bulk Operations module.

and the Node export package comes with the following formats:

JSON
Drupal var export
Node code
CSV
Serialize
XML


Should a form only be users to collect input and not display it? I'm using the Form API in a custom module to collect a large amount of user data, which is then collated and assessed to provide an output.

Currently I'm using ajax to refresh the form and display the output when the user submits the form. Should I be displaying the results in a different manner, or is it perfectly reasonable to do it in this manner?

Say for example I have a Myers-Briggs type survey. The user would answer a long string of questions, which on submission, I then collate and redisplay the form with results, links to other content, relevant articles etc (not just a simple result).

Is this too heavy use of the Form API to provide content, or is it reasonable for a performance and development standpoint to do it this way?

i.e.

$form['results']['#markup] = '<my markup>'

I think its totally fine to do what you want with Form API. I once did something similar for a personality test module. On the final submit the node gets reloaded but this time in a different view mode to provide the results. If I remember it right I got inspired by Drupal's poll module which uses/used this view mode approach. By that you have both parts divided a little bit better - logically and performance related. Could that work for you?