Filter Entity reference based on attribute Here's my situation: I have a "Project" content type. I want to be able to add employees to a project based on their role with a select or multi-select drop down widget with unlimited number of values. So I can add multiple people with different roles.

I would like to be able to choose a Role first - say a "designer" - and then have the drop down for the entity reference only show just the roles for designers.

Project
  --> choose Role "designer"
  --> choose designer "John Doe"
  Add next person
  --> choose Role "??"
  --> choose person "??"

What are possible ways to do this?

The best way I found offering a very high amount of flexibility is to combine the two following components:

The Dynamic Dependent Fields (DDF) module takes in charge the relation between the other fields composing your form and your Entity Reference field.

Concretely, it will add a new mode for the entity selection, "Views: Filter by an entity reference view with dynamic argument", which allows you to dynamically pass the value of one or several other fields of your edit form as contextual filters to a view.

The magic here is that the values proposed by your Entity Reference is dynamically updated upon modification of the controller fields content (JavaScript).

The only limitations I encountered with this module is that it does not support autocomplete fields as the controlee Entity Reference fields, drop-down lists must be used instead. Moreover, DDF does not take into account programmatically set default values for the controller fields, however I submitted a patch solving this.
A patch for Entity Reference (currently in RTBC status) adds the possibility to use tokens now as contextual filter for the views and complement very well the above mentioned DDF module.

For instance, this patch allows very easily to exclude the current entity from the Entity Reference available choices.

Associating the two modules let your Entity Reference fields available values to be generated by a View taking into account both tokens and other fields values. Hard to get more flexibility !


How do I define an external URL in settings.php and call it in a custom module? In the settings.php file, there are (for example) $base_url, $settings['hash_salt'].

I defined $settings['external_url'] = "google.com";

In my custom module, I want to get the $settings['external_url'] value.

<?php

namespace Drupal\my_custom_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Site\Settings;
use Drupal\Core\Form\FormStateInterface;

/**
* Contribute form.
*/
class MyCustomClass extends FormBase {

   private $base_url;
   public function __construct(){
       $this->base_url = Settings::get('external_url') . '/maps';

   }

   public function validateForm(array &$form, FormStateInterface $form_state) {
      $pb= $form_state->getValue('pb');
      $url = $this->base_url . '?timeline' . $pb;
   }
}

Then I got this error:

Notice: Trying to get property of non-object

I am using Drupal 8 and PHP 7.

Trying using the full path of the class:

\Drupal\Core\Site\Settings::get('external_url')

In Drupal 8, an ideal place for custom variables is in config files. Create a yml file in the config directory and import the configuration.

my_variables.settings.yml

external_url: 'url-string-here'

Then to fetch the values, it's:

\Drupal::config('my_variables.settings')->get('external_url')

https://www.drupal.org/docs/8/converting-drupal-7-modules-to-drupal-8/step-4-convert-drupal-7-variables-to-drupal-8


Drupal Rule to deselect radio button item? In Rules, I don't see any option to deselect radio button items.

In my rule, I want an Action which is to deselect 'Request Resubmission', as in this screenprint.

There is none that I'm aware of.

Radio buttons aren't meant to be deselected (a single selection is required). I would suggest using checkboxes to deselect an option or add a "None" option to your radio group.


Replacing theme() with render() in a block_view I'm trying to replace the theme() with render() as recommended:

https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7
So I started with:

 function mymodule_block_view()
 {
  $variables['module_path'] = drupal_get_path('module', 'mymodule');
  $block['subject'] = t('mymodule Slide');
  $block['content'] = theme('mymodule', $variables);
    return $block;
  }

And I tried

 function mymodule_block_view()
 {
    $variables['module_path'] = drupal_get_path('module', 'mymodule');
    $block['subject'] = t('OpenDTP Slide');
    $rdr = array(
      '#theme' => 'opendtp_slide',
        '#module_path' => $variables['module_path'],
     );
    $block['content'] = render($rdr);
    return $block;
}

But it says Undefined variable for module_path that I used in the tpl.php file.
How I'm a supposed to use variables in the template then ? What is the correct way of doing it ?

How about:

...
$rdr = array(
  '#theme' => 'opendtp_slide',
  '#module_path' => drupal_get_path('module', 'mymodule')
);
...


How to customize the map used on gmap module (node locations) When gmap module and location module are installed, there is a page called "node locations", which display all node with a location field (filled) in the site.

How can I customize the google maps parameters? I want to disable the satellite map (and options in top right), enable street view, and change the zoom widget..

Thank you

The google maps parameters can be changed in file: "sites/all/modules/gmap/js/gmap.js"

Here is the option I choose:

Street View enabled:

opts.streetViewControl = true;

Satellite map disabled:

opts.mapTypeControl = false;

Zoom widget change:

opts.zoomControl = true;
opts.zoomControlOptions = {};
opts.zoomControlOptions.style = google.maps.ZoomControlStyle.LARGE;


What is the Drupal 7 bookmarking module (a la delicious.com) that is equivalent to userlink in Drupal 6? I am using the Web Links in Drupal 6, and I would like to use its equivalent in Drupal 7. It doesn't appear to be a clear direction, according to Comparison of Links Page modules.

For Drupal 7, I am using the Link module. It defines simple link field types.


Print custom product variation field in order email confirmation Added custom field ('field_secretkey') under Commerce - Product variation (admin/commerce/config/product-variation-types).

I am able to get this value in Orders view by adding the "Product variation" relationship.

I just want to print this value in order confirmation email (commerce-order-receipt.html.twig) It can have multiple items with different values.

Please advice.

Example:

No | Product Name | Custom field

1 | Product 01 | XYUSNMAI

2 | Product 02 | AYUSSAAA

3 | Product 03 | PAUSNPPP

Updated: RESOLVED - TRY BELOW

URL - {{ order_item.getPurchasedEntity.field_custom_field.0.uri }}

TITLE - {{ order_item.getPurchasedEntity.field_custom_field.0.title }}

You should be able to get the product from the order which is available in the template.

I think that this will give you the products:

{% for order_item in order_entity.getItems %}
  {{ order_item }}// The product
  {{ order_item.FIELD_NAME.value }}// The field value
{% endfor %}

Otherwise you must add the product in a preprocess function.


Is it possible to create a table from Paragraph fields in Views? I'm trying to create a table in Views with the information from a node that is using Paragraphs. Somehow I can't find a way to display the values from the paragraph fields in a proper table, is this even possible?
All I can manage to do is the table as shown in the picture below:

If possible, how can I create a table where each field has its own column instead? And if that's not possible – what other approach should I use?

You need to enhance your view with Relationships.

Let's say you have a content type Client with a paragraphs field Mail, which allows embedding instances of the paragraphs bundle Client_Mail. When you create a view on all Client nodes, you should find a Relationship to the field (Mail) which contains your paragraph bundle (Client_Mail).
After adding this relationship, the fields making up the paragraphs bundle will show up in the field list. You can add and arrange them like regular node fields, but make sure that the paragraphs relation is chosen in the field settings.


Radioactivity and Rules- difference between "add an incident" and "set the energy" I want to increase the radioactivity level after flagging the node.
But I don't know exactly how to set the value.

If I fill in the value form field with 60, the Radioactivity text field will increase over 200.

So maybe the action settings are wrong.
What is the difference between the following actions?

add an incident to a field
set the energy of a field

You can do any custom logic you want using the Rules module which integrates with the radioactivity module.

Add an incident to a field - this increments or decrements the energy level by a specified amount.
Set the energy of a field - this sets the energy level to the specified amount.


How do I redirect to a route with POST method? I want to redirect to a route and also want to send some parameters which I don't want to expose on URL.

So, I need to redirect with a post method. How to do this?

$form_state->setRedirect('route.name', array('key' => 'value'));
new RedirectResponse(\Drupal::url('route.name',array('key' => 'value')));

all these above procedure to redirect is done through GET methods.

So, is it possible to do this with POST method?

Normally, you cannot redirect through a HTTP "POST" response. A normal Drupal RedirectResponse (or whatever redirect response you send) will be a 302 or 301 redirect, which is done through the GET method.

Basically, you can do a subrequest, as suggested by Eyal, or you can add some server validation to grant a "200 OK" response through your "hidden" route, such as a CSRF token. To keep alive some posted information, you can use your Session service to flash them for the next request, then flush them in your hidden route after your validation


drupal 7: new field with dynamically generated select list from PHP code I have a new node type where a user is asked who he or she knows from the site.  They are to be presented with a select list with the names of the existing users on the site.

When creating this new select list field in Drupal 7, I noticed that the PHP snippet is gone so I cannot dynamically generate the select list text and values.  Is there some Drupal way (Views?) to do this without having to download the CCK (development status) module for Drupal 7?  The CCK module is not ready for prime time in Drupal 7.  I understand that their rationale to remove PHP snippets are for security reasons (http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args).  The Drupal team would not leave us hanging without this common functionality, right?!??!

I think your best bet would be http://drupal.org/project/entityreference module and the entityreference_view_widget. PHP filter is still there in D7 but you have to enable it under modules.


Access view exposed filter arguments in field view My problem is that I can't access $view->filter['my_filter_field'] from my views-view-fields.tpl.php file.

In views-view.tpl.php I get my correct View object with the arguments sent via AJAX as exposed filter parameters, but how can I get this information without using the field's template file?

You have to use object methods (functions) to get and set exposed filter inputs.

E.g.

Use $views->get_input_filter and $views->set_input_filter($filters).  The format for filters is as follows:

$filters = array(
  'identifier' => '[your ident name]',
  'value' => '[your value']
);


How to turned off the translation on the node reference with entity translation? I have a multilingual site and I am using the feed module to import content. My site has two languages:

English and Arabic.

During import the node from excel value all the fields value save except node reference field value in Arabic language.

Previously i am having same issue for term reference. But it is solved by disabling Select taxonomy terms by language on  "admin/config/regional/i18n/select". But Node reference issue still there is there any settings present for this.

I got my answer.

There is an option for "Select nodes by language" in "admin/config/regional/i18n/select".

I just unchecked it. my issue has been solved.


Which actions in Drupal needs clearing the cache? I'm a newbie in Drupal. I usually use the clear cache function from Devel module for each changes(sometime I use drush command line tool) like: modify CSS, create/change blocks, change permissions, create new content type, create new web form, change template files... and clearing the cache costs a lot of time on my local environment (I've just 1GB of RAM).
So can anyone show me which actions in Drupal that we need to clear cache.

Strategy is quite easy - clear it when you changed something in code or database.

Below some popular cases (based on my experience):

you added new content and need to update cached pages, views or blocks (for example you enables cache for anonymous users)
you changed JS or CSS files and you have enabled aggregation
you installed new modules (in this case need to run update.php)
you did modifications in existing module which require update cache. For instance added menu item or implemented some hooks.
you did changes in theme files


How to reset my password if I forgot it? I forgot the admin user pass for my site. Then I followed the process to recover my password. I get an email with a link (available for 24hs) which allows me to login in my site. I go to 'user/1/edit' to create a new password, but the old one is a REQUIRED field. This is wrong, I forgot my password, then I can't fill this field.

Am I missing something here??

While you can change admin password either by drush or by running mysql query if you have access to database if you do not have direct access to your mysql server, install devel and wrap the mysql query with drupal query wrapper functions and run it at /devel/php page.

You may want to consider having nocurrent_password module which removes the current password field and you can directly update your passwords, NOTE: this behaviour will be same for other users as well.


How to retrieve a file or image from a content type? I'm using services module to get data from database, among those data there is an image.

All fields are loaded except the image, the uri seems to be wrong.

here's the postman response :

  "writer": "writer1", <==== ok
  "picture": "public://couverture_harry_0.jpg",<=== not ok(wrong path)
  "review": null, <====== ok
  "date": "2010-02-05",<===== ok

I've configured drupal to store on sites/default/files

the picture is there but the real path is :

drupal/sites/default/files/couverture_harry_0.jpg

(if I enter this path manually on postman it shows me the picture)
But by default the path services put is wrong.

How to "configure" services or drupal to get the good path ?

EDIT
This is my custom resource to retrieve a book (livre in french) :

function my_module_get_livre($entity_id) {
// check uid && entityID

$result = db_query("SELECT `field_title_value` as titre, `field_prix_value` as prix, `field_auteur_value` as auteur, `uri` as couverture, `field_resum__value` as resumé
    , `field_date_de_parution_value` as parution, `denomination_ed` as editeur,`field_nombre_de_pages_value` as pages FROM {field_data_field_titre_en_arabe} as t_ar
    inner join {field_data_field_prix} as pr on t_ar.entity_id = pr.entity_id
    inner join {field_data_field_auteur} as aut_ar on t_ar.entity_id = aut_ar.entity_id
    left join {field_data_field_photo_de_couverture} as ph_couv on t_ar.entity_id = ph_couv.entity_id
    left join {file_managed} as file on ph_couv.field_photo_de_couverture_fid = file.fid
    left join {field_data_field_resum_} as resu on t_ar.entity_id = resu.entity_id
    left join {field_data_field_date_de_parution} as d_paru on t_ar.entity_id= d_paru.entity_id
    left join {field_data_field_edit} as edi on t_ar.entity_id = edi.entity_id
    left join {editeur} as ed on edi.field_edit_target_id = ed.uid
    left join {field_data_field_nombre_de_pages} as pages on t_ar.entity_id = pages.entity_id
    WHERE t_ar.entity_id = $entity_id ")->fetchAll();

return array('code'=>'0', 'response'=>$result);
   }

 function my_module_livre_retrieve ($entity_id){
      return my_module_get_livre($entity_id);
    }

I've also tested this (it works) :

$fid ='2'; <=== i put it manually(but it would be set by select query
$file = file_load($fid);
$realURI = $file->uri_full = file_create_url($file->uri);
var_dump($realURI);<==== returns the real url (localhost/drupal/sites/...

I want to 'alter' or just put the $realURI value to every book(livre) in his field : "photo de couverture" (which is the pitcture i want)

Thank you

Yes, this is an annoyance, no doubt.  Drupal stores the uri using a public:// streamwrapper. Thankfully, someone has written the code to resolve that into a full url that gets attached to the file object for you whenever one's loaded: https://www.drupal.org/project/full_url_file_info


How to disable edit links/tasks for mobile theme? I have a separate sub domain and theme for a mobile version of my site. I would like to disable the edit links/tabs for nodes if viewed from that subdomain/theme, but still allow users from editing in the main theme.

Any help or tips will be appreciated.

Items should be disabled, if they are usually enabled, but not useful in that particular circumstance. For example, a submit button could be disabled when the form does not validate. Having an item that is permanently disabled raises the question why the item is displayed at all.

If you want to hide the items, you can do this using CSS if there is an appropriate CSS selector. Have a look at the HTML to figure that out.

For Drupal 4.7.x, 5.x and 6.x, you can also remove the links as described on the drupal.org page Remove unwanted tabs from pages.

Note that both methods only remove the link from the page. They do not prevent users from actually editing the page (e.g. by entering the URL manually).


How to access nid in views I'm trying to build a simple module that renders facebook like boxes for each article. To do that, I need to know full absolute path to article.

I have my views set up to show all published posts as content (teaser). But I would like to insert a custom markup after each item. For that I need to know nid, so I can build a link that leads to article. How can I do that?

Here is how my views is set up: http://i.imgur.com/bMHtzTo.jpg

If you're using the rendered entity style I don't think you can do it through the UI - Views passes off the display to node_view() in that case, and doesn't get involved with the markup for the row.

The easiest way to do what you want is to implement hook_preprocess_node(), look for a View in the current context, and if the node is being rendered as part of that display, you can make some alterations.

For example

function MYMODULE_preprocess_node(&$vars) {
  if (!empty($vars['view']) && $vars['view']->view_name == 'foo') {
    $nid = $vars['node']->nid;
    $vars['extra_link'] = l('Some text', "node/$nid");
  }
}

Then in your node.tpl.php file you'll have access to $extra_link.


Why would I provide a composer.json for my modules? I’ve come across several Drupal7 modules that include a composer.json. It seems that this somehow influences how Drupal-CI determines test dependencies. Now I’m trying to find out whether it’s worth providing a composer.json at all in Drupal7 modules/themes maintained by me. I couldn’t find any hard facts about what exactly can be achieved by providing a composer.json, that’s why I’m looking for pointers to …

How does the presence of a composer.json affect processing in the Drupal-CI?
What other functionality is enabled by providing a composer.json file for Drupal7 modules (or themes)?

Note: There seems to be a lot of documentation about Drupal 8 / composer, but nothing specific for Drupal 7 / composer.

Here is a list of some Drupal7 modules with a composer.json:

currency: Specifies exclusively non-Drupal dependencies.
raven: Specifies exclusively non-Drupal dependencies
stringoverrides: Only  package metadata, no dependencies.

I wrote a blog that gives some case studies about when and why you would include a composer.json with your module: https://www.morpht.com/blog/drupal-and-composer-part-4-composer-drupal-developers

Basically it comes down to four things:

It allows your module to be managed with composer.
It allows your module to have it's Drupal module dependencies managed by composer
It allows your module to have it's 3rd party library dependencies managed through composer
Composer handles autoloading of namespaced classes in libraries it manages, meaning your module can use the 3rd party libraries it depends upon, without having to include any files

If none of the above requirements match your needs, then there is no reason to have a composer.json file in your module.


How to make a specific region use a specific template? I'm currently working on Drupal 7 project in a Zen sub-theme. Each of my region uses "region.tpl.php" as HTML/PHP template. I just created a new region called "foo". This region needs a different HTML/PHP than the other regions.

How do I make Drupal use my custom template "region--foo.tpl.php" instead of the default "region.tpl.php"?

I thought Drupal already added the theme hook suggestion for region--name.tpl.php, but if not you can add it yourself with a preprocess function in your theme's template.php file:

function MYTHEME_preprocess_region(&$vars) {
  $vars['theme_hook_suggestions'][] = 'region__' . $vars['region'];
}

Once you clear Drupal's caches your new template file should start being used for that region. It might be worth noting that you'll probably need a copy of the core region.tpl.php file somewhere in your theme folder as well, or the theme registry might not pick up your custom file.


How to get Signatures for Forums using SQL query? In a D7 site, I'd like to get all of the user signatures using raw mysql query .
I've found a signature_forum_post table but could not figure out how to make a query that returns both user.id and signature text, so appreciate your help.

Please try the following.

if ($account->id() && isset($form_state['values']['user_signature'])) {
    if (!$account->get('user_signature')->isEmpty()) {
      db_merge('user_signature')
        ->key(array('uid' => $account->id()))
        ->fields(array(
          'signature__value' => $account->get('user_signature')->value,
          'signature__format' => $account->get('user_signature')->format,
        ))
        ->execute();
    }
    else {
      db_delete('user_signature')
        ->condition('uid', $account->id())
        ->execute();
    }
  }


Attaching 'active' class to faqfield expanded question I am using the FAQ Field module my project which utilizes the jQuery Accordion UI and HTML definition lists, and I am wondering how I can attach an 'active' field to the expanded question. I would like to know so I can show/hide an up/down caret next to each of the questions based on it's active (expanded) state.  I am using Drupal 7.  Thank you.

This functionality is provided by FAQ Field using the jQuery Accordion UI.

In Structure > Content Types > Your Content type > manage display (admin/structure/types/manage/[your_content_type]/display), if you change your FAQ field display settings from Definition List to Accordion, an up/down caret is shown next to each question.

If you click on the gear icon corresponding to your FAQ Field you can configure which question is active by default, as well as whether the questions are collapsible.

Result:

The Accordion setting also adds the class ui-state-active to the active question element (an h3) and the class ui-accordion-content-active to the active answer element (a div).


Composer is git cloning modules instead of download them? My composer file looks as follows:

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/drupal-extension": "~3.0",
        "drupal/search_api": "1.x-dev",
        "drupal/search_api_view_modes": "1.x-dev",
        "drupal/paragraphs": "^1.0",
        "drupal/features": "3.x-dev",
        "drupal/robotstxt": "^1.0",
        "drupal/search_api_solr": "1.x-dev",
        "drupal/metatag": "1.x-dev",
        "drupal/pathauto": "1.x-dev",
        "drupal/acquia_connector": "^1.4",
        "drupal/sharethis": "2.x-dev",
        "drupal/field_group": "1.x-dev",
        "drupal/ckwordcount": "^1.0",
        "drupal/menu_link_attributes": "1.x-dev",
        "drupal/yaml_editor": "1.x-dev",
        "drupal/devel": "1.x-dev",
        "drupal/menu_block": "^1.4"
    },
    "replace": {
        "drupal/core": "~8.2"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url":  "https://packages.drupal.org/8"
        }
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "modules/contrib/{$name}": ["type:drupal-module"],
            "themes/contrib/{$name}": ["type:drupal-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    }
}

For all the modules that were downloaded as a 'dev' status, they appear to have been git cloned. Therefore, the changes aren't recognized or saved to my git tree, and don't push. These modules did not make it to my remote repository, and did not show up on the remote website.

I am not sure how this occurs, but for time being, I had to:

cd into module directory
rm -rf .git folder
git rm --cached modulename
git add modulename
git commit -m "Adding module"
git push

The module(s) then make it into my project repository and make it up to the remote server.

What is the correct workflow here? I am not running any build process or tool remotely but want to retain my project build with composer tracking the modules and themes I have installed.

Yes, that's what it does when you specify a dev version.

The recommended way to handle a composer project is to not commit composer managed code. all you commit is the composer.lock file and it is guaranteed that a composer install with install the exacty same versions, every time.

See https://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md for more information on that and ways to work around it if you really want to.

Have a look at https://github.com/drupal-composer/drupal-project, it gives you a project environment that is preconfigured using the recommended git ignore settings and follows modern standard by keeping the vendor folder and other non-publich files out of the public web folder.

Update: One of the reasons why git does it, is that drupal.org AFAIK does not give you the possibly to download a specific dev snapshot, only the latest. And one of the main features of composer is to build the lock file and get the very same commit every time you run composer install, until you run composer update again.


How to save the URL of anonymous user on a webform? Using Webform 7.x-3.18, I'd like to save the referring URL of an anonymous visitor on a webform. I added some code to MYTHEME__preprocess_page() in template.php to save the info as a cookie:
user_cookie_save(array('webform_referrer' => $_SERVER['HTTP_REFERER']));

On my webform I added a hidden component, with a default value of %cookie[Drupal_visitor_webform_referrer].

I'm testing with safari/chrome/ff on a Mac and on Windows. I can get this to work on my local testserver, but only about 10% of the time on the production server, and never from Windows to the production server. The production server has hardware load balancing. I'm suspecting this is a caching issue. I've also read that server vars may not be available as webform default values for anon users (http://drupal.org/node/296453#comment-2397674) - is this the issue? Why then would it be working for anon users coming to my local server?

I can't think of another way to integrate this easily into webform as a hidden field. Perhaps I have to write some kind of custom hander to save the referrer?

So you can achieve this using form alter,

create a text field namely 'refer_url' for saving referring url, then using following snippet in your module you can save the referring url. You can hide this field in display using css or form alter.

function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_27') {
    $form['submitted']['refer_url']['#default_value'] = $_SERVER['HTTP_REFERER'];
    }
}


Using a Paragraph field value as a View filter I am attempting to create a view and paragraph combination that allows for site authors to customize the content that they want to display.

What is currently working:

Within my site is the content type of Article
I have a view, called News, that is set up to display the published Articles.
I created a Paragraph called Article Scroller (article_scroller) that uses a Views reference field (field_view_ref_news) to display the above view.

The above setup allows authors to add the News view to any page, such as a Basic Page or another custom content type. This is all working great.

Where I'm stuck:

I want to take this a step further and allow for the content author to define a filter for the view, such as a location. To do this, I added an Entity Reference field to my Article content type called "Location" (field_location). This is populated with a value from a taxonomy list of states (e.g. Texas).

I then added this same field (field_location) to my article_scroller paragraph.

The idea is that an author would add Texas to an article, and then if they wanted to customize the view to show Texas articles only, they would also define this term within the paragraph.

From there, I'm not sure how to proceed. I'm pretty sure I need to add some kind of relationship and contextual filter here, but am struggling because the term/tid is not going to appear within the URL, and the options under "Provide default value" don't seem to be relating to what I want to do (at least, nothing I've tried from other posts and research has seemed to apply).

Another confusing thing is that I only have my one "field_location" field, but within the view, it appears as two different fields - one under the "Content" category and the other under the "Paragraph" category, which makes sense, but seems to complicate the contextual filters even more as I have to choose between "Content: Location" and "Paragraph: Location".

I know that one alternative method would be to create a view page/block for each location, Texas, California, New York, etc. I am just hoping I can do something a bit more dynamic.

Have you seen these Modules, i have not used them but they look like they do the job.

https://www.drupal.org/project/viewsreference
https://www.drupal.org/project/viewfield

Otherwise you could preprocess your paragraph and render the view

function renderView($viewId, $displayId, $arguments)
{
    $result = false;
    $view = Views::getView($viewId);

    if (is_object($view)) {
        $view->setDisplay($displayId);
        $view->setArguments($arguments);
        $view->execute();

        $result = \Drupal::service('renderer')->render($view->render());
    }

    return $result;
}


How to render the main menu in alphabetical order regardless of menu link weight? We are using the main menu of Drupal to build out the main navigation of the site. The content creators have access to add a menu link for a node in any level of the main menu and they are also able to use the weight field to set the location of where the menu link will fall under.

We are using a superfish menu block to render our main menu. We are having trouble figuring out how to always alphabetize regardless of what the current user's language is. How would we accomplish this?

Example scenarios:

For English content, the main menu will display all links only when the user's locale is English. Additionally all menu links for English should always be alphabetized regardless of the menu link weight.
For Japanese content, the main menu will only display Japanese menu links, but also in alphabetical order
For German content, the main menu will only display German menu links but also in alphabetical order.

I found that if the menu link weight is the same, then the alphabetical order will be applied.


How to import date fields using CSV file? I'm trying to import few nodes using feeds CSV file. I'm able to import some of the fields but I'm unable to import CCK date fields.

I have tried feeds module with uc_feeds_product_importer.

How can I import date fields?

This was an issue with the feeds importer. I deleted the existing importer and created a new importer with new mappings, then all the date fields started working as normal.

The date format I use in the csv file is: 23-Apr-12


Index Data from External Database for Search - Views I have a Drupal 7 view which obtains data from an external database and displays it on the page. I would like to index this external data (read through Views) so that the resulting items can be searched for using Drupal Search. How do I go about doing this?

Like Michiel said Solr is a good option but is complicated to set up.

Another option is to implement a Google search server that can then be integrated with Drupal using the Google Search Appliance module. This is a paid solution but easier to setup.


Pinterest-style image presentation page? Any Ideas how to create pinterest style image presentation page(view)?

Basically, it is like a page that have images in columns, images in each column have same width but different height.

For that, you need to use Masonry jQuery plugin. With Drupal you've this module but it's not available yet for Drupal 7.x, so you should either make your own template with the plugin or try to port the mentioned module into Drupal 7.


Feed import save empty value in multilingual site I have a multilingual site and I am using the feed module to import content. My site has two languages:

English and Arabic.

When my excel files have English content, it imports properly.

But if excel file having Arabic content, it imports and shows in view page but in edit page it not displaying.

Feeds: Entity Translation

  This module adds support for importing data through Feeds into
  translatable fields handled by Entity Translation.

  The module exposes fields that are translatable into all enabled
  languages, enabling the creation of translations of entities when
  importing.

Another fantastic Solution

Import from two xml files (on for each language), my empiric solution :

I created two feed imports.
I forced the language field for each one.
Two separated nodes were created for each content (one in each
language) but it didn't links the translations.
So I used a SQL query to finish the job, it's based on the feeds uuid


Access denied to all profiles of a certain type I am migrating from D7 to D8. I've had success with everything but the profiles from D7's profile2 module.
Four profile types have to be migrated. One of them is being migrated without issue: I can view and edit them. The other three, however, are giving me "Access Denied" errors when I try to view them. There is no difference in the parameters for the individual profile type migrations, aside from the names of the fields and the names of the profiles themselves.
When I view the list of profiles at admin/people/profiles, only one type of profile as an option to edit it. The others just have a button that says "Devel."
My user has permission to view, edit, and create profiles of all types, so it does not appear to be a permissions issue. I know for a fact that the data is being migrated, because I can see it in the MySQL DB. I have also cleared the cache, updated the db, and rebuilt the permissions.
I'm stumped, and I really need to have access to those profiles.

Drupal Version: 8.9.6
PHP Version 7.3.22
MariaDB Version: 5.5.5-10.4.14

Incidentally, using the patch at https://www.drupal.org/project/profile/issues/2957256 made the migration of profiles possible in the first place.

I think I understand what's happening now. During migration, empty profiles were made for users who did not have profiles on the origin site. That is why access is denied: there isn't anything to access. That message really should be "a profile doesn't exist yet," or something like that. I can see the existing profiles without any issue.


Entity reference for feed imports not working on some referenced nodes I've posted this problem on drupal.org but I feel that it's so cryptic that maybe it deserves a larger audience.

For some reason, when I'm trying to import users that are associated with group nodes some imported users do not have any referenced group nodes associated.

I've noticed that the group nodes that cannot be referenced are only nodes that have been imported via a previous feeds import. Despite this, users that are created through the user creation form CAN be associated with the group nodes that do not work through the feeds import process.

There are two php warnings that occur when an entity reference cannot be created through the feeds process:

Warning: array_keys() expects parameter 1 to be array, boolean given in entityreference_feeds_set_target() (line 132 of /home/angelo/dev/client/profiles/openatrium/modules/contrib/entityreference/entityreference.feeds.inc).

Warning: reset() expects parameter 1 to be array, null given in entityreference_feeds_set_target() (line 134 of /home/angelo/dev/client/profiles/openatrium/modules/contrib/entityreference/entityreference.feeds.inc).

This implies that for some reason
127: $handler->getReferencableEntities($value, '=')
isn't returning what it's supposed to and I'm not too sure why.

Has anyone else run into this issue?

Fixed. It turns out there were erroneous microsoft nbsp characters in the feed CSV that looked exactly like spaces. This resulted in the referenced entity not being found.

Removing these characters made the feed work correctly.


Twig/variable support in Custom block HTML I'm trying to understand if/how you insert Twig variables in blocks in the custom block library.

To clarify, the block's HTML has been configured via the UI at /admin/structure/block/block-content

Standard Twig syntax, e.g. a 'say-something' tag like {{ base_path ~ directory }} - which I want so I can set an <img src attibute correctly - doesn't seem to be parsed at all and I don't see a way to use Tokens.

Examining the HTML source with Twig debugging on, it's theme hook is listed as "field", so if I add a preprocess function:

function themename_preprocess_field(array &$variables, $hook) {
  xdebug_break():
}

that's being called rather too often
when it does reach the custom block, there doesn't seem to be anything in $variables that labels it as such, other than a render array with the processed text:

$variables['items'][0]['content]['#text']

What's the simplest approach for this? Is the only way to do it to write a module?

Thanks,
William

You can't use twig variables in the body field of a block (or a node). But you can use tokens. Install the modules Token and Token Filter. You need to add the token filter to the text format you are using in the body field.


more than one content type in a condition? I'm using this as below described in my subtheme (Thanks to @4k4 and @Berdir):

function kanu_preprocess_node(&$variables) {
  if($variables['node']->getType() != 'test') {
    return;
 }
  $field = $variables['node']->field_where_to_publish;

  if (!$field->isEmpty() && $field->entity->label() == 'public') {
     $variables['display_submitted'] = FALSE;
     $variables['content']['comment']['#access'] = FALSE;
  }
}

How to write it for 3 different content type (with same field names)?

You can use in_array.

$types = array('one', 'two', 'three');

if (!in_array($variables['node']->getType(), $types)) {
  // code
}


Theming a view of comments I have a view which creates a block of comments.  I have a comment.tpl.php in my theme folder which I use to theme the comments on the node.

To theme the view, I need a variant of comment.tpl.php and have tried the following:

comment-view.tpl.php
comment-views.tpl.php
comment-view--name-of-view.tpl.php
comment-view-name-of-view.tpl.php

After cache clearing each option the template is still not picked up.

How can I theme this view please?  By the way I am using the Omega theme.

Ok, I came up with some sort of solution, thanks to @clive.

function hook_preprocess_comment(&$vars){
    if (isset($vars['view'])) {
        $view = $vars['view'];

            if ($view->name == "my_view_name"){
            $vars['theme_hook_suggestion'] = 'comment__' . str_replace('-', '_', $view->name);
    }
  }
}

I tried to do $vars['theme_hook_suggestions'][] but those templates were never picked up.  Is it ok to directly set theme_hook_suggestion.

Really hope this helps someone else out there..


How do I change the input type of an exposed filter in a view? I have a view which lists products. I created an exposed filter based on price criteria.

The exposed filter shows a text input where you can type an integer number to get the products filtered. What I need is to replace the text input with a select list showing values such as 50000, 100000, 1500000, 200000.

I have the Better Exposed Filters module, and the Views PHP module enabled.

Edit View >> Configure filter criterion >> Select grouped filter (instead of the default, single filter) >> Set-up your options. That's it! you now have dropdown filters of free filled node field.


Does anybody know how to add the remove button in a custom module (field type) with unlimited number of values? I am trying to add my custom field/module to a content type. I select Unlimited for the Allowed number of values option in Field Settings and I am able to Add another Item, however there is no remove button. Furthermore, each time I edit the content; an extra (blank) field is added.

The custom field type has to implement a method which tells whether the field is empty (if the inherited default method is not able to do this).

For example for a numeric field:

NumericItemBase::isEmpty()

  public function isEmpty() {
    if (empty($this->value) && (string) $this->value !== '0') {
      return TRUE;
    }
    return FALSE;
  }


How to show organic groups users that their subscription is pending? I'm using the Organic groups (=OG) module. When a user subscribes to an OG they just see "Unsubscribe from group", even if they are not yet members, but their membership is pending. What is the best way to display a message such as "Thanks for your subscription request, it is currently being considered." or something like that?

Note: I have quite a number of questions related to Organic Groups but this is the best place I have found or support. If you can suggest other sources of OG support I would be very grateful!

A possible solution for this is to use a combination of the Flag and Rules modules, which integrate very well with the Organic groups module.

Here are the highlights of how you could make it work:

Create a 'global' flag (using Flag) that will be used to identify (flag) users with their membership is pending
Create a 1st rule (using Rules) like so:

Rules Event = User has become a group member
Rules Condition = og-membership:state EQUAL TO pending
Rules Action = set the flag (defined as in "1.") the user (using Flag)

Create a 2nd rule (using Rules) like so:

Rules Event = User has become a group member
Rules Condition = og-membership:state EQUAL TO active
Rules Action = unset the flag (defined as in "1.") the user (using Flag)

Create a 3rd rule (using Rules) like so:

Rules Event = Content is viewed
Rules Condition = "Path matches some path on which you want to show such message"
Rules Action = Show a message on the site

In case you have multiple organic groups for which you want to implement something similar, you have these options:

Create a similar flag and a similar set of 3 rules for each of these groups.
Use the Rules Conditional module so that you can combine the above logic for all groups in an enhanced version of rule2, -3 and -4.
It would probably also be a good idea to move part of the logic in the above rules in a 'rules component'.

Using the Rules Conditional module you could also combine rule 2 and rule 3 above in a single rule.

In case the above may seem like overkill (2 extra modules, and 3 rules to be created ...), keep in mind that with these very same 2 modules you can implement lots (dozens?) of other functions/features. Probably also to address "... quite a number of questions related to Organic Groups..." you mentioned in your question.

Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module. For Organic Groups there is another set of amazing videos to Learn Organic Groups.

Possible alternative

For anybody who considers the Organic Groups module as rather complex (like me ...), have a look at the Group module as a possible alternative. For (way) more details about this module, refer to my answer to "How to create basic Organic Groups functionality with flags and references?".


How to display a table with results when a batch is finished I could setup a nice batch, everything is working well.

But when the batch is finished, I would like to display a beautiful table with the computed results.

I could do it with the drupal_set_message (see below) function, but it is not good enough. [if mandatory, I accept to be redirected to a new page... but how can I pass the result in this case?]

function my_batch_finished_callback($success, $results, $operations) {
    if ($success) {
        $header=[t("col1"),t("col2")];
        drupal_set_message( theme('table', ['header' => $header, 'rows' => $results]));
    }
    else {
        // An error occurred.
        ...
    }
}

You need to store your results somewhere to be able to display them. If they are only required temporarily, the Drupal cache may be an appropriate place to use.

You'll need a key to identify the cache item and make it unique to the batch. As batch callbacks are not passed the internal batch ID, which would be the ideal choice, you'll need to generate one, for which you can use the uniqid() function.

So your batch finished callback will be something like:

function mymodule_batch_finished($success, $results, $operations) {
   if ($success) {
     $key = uniqid();
     cache_set('mymodule_batch_results:' . $key, $results, 'cache',time() + 86400); // keep for 1 day
     drupal_goto('mymodule/batch-results/' + $key);
   }
   ...
}

In the callback function for the redirected page you can extract the key from the path and read the data from the cache.

function mymodule_menu() {
  $items['mymodule/batch-results/%'] = [
     ...
     'page callback' => 'mymodule_display_results',
     'page arguments => [2,],
     ...
  ];
}

function mymodule_display_results($key) {
   $data = cache_get('mymodule_batch_results:' . $key);
   if ($data) {
     ...
   }
}


Is Pathauto designed to modify URL requests? I have configured Pathauto to redirect /node/23 to /resource/resourcename. Should it render menus as /resource/resourcename, or still /node/23? If a user requests /node/23, is Pathauto supposed to change the request to /resource/resourcename?

Currently, it does allow for /resource/resourcename to be used, but it does not actively change /node/23 if it is entered.

Pathauto only creates path aliases for nodes, users, etc. based on patterns, i.e. /node/23 will also work with /resource/resourcename. However, no redirect is made. If you wish to redirect the node path to the path alias you could use the Global redirect module.

Once an alias is created all menus etc. will use the alias instead of the real path, in fact, all links created with the l() (url()) function.


How to force a menu parent link to be non-clickable? I want the parent link in the menu to not be clickable. As a path is mandatory, I have created a blank node, and in my module I substitute the link by a "#" char.

I used custom code in module because I have a multidomain/multilanguage site, and a mixture of Drupal and database own tables content for the links. Many solutions for custom menus could not be used as they were not compatible with Domain Access or there was some problem in customizing.

The code I use is:

$a = menu_tree_output( menu_tree_page_data("main-menu") );
if(in_array($value["#href"], array("node/123", "node/456"))) $nolink = true;

I wonder if there is a workaround to this problem, as the typical behavior for a parent menu is to be non-clickable, not to load another page, which would be, IMHO, less typical.

You can take look at Special menu items.

User can create a new menu item and place either "nolink" or "separator" to the Path field, without quotes.
Nolink item will be rendered similar to a normal menu link item but there will be no link just the title.

Here is another module you can check: Content Menu

You can create a new menu item as

URL – With the traditional menu item form
Dummy – As a dummy menu item (with simple dummy link target)
New NODETYPE – directly create a new content for the new item


Where is the setting saved when I modify a configuration setting? When I modify a setting from a custom module, where is that saved?  How can I get that setting without exporting the configuration?

https://www.drupal.org/developing/api/8/configuration/simple

See the section on Interacting with configuration and Reading configuration.

E.g. $config = \Drupal::config('system.performance');

I'm assuming the saved settings are configuration.


Display driving distance between coordinates I have working a site that needs mileage given between user coordinate and node coordinate. using location module. I thought it was returning wrong results, when I discovered it returns actual miles "as the crow flies" so to speak. I determined that when looking at what it plotted on a map. I need driving distance.

I am trying the store locator module (but it really doesn't let me do coordinates yet. But the mileage doesn't display there, and views doesn't let me do that, that I can tell.

Everything I have tried has failed. Anyone doing this?

You can use The Google Distance Matrix API

If you want it to display in views there are a few ways you can implement it Either as a custom module, theme the view, or use the views php module.


Entity reference in a content type for a taxonomy. Limit it to a single value I have a content type. Lets' call it Events. For said content type I have a field(event_type) set as an entity reference to a taxonomy named Event Type.

I've set the limit on the field(event_type) to a single value.

However, visually, I can add more than one value as a comma separated list of values.

As far as I can tell the last taxonomy term is kept as the value.

This raises the problem that at some point in time somebody may very well add more than one thinking that all of them will be kept.

Is there a way I can visually limit the values entered? Perhaps a dropdown or radio buttons or something?

If anybody can point me in the right direction I'd be grateful.

Also, I've searched in the Drupal 8 know bug list, but quite frankly the list is huge and I can't find it.

You should change the widget to a "Select list" instead of "Autocomplete (Tags style)".

You can find this on the "Manage form display" tab of the content type.


If a vocabulary and a view have the same machine name, will they conflict when exporting to a same feature? In other word, does the machine name of every type of Drupal object has its own scope? Do we need use some prefix?

If it's in a different table it's in a different scope. If it allowed you to set a similar machine name you are obviously in a different scope. If you go to a node page and try to create similar machine names you will get an error while adding the field.

taxonomyTable.same_machine_name is different from viewTable.same_machine_name

No they wont conflict when exported from features. on the features page it shows different sections like taxonomy terms, nodes, strongarm, image styles ect.. anything that could be related then it auto detects anything related and you can select what you want to go with it. That's why it's important to have unique machine names so you know right away what you are working with. When using features try to avoid using the same machine names; but you can get away with it


pattern name for override view templates Twig template - views-view-unformatted.html.twig contains :

#}
{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}
{%
set row_classes = [
default_row_class ? 'views-row',
]
%}

{{ row.content }}

{% endfor %}

I want to insert a
 tag after each
:

{{ row.content }}

{% endfor %}

It works, but for all and every {{ row.content }}. I want to do it only for certain views-blocks. Twig debugging offers me to theme a whole block (for example: block--views-block--news-left-block-1.html.twig) and I need something like views-view-unformatted--news-left-block-1.html.twig or some other way to insert the tag.

what is the correct filename to override view template?

Thank you.

Just use  views-view-unformatted--(your view block name).html.twig.
Eg. If your view name is Slideshow, use views-view-unformatted--slideshow.html.twig

This is a good reference point - http://redcrackle.com/blog/drupal-8/theme-views-templates


Adding a module dependency to a public project I have a module on drupal.org that is currently just has a -dev branch.  The module feature detects for another module, and uses it if available.  Otherwise, it can safely ignore it.  In other words, it is not listed a dependency in the .info file.

A bug report came in, and it looks like I may need to make this a proper dependency.

Is there proper way to handle this situation which minimizes people breaking sites if they update?

I would use hook_requirements() for this, at least in your next version.

It takes severity parameter:

  The requirement's result/severity level, one of:

  REQUIREMENT_INFO: For info only.
  REQUIREMENT_OK: The requirement is satisfied.
  REQUIREMENT_WARNING: The requirement failed with a warning.
  REQUIREMENT_ERROR: The requirement failed with an error.

What you want seems to be REQUIREMENT_WARNING

  Requirement severity -- Warning condition; proceed but flag warning.

That way admin will see that requirement is not satisfied, but will be able to proceed anyway. I currently have this in one of my projects:

If I click "try again", I can proceed, but I will not be surprised if next version will not allow me to proceed, and I am aware that some important functionality will not work if I will proceed now, without addressing this warning.

It's also a good idea to provide a link to installation instructions or drush installation helper syntax in your warning message, as seen on the screenshot.

It should be a temporary solution only, of course. After a week or two you could move your dependency to .info file. Module users will expect it, informed by your warning, and no further logic or warnings will be needed anymore.

Of course changelog and project's page should be a main source of information about serious changes, but many people update using Drupal's built-in functionality and will not even see module's page before update, so it is unsafe to assume they will know basing only on the assumption you posted it there.


How to add field to ALL webforms? How do I add a field to all webforms?
I have a website where I'm using webform for surveys and I want that on each survey there will be a field that is the same in all of the nodes/webforms.
Thank you.

You have 2 options:

Go to /admin/structure/types/manage/webform/fields and add a field. Then all your new webforms will use the new field.
Install the Webform Share module, create a webform as usual, create your field, click the Export tab, go to /admin/structure/types/manage/webform and paste your configuration in the Publishing options > Webform default components box.

If all you need is one simple field, I recommend the former option.


How to make drush to work correctly in Windows? In Linux drush is comfortable with all Linux native commands. But how to make it working in Windows?

Of course there is a drush installer for Windows and it is correct, but the real question is: how to make all commands to work correctly?

For example drush sql-dump returns this error:

'mysqldump' is not recognized as an internal command

I'm going to assume that you're trying to ask how to get drush working in windows.

If you consult the documentation there is a windows installer:

  The Drush Windows Installer provides a convenient way to install Drush
  and the components it needs in order to run on Microsoft Windows. You
  may download it from the attachments list at the bottom of this page.
  Please see the installation guide below for instructions on how to run
  the installer.

Furthermore, if you're trying to get drush working before 5.7 there's a manual installation guide if you need to:

  The Drush Make command does not work in Windows 7 / Vista, when using
  Drush release 5.5, 5.6, or 5.7. However, the current development
  version of Drush fixes this issue! The only problem is there is no
  windows installer program for this version.

  No worries. This article provides instructions for manually installing
  the latest development version of Drush in Windows.

Update:

  For example drush sql-dump returns this error :

  'mysqldump' is not recognized as an internal command

This is a seperate and non-drupal issue. This is caused because drush doesn't know the path to mysql.exe. You need to update your paths in order for msqldump to work. Search super user or stackoverflow regarding mysql, windows and or path together in order to get an answer. I used to know this but it's been too many moons.


How do I update a site after its installation profile is updated? Say I decide to add a new module to an installation profile I've created and used to build a bunch of sites with.  Can I easily use Drush to update all of those sites to the latest version of the Installation Profile?

I've just recently started to grok installation profiles, but I'm not sure if they are useful after a site has been set up.  I manage 40+ sites at work, so this would be amazing if possible.

TIA.

Aaron

I don't know if you have any problem using Drush to update the installation profile, but I use git and everything is fine.

If you have code (in the installation profile) that writes on the db and push this to production nothing will happen. So all your changes must done manually.

Finally, the installation profiles aren't the best way to maintain a site, after Drupal install nothing will happen.

About the 40sites take a look at Aegir. It's a hosting platform for Drupals.


Can I use a universal no-results display for Views? In Drupal 7, is there a way to set a default, universal No results message for Views? Which of these following options should work?

Should I use a Rendered Entity? If so can I create a node (say, called 'no-results')? Is the Entity Id field, the URL of the entity?

You can copy views-view.tpl.php template to your theme folder, then modify relevant part.

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

To:

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php else: ?>

<?php endif; ?>

You can keep the <?php elseif ($empty): ?> part if you still want to be able to override your custom output.

Cheers,


Field weight ignored on buildForm() I need to set the  $form['langcode']['#weight'] to -251.

I tried also to access the widget weight. But the position weight still remains on bottom of the form.

Why is that? I tried:

//form field sort ('#weight')
$form['langcode']['#weight'] = "-251";
$form['langcode']['widget']['#weight'] = "-251";
$form['langcode']['widget'][0]['#weight'] = "-251";
$form['langcode']['widget'][0]['value']['#weight'] = "-251";
$form['langcode']['#weight'] = -251;
$form['langcode']['widget']['#weight'] = -251;
$form['langcode']['widget'][0]['#weight'] = -251;
$form['langcode']['widget'][0]['value']['#weight'] = -251;

Also on the hook_form_alter I cannot change the weight.

Sometimes these arrays will have a #sorted key that needs to be set to FALSE for the array to be sorted (again) and your weight changes to have an effect. Here it would be at $form['#sorted'].


Prefix html before radiobutton (input field) I'm looking to insert some extra html before an input radio button. This is my html now:

        <input type="radio" id="edit-field-geslacht-und-female" name="field_geslacht[und]" value="female" class="form-radio">
        Female

        <input type="radio" id="edit-field-geslacht-und-male" name="field_geslacht[und]" value="male" checked="checked" class="form-radio">
        Male

        <input type="radio" id="edit-field-geslacht-und-other" name="field_geslacht[und]" value="other" class="form-radio">
        Other (transgender...)

Now I would like to add the following html before every radio input:

But how can I do this?

UPDATE:

I've tried to do it with theme_form_element function and now have this:

function theme_form_element($variables)
{
    if($variables['element']['#type'] == 'radio')
    {
        dump($variables);
    }
}

My dump shows me this array:

array (size=1)
  'element' =>
    array (size=27)
      '#type' => string 'radio' (length=5)
      '#title' => string 'Female' (length=6)
      '#return_value' => string 'female' (length=6)
      '#default_value' => string 'male' (length=4)
      '#attributes' =>
        array (size=0)
          empty
      '#parents' =>
        array (size=2)
          0 => string 'field_geslacht' (length=14)
          1 => string 'und' (length=3)
      '#id' => string 'edit-field-geslacht-und-female' (length=30)
      '#ajax' => null
      '#weight' => float 0.001
      '#input' => boolean true
      '#process' =>
        array (size=1)
          0 => string 'ajax_process_form' (length=17)
      '#theme' => string 'radio' (length=5)
      '#theme_wrappers' =>
        array (size=1)
          0 => string 'form_element' (length=12)
      '#title_display' => string 'after' (length=5)
      '#pre_render' =>
        array (size=1)
          0 => string 'ctools_dependent_pre_render' (length=27)
      '#after_build' =>
        array (size=1)
          0 => string 'conditional_fields_element_after_build' (length=38)
      '#defaults_loaded' => boolean true
      '#tree' => boolean true
      '#array_parents' =>
        array (size=3)
          0 => string 'field_geslacht' (length=14)
          1 => string 'und' (length=3)
          2 => string 'female' (length=6)
      '#processed' => boolean true
      '#required' => boolean false
      '#name' => string 'field_geslacht[und]' (length=19)
      '#value' => string 'male' (length=4)
      '#ajax_processed' => boolean false
      '#sorted' => boolean true
      '#after_build_done' => boolean true
      '#children' => string '<input type="radio" id="edit-field-geslacht-und-female" name="field_geslacht[und]" value="female" class="form-radio" />' (length=119)

I've tried to change the #children variable and add my html before it. But when I do that no element on my page is showing ... .

You can override the theme_radio function in your own theme :

function mytheme_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  if ($its_my_field) {
     return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
  else {
     return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }

Maybe try with the more generic function theme_form_element.

Make sure to add conditions to only affect the form or the element you need like in the example written above.


How to export a view to module file with CTool Bulk Export module? I am trying to export some views to module file. It could be done by Views Bulk Export module, but it looks like that Views Bulk Export no longer exists for Views 3??

It (views_export.module) left a node says

<?php
// This module has been removed, and this note is left here to ensure
// that users who don't delete their directory before upgrading have
// the code removed and to let people looking for it to know to use
// the CTools bulk export module instead.

So how can I export my view now?

I figured it out.

@kiamlaluno, the 'export' link in your answer (screenshot) does not require Chaos tool, it comes out of box of views. And it only exports view code, to module file.

To export to module, goto admin/structure/bulk-export, then tick views,


Can't get drush to work after moving to Acquia Dev Desktop I installed Acquia Dev Desktop. Most things work but drush does not. I get an error:
Drush was not able to start (bootstrap) the Drupal database.

Because I had previously installed php and mysql on my local, I removed those old versions and adjusted my ~/.bash_profile to ensure I was loading the Acquia Dev Desktop version of php, mysql, and drush. To test, I run "which php", "which mysql", and "which drush" all of which returned the Acquia Dev Desktop version.

To test mysql, from my drupal site directory I entered the mysql cli with "mysql". I ran "show databases" and confirmed the Acquia Dev Desktop Database is in this Mysql server.

To test the php, from my drupal site directory I ran "php -r 'phpinfo();'". I confirmed the PHP version/config loaded is the Acquia Dev Desktop version.

I see in drush looks for aliases in ~/.acquia/DevDesktop/Drush/Aliases/aliases.drushrc.php
I inspected that file and see the alias configured as loc.mysite.dev. I tried my drush commands using that alias. "drush @loc.mysite.dev status". This made no difference.

My drupal install is setup like a multisite. Maybe that is an issue though I always use multisite and have no issue with this same site and drush in a vagrant box (not using Acquia Dev Desktop). I am running my drush commands from my site directory (sites/mysite.org) which is where my settings file is (sites/mysite.org/settings.php).

Here are some drush debug outputs
This is the issue after installing Acquia Dev Desktop https://gist.github.com/maestrojed/78ff27cfae1f65821ce8
This is the issue after installing Acquia Dev Desktop AND my attempts to get drush to use the correct Acquia Dev Desktop versions of Drush and PHP. https://gist.github.com/maestrojed/45c1635f5d1d88d4bd9e

I have to use Acquia Dev Desktop and I don't think I can live without drush. I am happy to provide any other info to help debug. Any tips are greatly appreciated! Thanks.
- See more at: https://forums.acquia.com/acquia-products-and-services/dev-desktop/cant-get-drush-work#sthash.bZJBgcc0.dpuf

Use the console coming with ADD - launch the console from the ADD client. Using that console everything is correct setup. You might of course get everything to work inside your "Bash" (which it think you are using since you talk about the "which" command), but it kind of removes the whole point of using ADD - that everything is working out the box.

PS! I use Git Bash for my Git work and the ADD (cmd) console for Drush work. Then I don't have to think ;-)


Add a custom line item type with custom fields when my module is active I'm developing a module that adds on to Drupal Commerce that requires a custom line item type (LIT) along with additional fields on the LIT. With this hook I can add the LIT.

function package_designer_commerce_line_item_type_info_alter(&$line_item_types) {
     $lineItemType = array
    (
        'name' => "new product line item type",
        'description' => "A customized product line item type",
        'product' => true,
        'add_form_submit_value' => "Add product",
        'base' => "commerce_product_line_item"
    );
    $line_item_types['new_product_line_item_type'] = $lineItemType;

}

And it appears in the LIT list under the configuration menu. But when I click on Manage Fields it doesn't have the same list of as the regular commerce line item type, which is what I thought the base entry was meant to do. That is secondary though to my actual problem.

I want my LIT to have a specific field attached to it without having to provide instructions on how to go through the admin interface and create it. This might mean that instead of using that hook I need to use the .install file but I'm new to Drupal and would like to start with the recommended method instead of developing bad habits.

Update

It turns out base doesn't do what I thought it did. It only sets the line item up for using the default callbacks that start with 'commerce_product_line_item_type'. To actually make my LIT have the same base fields as the commerce product one I need to add this to my module

function package_designer_enable() {
    commerce_product_line_item_configuration(array('type'=>'new_product_line_item_type'));
}

As stated by @pcambra, the hook to define custom line items is hook_commerce_line_item_type_info.

The base key is used to build the name of some callback functions. If not specified, it defaults to the line item type name.

One of the possible callbacks is "configuration", and it is invoked when the line item is first detected by Commerce. In this callback is where you should create the fields/instances related to your line item type. Commerce already does it in commerce_product_reference module. See commerce_product_reference_commerce_line_item_type_info and commerce_product_line_item_configuration for reference.

Also, you can consult this blog post for some tricks to ease the creation of fields/instances.


When should I use methods, get() and magic offset There are three different ways to get an entity value, for example the node content type.

$node->type->value
$node->getType()
$node->get('type')

Which one should I use?

If there is a specific method - as for $node->getType() - I'd recommend using this one. Obviously that's never the case for dynamic stuff like fields - for that $node->type->value would be the recommendation.

Edit: $node->get('type') is just a more verbose variant of $node->type - both get you the "type" field object.


How to implement revisioning in my own module? In my module I store some node related data in a specific table of the database. Now I want to implement the revisioning system, so I create my_table_revision with the same information and a new column called revision_id.

But, How can I know when a new revsion of the node is created? and how can I know when a node revision is reverted?

It exists something like hook_revert() or hook_revision?

As Clive says, you need to create a custom entity (with the API) to hold the data. Then Drupal will create the necessary tables and take care of the versioning for you.

If you need to do special things (that is not already done by Drupal's built-in versioning), you can intercept both saving of new revisions and reversals with hook_entity_update.

AFAIK, there is no simple way to tell a new revision apart from a reversal.  Technically, a reversal results in a new revision with a new version ID (vid) being created, where the content of the new revision just happens to be identical to some old revision.

If it is really important for you to tell them apart, I guess you could keep a table with SHA2 (or MD5) hash signature for each revision, and look up the signature in that table to identify a reversal.

For the sake of completeness, I'll also mention that I've observed than when someone do a reversal, a log message is generated and placed in {node_revision.log} (E.g. "Copy of the revision from Thu, 2014-06-19 13:53.". Otherwise, this field is filled in with a user-written change notice (or left blank). You may be able to use this to detect reversals, but IMHO this method is not reliable as the string can easily be spoofed by a user who knows about this.


Error while registering When I register as a new user I get an error.

An illegal choice has been detected. Please contact the site administrator.

If I reenter my password fields, and press create new account then it lets me register. Ideas?

An illegal choice typically means that the Form API received something it didn't expect when the form was processed. As Stan Ascher says, make sure you don't have modules enabled which modify the login process. You can tell if there are functions which end in _user or _form_alter in those modules.


Can't get Jcarousel to work, followed the instructions This what I have done:

Get Jcarousel module and install.
Got Jcarousel Pluggin zipped files
Created sites/all/libraries/jquery.jcarousel folder
Moved the content of the downloaded folder into the sites/all/libraries/jquery.jcarousel     folder

Now this is where there is a problem:

  When this is done there should be a file
  sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js or
  jquery.jcarousel.min.js

There is no such file there. Where do I get those files? I've tried to copy and paste the files from folder:

sites\all\libraries\jquery.jcarousel\dist

Not working.

What am I missing? Where do I get the files :

jquery.jcarousel.js

jquery.jcarousel.min.js

I have installed Jcarousel module and it works. The directory in the libraries folder is like this

and it works. I downloaded the module's library from

  https://github.com/jsor/jcarousel

and Those files are under dist and src directory


Use a view to show multiple content types, but only show a field if it belongs to specific content type I was wondering if the following was possible:

content type A and B have field X
create a view to show nodes of content type A and B
show only field X for nodes of content type B?

Yes, i'm pretty sure you could use a module like Display Suite to make a custom view_mode for content type B. You could only use this view_mode in your View to show everything but field A from Content Type B.

Note, there are other modules that let you define custom display modes as well -- DS is not the only solution.


How to automatically deliver Drupal 7's static contents using CDNs? I use "Rackspace Cloud Files" service as my CDN (Content Delivery Network). This service provides nice API for many CDN-related automation. Please, help me to integrate Drupal with Rackspace Cloud Files. I even don't want to copy static contents to CDN manually.

Easy

Copy the static files to your CDN (Rackspace cloud files in this case)
Install http://drupal.org/project/cdn (drupal 7 requires no core patch)
Configure the CDN module

Update

You can automate the delivery of content files with the File Conveyor mode, this module integrates with the File Conveyor daemon. This allows for much more advanced setups: files can be processed (e.g. optimize images like smush.it, minify CSS with YUI Compressor, minify JS with YUI compressor or Google Closure Compiler, before they are synced and your CDN doesn't have to support Origin Pull, any push method is fine (supported transfer protocols: FTP, Amazon S3, Rackspace CloudFiles). File Conveyor is flexible enough to be used with any CDN, thus it enables you to avoid vendor lock-in.


How to find the list of 'paths' on my site? I recently became the administrator of a Drupal site. I am attempting to configure various blocks on the page, and have so far only succeeded in removing them altogether. The configuration menu tells me to enter the 'path' for where I want the block to appear. How do I find the list of path names available for entry? The site has a blog, but entering "blog" or even "blog/*" did not make the block appear on the block.

To get all the paths you can use, you can use the following code to get all the paths defined from modules:

$items = module_invoke_all('menu');
drupal_alter('menu', $items);
foreach ($items as $path => $info) {
  print preg_replace('/%([a-z0-9_]*)/i', '*', $path);
}

The code will show the path as you enter in the block settings; this means it will change node/%node in node/*, and node/%node/edit in node/*/edit.

About your specific issue, the block could not appear because the block has not been assigned to any theme section, the theme doesn't define the section where the block should appear, or the block is empty. In most cases, modules don't output empty blocks.


In Drupal 8 how do I get the image path from a twig node template? I'm working with Drupal 8 and twig

I created a Drupal content type called hero. It contains a title, body copy and an image. I'm overwriting node.html.twig for this content type but am having trouble accessing the image source to generate html I need to.

              Headline

              Subhead Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex, sed voluptatum fugit ipsa animi quos nobis?

I can access the Headline and title with the code below but I don't want to load the image file I want only want the image path (source).

{{ content.body }}
{{ content.field_headline }}
{{ content.field_hero_image }}

How do I get the image file path from in my node template from
{{ content.field_hero_image }}? How do I access the attributes of content.field_hero_image?

I've looked at image.html.twig and see

So I know it's in the attributes, but don't know how to access the attributes from the node template.

Ok, after writing this question a similar one showed up and I think I found the solution:

{{ file_url(node.field_hero_image.entity.fileuri) }}


Custom form with custom submit I'm building a custom form that will show some details from a web service.

On my page callback I have two fields and submit button:

<?php

$form['starting_date'] = array(
   '#type' => 'date_popup',
   '#title' => 'Starting date',
   '#date_format' => 'd.m.Y',
);

$form['end_date'] = array(
   '#type' => 'date_popup',
   '#title' => 'End date',
   '#date_format' => 'd.m.Y',
);

$form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Check'),
   '#submit' => array('reports_list'),
);

On

<?php
function reports_list($form, &$form_state) {

}

I'm inserting the code that connects with the web service, passing the form_state values of selected dates and after that I'm trying to display the table with the web service details on the same page, but after clicking on submit it simply refresh the page and doesn't show anything.

I can see connecting with the web service is successful.

On custom submit function this for an example is not displaying:

<?php

$form['results'] = array(
   '#type' => 'markup',
   '#markup' => '
TEST
',
);

I'm doing something wrong, I guess...

EDIT: I've tried to display something in the submit function like this:

<?php

$form['results'] = array(
   '#type' => 'markup',
   'markup' => 'TEST10',
);

echo render($form['results']);

It's not working.

I think your problem is due to a misunderstanding of how Drupal forms work.

Drupal uses the PRG pattern for form submissions. That means for you, that you can't set form elements in the submit handler.

You can either set a message using drupal_set_message() which will be displayed on the next page.

Or you can instruct the form to rebuild, which will result in a redirect to the same form page that you came from with your form builder being called again. In the form builder function you can then check if the form has previously been submitted and then build the form accordingly. This second option is usually referred to as a multistep form. Have a look at this blog post for an example: http://davidsonj.com/blog/how-create-multi-step-form-drupal-7


Strange behavior with flexslider: Uncaught TypeError: $(...).flexslider is not a function When I logged into a dev version of my site flexslider was broken. Rather than a slide show, I have the slideshow images repeating down the page in a single column . I get a js error in the console that reads Uncaught TypeError: $(...).flexslider is not a function in the jquery.min script.

I'm baffled because I don't recall changing anything, and another dev version of the site doesn't have the issue. The only thing I've done recently is zip the sites folder to move it to a test server which doesn't exhibit the issue.

From googling this is a jquery issue, but I'm at a loss to diagnose how to fix this.

Any help appreciated

EDIT: Not an issue of jquery versioning. Both versions of the dev site (on my local machine) and the live site are all using jquery version 1.5.

EDIT 2: Noticed an issue with my drupal install, specifically flexslider library wasn't there. So, I copied the library to the libraries folder, flushed caches, and still nothing.

Try this: Install jQuery Update module. Seems like your jQuery version is out of date.


How to create a table without uninstalling and reinstalling the module? I have a module and an installation file that is used to create a table.

According to my requirement, I need to add an another table in the same install file. I know that by using hook_schema() we can create n number of tables.
But we need to uninstall and reinstall again to create the tables. If I use this, my existing data will be lost, so I am not supposed to do this.

Is there any way to create a table without uninstalling and reinstalling the module?

This link answered my question: Updating tables: hook_update_N() functions.

For example:

In Drupal 7:

<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}
?>

and in Drupal 6:

<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_6101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  $ret = array();
  db_create_table($ret, 'mytable2', $schema['mytable2']);
  return $ret;
}
?>


My Feature depends on a module. Do I have to specify that module's dependency, as well? My Feature depends on Views. Views has a dependency on Ctools. Do I have to specify Ctools as a dependency in my feature as well.

If you use ctools calls in your module, then you should declare it as a dependency. Otherwise no need.


How to delete all nodes referencing a given one? I'm working on a catalog based on Drupal Commerce. I have a product display content type referencing product entities. I'm thinking about the ways to make life of a content manager easier.

I made a rule which fires when product is created and creates a corresponding Product display. But I can't figure out the best way to delete a product display nodes when the product is deleted.

Till now I've tried VBO, but seems in Drupal 7 rules2 lacks the ability to run VBO actions.

I guess a quick and dirty solution is to write a module for this task, but I'm looking for something more elegant. Any ideas?

I think a "quick and dirty" module would be the more elegant way. I did something similar recently in drupal 6 with ubercart. I have a content type that sometimes needs to be associated with a product and sometimes doesn't. When one of the custom nodes is deleted, if it has a product associated with it, that needs to be removed as well:

your_module_nodeapi(&$node, $op) {
  if($op == 'delete') {
    $product_nid = db_result(db_query('SELECT nid FROM {content_type_product} WHERE field_product_list = %d', $node->nid));
    if(!empty($product_nid)) {
      node_delete($product_nid);
    }
  }
}

In this case, field_product_list was a node reference field added to the product. I'm sure something similar would work in your case.


How to use a contextual filter value in a menu displayed on the same page I use a view to display a list of books sorted by title. The view has a contextual filter to limit the list by topic. So, a link to the view might be /books-by-title/34 where 34 is the taxonomy term id for "self-help". The result is a list of self-help books in title order. Works great.

The user may also want to view the same books in popularity order, so I include a menu in the view header, one choice being "By Popularity". The menu link needs to be /books-by-popularity/34.

How do I pass the term id (34) from the URL into the menu link?

Seems like this should be easy, but after reading a dozen articles and trying several approaches, no success.

I should note that a given book be assigned more than one topic. For example, a "self-help" book may also be classified as being about "exercise". So I can't get the term id simply by looking at the topic field of the book.

Something about the answer by @No Sssweat got me thinking, so I searched differently and discovered that arguments.field_topic_target_id contains the value from the contextual filter. So, the answer is to my question is to use:

/books-by-popularity/{{ arguments.field_topic_target_id }}

as the Popularity link in the menu. Credit to @No Sssweat for providing the spark!


Get rid of absolut links / redirects I just got a project from a friend:
D6, 6.34, 3 languages.
Theme: Sharp Sales (via Fusion via Topnotch)
So quite an ancient project and I first installed a local copy, but I can't login - it keeps on forwarding me to the live server.
I deleted the rewrites in .htacces, deleted cache, watchdog, access_log tables and I searched for redirects in the database, but it seems to come from the theme somehow:

INSERT INTO `cache` VALUES ('theme_registry:tnt_sharpsales_6',
...
:\"skinr_preprocess\";}}s:23:\"link_formatter_absolute\";a:8:{s:9:\"arguments\";a:1:{s:7:\"element\";N;}s:4:\"file\";s:14:\"link.theme.inc\";s:4:\"type\";s:6:\"module\";s:10:\"theme path\";s:22

and I found sth in the template.php as well:

* @param $options
 *   An associative array that contains the following other arrays and values
 *     @param $attributes
 *       An associative array of HTML attributes to apply to the anchor tag.
 *     @param $query
 *       A query string to append to the link.
 *     @param $fragment
 *       A fragment identifier (named anchor) to append to the link.
 *     @param $absolute
 *       Whether to force the output to be an absolute link (beginning with     http:).
 *       Useful for links that will be displayed outside the site, such as     in an RSS
 *       feed.
 *     @param $html
 *       Whether the title is HTML or not (plain text)
 * @return
 *   an HTML string containing a link to the given path.
 */
function tnt_sharpsales_6_themesettings_link($prefix, $suffix, $text,         $path, $options) {
  return $prefix . (($text) ? l($text, $path, $options) : '') . $suffix;
}

So I installed a fresh D6 and copied the theme over, but I can't find a setting there for absolut links.
Anybody any idea how I could get rid of the absolut links?

Finally figured it out:
Issue derived from the language negotiation settings.
Under: admin/settings/language/configure Domain name only was configured and I switched it in the database (manually updated the variables table):

UPDATE `dinilu6`.`variable` SET `value` = 's:1:"2";' WHERE `variable`.`name` = 'language_negotiation';

Afterwards I needed to clear the cach with drush cc and then it finally worked.


If I install the same module in sites/all/modules vs sites/example.com/modules, which is used? I assume that example.com would use its own version of said module, but I don't know. I have the same question regarding themes.

The sites/site.com/modules will be used over anything in sites/all/modules.

There's a really good description of how it works on Acquia:

  Site-specific modules and themes

  Each site in a multi-site install contains at least a settings.php and
  a /files directory. But each multi-site directory can contain modules
  and themes too - and any modules or themes in those directories will
  only be available to that site.

  For example, imagine I have two sites, example.com and example2.com:

  /sites/all/modules/contrib contains all of the community contributed modules that I want both sites to share. For example, Views might live there.

  /sites/all/modules/custom contains all of my custom modules, written specifically for my Drupal installation.

  /sites/example2.com/themes contains any themes you want to only be available on example2.com.

  /sites/example2.com/modules contains any modules you want to only be available on example2.com.

  When Drupal looks for available themes and modules, it searches in the
  following order:

  /modules/

  /profiles/

  /sites/all/

  /sites/[sitename]/

  So, when I write my custom theme for example2.com, I can put it into
  the example2.com multi-site directory:

  /sites/example2.com/themes/chicken

  And the "Chicken" theme will only be available to users of
  example2.com. Users of example2.com will still have access to all of
  the themes in /sites/all and /themes, but example.com won't be able to
  see the "Chicken" theme at all.


How to unset _none option inside field collection? Normally, in a node form you'ld unset the _none option like so:

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    unset($form['field_name'][LANGUAGE_NONE]['#options']['_none']);
}

Why doesn't this work in a field collection? I tried:

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    $field_collection = $form['field_field_collection'][LANGUAGE_NONE];
    $delta = 0;
    $max_delta = $field_collection['#max_delta'];
    while ($delta <= $max_delta) {
        unset($field_collection[$delta]['field_name'][LANGUAGE_NONE]['#options']['_none']);
        $delta++;
    }
}

In dpm() the option is unset and doesn't appear anymore. But on the screen it's still there... What to do?

You're modifying a local variable. You need

$field_collection = &$form['field_field_collection'][LANGUAGE_NONE];

or

unset($form['field_field_collection'][LANGUAGE_NONE][$delta]['field_name'][LANGUAGE_NONE]['#options']['_none']);


Where to add Drupal.t function in a javascript Hi I have a string in a string that needs to be translated. What needs to be added to this line to get it done?

  $(language).find('.content').append("
Next step
");  // add next steps to demo voice list

$(language).find('.content').append("
" + Drupal.t('Next step') + "
");  // add next steps to demo voice list


Exporting a feature to a specific directory using drush I am creating a new feature using drush. I looked up the component I want to create the feature with. When I run the command drush fe my_feature views_view:my_cool_view, drush wants to put it in sites/all/modules. How do I tell drush to export my feature to sites/all/modules/custom?

Use the command drush fe my_feature views_view:my_cool_view --destination=sites/all/modules/custom

https://drushcommands.com/drush-7x/features/features-export/
http://dirtystylus.com/2016/02/18/setting-a-destination-directory-for-drush-features-export/

Bonus: To change the name of the feature, and other info, edit the name= section of: sites/all/modules/custom/my_feature/my_feature.info


print image as a background-image The page.tpl.php prints the header image like so. I need to change it so that it prints it as a background image. i.e

  When I make that change the value of $url changes and includes additional text, not just the path to the image as it does in this format. How can I change this?

if ($node->field_header_image && $node->field_header_image['und'][0]['uri']) {
        $url = file_create_url($node->field_header_image['und'][0]['uri']);
        echo '';

You are retrieving the absolute url of the file correctly, but your quotes in style attribute are a little mixed up.

Try this:

<?php
print '

';
?>


What happened to the links to import or export a View? In Drupal version 7, within the overview of all Views available in a site (located at "admin/structure/views"), for each view there are these options (links) at the very right after each view:

Enable (if view is disabled) or Disable (if view enabled).
Edit.
Delete.
Clone.
Export.

And near the top there is also an "import" link.

However, in Drupal version 8, on the equivalent page (also at "admin/structure/views"), there is no more link like export or import.

So what happened to importing/exporting of a view in D8?

That Views import/export facility is no longer available in Drupal version 8 (within "admin/structure/views") ...

A possible way to do similar Views imports/exports in Drupal version 8 is to use the new configuration management facilities, which can typically be used to migrate configuration items, such as Views, between related dev, staging and production sites.

So it appears to me that as of right now (8.0.5) there is no "easy" way (as it used to be in Drupal version 7) to do such imports/exports between 2 sites that are not "related". Except probably/maybe with some special manual editing to make the site Ids match somehow.

Though according to Berdir's comment below (excl. some typos), "that's not true. You can use single import/export of any configuration file between any site, as long as you take care of the dependencies as well. The related site/UUID checks only apply to a whole config sync.". And followed by the /admin/config/development/configuration/single/import suggestion (merci Berdir).

Maybe an opportunity for a new D8 contributed module to bring this import/export facility back ... and/or one of the "reasons to be" for the Features module in D8 (as suggested in another comment by Danny Englander) (merci Danny).

PS: For some more info about /admin/config/development/configuration/single/import mentioned above, refer to the Community documentation about "Managing configuration in Drupal 8". Part of what is included on that page is like so (bold markup added here):

  It is possible to export a single configuration file and paste it into another environment. The single import option lets you specify the type of the configuration file and import it from your copy-pasted value.

Though nowhere on that page I could find an indication if using "environments" for which site Ids are different (for "single" imports) is allowed or not.

If you want to get an idea of how it is like to use these import/export features, then have a look at the slideshow "The Magic of Drupal 8’s Configuration Management on a Managed Workflow" (especially slides like on page 44 to 48).


Assigned block system to an invalid region I've renamed a region in my .info file by mistake.
After clearing the cache with drush, the block I've attached to that region was disabled.
Drush printed the following message:

The block Nivo Slider was assigned to the invalid region slider and has been disabled.

I corrected the false region, but still the block seems to be "disabled" somehow, see picture from structure -> blocks, below.

Already enabled/disabled Nivo Slider Module, cleared cache with drush.

I can't explain why, but if somebody does the same by mistake and assigns a invalid region to the block. The following did the job for me.
Just delete the entire region and add the block to another region. Clearh the cache and afterwards setup the region you had before again and assign the block to it.


How to print number of blocks in a region in Drupal 6 I use Drupal 6 and I'm trying to get number of blocks in a region. How is that possible?

The following query returns the number of blocks in the left region of the current theme.
Replace left with your region name.

$current_theme = variable_get('theme_default', '');
$number_of_blocks = db_result(db_query("SELECT COUNT(*) FROM {blocks} WHERE theme='%s' AND region='%s'", $current_theme, 'left'));