What is the skeleton structure for a Drupal 7 module? What are the files necessary for building a Drupal 7 module?  What are the requirements for constructing a basic .info file? The essence of this question is to provide a skeleton for building a basic Drupal 7 module from scratch.

Minimum files needed:

Normally, the minimum files needed for a module is the following:

sites/all/modules/{name of your module}

{your module}.info
{your module}.module

Or use the examples module:

The examples module on drupal.org provides you skeleton modules to develop custom/contrib modules. Just use that to copy and create your modules off of.

Check out the project page:

  This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.

  (Interested in other, non-core examples?)

  Developers can learn how to use a particular API quickly by
  experimenting with the examples, and adapt them for their own use.

Link to the git repository: http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x

Code from the examples module:

I've also just pasted in the code you could get from the examples module.

example.info file:

name = Examples For Developers
description = A variety of example code for you to learn from and hack upon.
package = Example modules
core = 7.x

example.module file:

<?php

/**
 * @file
 * This file serves as a stub file for the many Examples modules in the
 * @link http://drupal.org/project/examples Examples for Developers Project @endlink
 * which you can download and experiment with.
 *
 * One might say that examples.module is an example of documentation. However,
 * note that the example submodules define many doxygen groups, which may or
 * may not be a good strategy for other modules.
 */

/**
 * @defgroup examples Examples
 * @{
 * Well-documented API examples for a broad range of Drupal 7 core functionality.
 *
 * Developers can learn how to use a particular API quickly by experimenting
 * with the examples, and adapt them for their own use.
 *
 * Download the Examples for Developers Project (and participate with
 * submissions, bug reports, patches, and documentation) at
 * http://drupal.org/project/examples
 */

/**
 * Implements hook_help().
 */
function examples_help($path, $arg) {
  // re: http://drupal.org/node/767204
  // 5. We need a master group (Examples) that will be in a main
  // examples.module.
  // The examples.module should be mostly doxy comments that point to the other
  // examples.  It will also have a hook_help() explaining its purpose and how
  // to access the other examples.
}

/**
 * @} End of 'defgroup examples'.
 */


Select an image from a list to an image field I'd like to achieve the following:

When the user creates new content, instead of uploading an image to an image field every time, I would like to make an opportunity for the user to select from 8 pre-uploaded images and if none of those are appropriate, allow her/him to upload a custom image as well.

Is there any way I can achieve this with contrib modules?

Thank you.

You can try "IMCE for File Field" module for this: https://www.drupal.org/project/imce_filefield

It depends on IMCE module. Gives the option to select a file from the predefined location instead of uploading.


Why my theme suddenly gone blue after an update? After updating the Bartik 960 template on Drupal the homepage highlight each of the blocks on the page in blue. It looks like it's gone into a debugging mode, but I'm not sure how to fix it.

Check the css with your browser's inspector and see what elements are surrounding this behavior.  Is this occurring for all users (admin to anonymous)?

Does this happen in all regions or just the "highlight" region?


Show only login page to guests When ever user comes to my website he should be greeted by a pop up or normal login page only. When he logs in whole website should open up to him. SO how do i do this ?

Two separate Panels everywhere variants, one with a selection rule "User is anonymous", the other with "User is authenticated", could accomplish this.


Couldn't create range_filter for search index(commerce price) I'v a Search Api indexing server, I've added an index for price on it, and I want to create a price range filter on my created view.
I've added the price to the CONTEXTUAL FILTERS on my created view, but when i go to the contextual_range_filter configuration page (admin/config/content/contextual-range-filter), I couldn't see the indexed price field, so I couldn't use the contextual_range_filter.

Note : I need to use Contextual Range Filter module to be able to use the filters with services.

How to make it work by default?

There is an opened issue for the module contextual_range_filter with search_api and the patch patch-contextual-range-filter-search-api.txt will make the range filter work with views based on search api though you could use it for a resource for services.

Another way of achieving that scenario is to use search_api_ranges but it won't be controlled by services module.

Hope that helps with your case.


How to copy data from Profile2 form to a new node using Rules. I'll try to explain what I need to achieve:

User submits profile data during the registration proces (using Profile2 module).
Rules trigger event "After saving a new user account" that creates a new node, and then copies Profile 2 data fields to a new node.

Any ideas how can I get this working? Guess I need to use Action "Create a new entity" but not sure how can I pull data from Profile 2 and then save it to a new node?

Thanks a bunch!

Why do you want this through Rules?..according to me a simple submit handler, grabbing the data on submit and creating a node programatically will be a much better approach. I can provide you direction on this if you let me know you want to go with this approach.

Update:

Here is my suggested workflow:

Use hook_user_save() to grab the submitted profile field values. All the profiles2 field you add, will be available in the user object.
Next in the content type you want to save the values, create proper fields so that you can map and store data.
you can look up in google to see how you can progmatically create a node. So you can grab the required values, and map them to appropriate fields you added to the node and then save the node.

Just a thought, I am really curious why are you trying to do this?


Print #field_suffix with drupal_render($form['field_custom_text_field']) I have a custom module that defines a field_suffix for a custom text field

function custom_check_form_user_register_form_alter(&$form){
$form['field_url']['und'][0]['#field_suffix']='text goes here';
}

I then am calling the field in a user-register.tpl.php as

print drupal_render($form['field_reg_site_url']);

However, the #field_suffix isn't printing (checked that the value is in the array - yes). It does work (same code pattern) for username. Any ideas what I'm missing?

Try

$form['field_url']['#field_suffix']='text goes here';

Also, in your example, the suffix is being set on field_url but you are printing field_reg_site_url. That could be causing some confusion.


How to display 9 products WITH images on one page I've managed to add products and even create a "Store" node that gives me a dropdown of my CDs. BUT, I have yet to figure out how to display all 9 products on that "store" node or, at the very least, have each product show a thumbnail image so that it's not just a plain dropdown menu.

In addition, I followed another tutorial that instructed me to create add content using the "Display" content type I created but this still only shows one product. {http://drupal.stackexchange.com/questions/1849/how-do-i-display-my-products

Please help.

…Drupal Newbie…

A Node is not a "Store", it's a Product display, meaning that it displays a group of Products that belong together (like t-shirts in different colors/sizes).

To have 9 separate products displayed on a page, you create 9 nodes and assign a product to each of them. Then you can for example build a view that lists them on a single page.


After selecting "My billing information is the same...." an Edit button is shown QQ - When registered user goes through their cart to their payment information the "My billing information is the same as my shipping information. - Optional" is shown as default checked.
When they uncheck this box an Edit button appears. Is there any way to stop the edit button from appearing and simply show the fields? This happens when the user has NO address stored. So it's not very intuitive what the next step is.

In the CSS, on a working site I notice id="shipping-information-wrapper"
On my broken site, that div is not on the page. Instead, this is provided:
<div data-drupal-selector="edit-shipping-information-shipping-profile" id="edit-shipping-information-shipping-profile" class="js-form-wrapper form-wrapper">

Figured it out - The commerce Autosku module had a bug which is fixed here:
https://www.drupal.org/project/commerce/issues/3086575
I decided to remove it entirely though as it doesn't work as well in D8 as it did in D7.


menus as a block in drupal7 i have created a navigation menu  like

home, services, about us, so on and then contact us .. each parent has many child and their own child . it was created sucessfully.

Now what i want to show  menu navigation on left side bar expect home and contact us .  but all menu is display as a header too.

i want to show only parent item. when i click on parent then it's child automatically open.

Is there is any module for this. Or their is any other way to achieve this

Thanks a lot

Have you tried Dhtml Menu?

  Ordinarily in Drupal, in order to see the sub-items in a menu, you
  need to click the link of this item and wait for a full page load.
  After enabling DHTML Menu, clicking a menu link once will expand it to
  reveal its sub-items without reloading the page. A double-click on the
  item will load the page normally. Additionally, a cookie stores which
  menus are open and which are closed, so that the state of the menus
  remain consistent as you navigate around the site.


Trying to use EntityFieldQuery to find all nodes with a node reference field not set After some searching the closest code snippet I've found is:

->fieldCondition('field_name_ref', 'nid', 'NULL', '!=');

This will find everything where the node reference is not null. But if I change the != to = it returns nothing. I've tried all the combinations of values I can think of:

Passing in NULL instead of 'NULL'.
Passing in array()
Trying 1, "<"
"", "CONTAINS"
"", "="
0, "="

Plus a few more, just trying all the combinations I can think of.

How can I pull this off?

As crazy as it might sound, you can't. Normally you'd use the IS NULL operator to do this but it is apparently not supported by EntityFieldQuery:

EntityFieldQuery does not support isNull or isNotNull

Also I think the EntityFieldQuery internally uses INNER JOIN, rather than LEFT JOIN so records that don't have a value in your condition table would be excluded from the query results anyway. The issue has been reported several times:

EntityFieldQuery doesn't support query for entities without a value for a specific field
EntityFieldQuery doesn't support query for entities without a value for a specific field (duplicate)
In field_sql_storage_field_storage_query, any condition on a field's column excludes entities with a NULL value for this column


Notify user if they are about to delete a node that is referenced by another node Is there a way to notify a user when they are about to delete a node that is linked to by another node?

I'm working on a site where many of the pages reference another and I would like to put some mechanism in place where the user is notified before taking action.

If the node has an entity reference you can use the Rules module.


Is there a way to show different Amazon affiliate link based on visitor locations? I'm trying to get an Amazon affiliate link set up that directs the visitor to their local store, rather than being fixed to one particular store. I know I could set up individual links for each country and let the user choose the right one, but ideally I only want to show the one Amazon link.

Essentially what I'm looking for is a Drupal version of this Amazon Affiliate Link Localizer Wordpress plugin, or a combination of modules/tweaks that will let me do the same thing.

I wrote that plugin, so should be able to help!

There is a Javascript-only version of the Amazon Link Localiser. I don't know Drupal, but I can't see any reason why you wouldn't be able to use this - you'd just insert the JavaScript link into your template.

Cheers

Pete


How to display search results in admin theme? I want to start using the search function in my admin area. I googled quite a lot, but i couldn't find away to display the search results in the admin theme. Anyone any idea's how to accomplish this?

At the code level you can use hook_admin_paths(), e.g.

function MYMODULE_admin_paths() {
  return array(
    'search/*',
  );
}

Or if you'd rather use a non-code solution, you could install a module like ThemeKey

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.


Why (or how) order number increases in Drupal Commerce Does anyone know how the Order number increases in Drupal Commerce?

Obviously when someone puts in a new order the order number will be AT LEAST one larger than the previous order number, but other than that why would the order number increase?

For example while testing the site my first order # is 1 (duh), but then 19 days later when I tested it the order # was 19, without any other tests occurring in the interim. The following day I did a test transaction and the order # became 31.

It keeps going up every time I test it but it doesn't just increment by one every time. So I'm just curious why it might be behaving this way. Anyone know?

If you are certain there are no other users that have access to the order process, it might be caused by abandoned carts or failing payments.

Best is to have a look at example.com/admin/commerce/orders. It should give you a full list of all orders and the states they are in. Like I said if these were abandoned carts or half completed payments, orders might remain in a certain state, in which they are invisible in some other UI pages.

To answer your question. The Drupal Commerce order id is an auto increment field just as any other ID in Drupal, and it should increase with your auto increment value (mostly 1, though I sometimes have heard 5 as well).


Why the meta-tag module add "|" after the site name? I am building a Drupal 7 site using the Metatag module.

I know that on the settings of the module there are many tokens, and that's great.

For example, the title under 'Global -> page title' is: "[current-page:title] | [site:name]".

Here it's great and I like that the "|" between the words.

But, When I am on my home page, I see that my site name the browser tab is

  Site Name |

In all the metatag settings, and in the site information settings I didn't found any token that looks like "[site:name] |".

Does someone knows why my site name is "Site Name | "?

So by default, the module sets up all pages to use "[current-page:title] | [site:name]" and then for the front page it uses "[site:name] | [site:slogan]".

Now I am assuming you do not have a slogan set for your site, which is why it appears like "Sitename | ".

If you navigate to admin>configuration>site information, you will probably see the site slogan box is empty.

So you have a few options..

Add a slogan to your site
change the tokens for the front page.

to change the tokens for the front page, go the the Metatag config page and expand the "Global: Front page" field. You may need to click override to configure it to something other than default.

Click edit to edit the Global Front Page settings. Then remove the token you dont need and the seperator "|".

Hope that helps.


How to use Interface Translation for specific text on specific pages only I need to translate certain text in a twig template to one of several languages, depending on the Language selected for the node being displayed. I've installed the Interface Translation module (without translation files because I don't want the interface translated) and added custom translations for the text I want translated. This works perfectly using {{ "text to translate"|t }} in the template.

Here's the problem: When I'm at a page like "/es/node/50" (Spanish), Drupal "shifts to /es mode" by adding /es to menu entries, admin links, etc. I assume this is expected, but I don't want it. I simply want to use Drupal's built-in translation capability (via |t) to translate things I specify. I don't want any other pages to get an /es prefix.

I want to select a language for a node and then have translation capacity for that node's template only, without affecting anything else in the site.

Is this simply outside the use case for the Interface Translation module? Or is there a combination of modules/settings to make it possible?

I've fiddled with this for hours (days) and have read documentation and many posts without success.

Drupal has very advanced Multi-lingual capabilities, so it's safe to assume that you can configure your site according to your needs. You just have to learn a bit about Drupal multilingual fundamentals and see how your needs fit in there.

It seems your question is about how languages are selected and displayed, and not about Interface translation. You probably already understand the difference between content and interface, and that the strings you put into the templates are part of the interface. And you probably want to be able to view content in different languages while keeping the interface language the same.

Under Configuration > Regional and language > Languages > Detection and selection you can choose to set that your Content language selection should work differently from the Interface language selection.

Enable that option Customize Content language detection to differ from Interface text language detection settings and then also enable the Content language Detection method (Determines the content language from a request parameter.) and it should be ordered to be your first enabled method.

This way you will be able to view Spanish nodes while keeping the English interface. This is happening through the parameter that is being added to the URL. Instead of:

/es/node/50

you will have:

/node/50?language_content_entity=es

With interface language kept as English, your menus and other links will lead to the English side of things, but you will be able to view translated content.


Calculate Audio file duration I am using Drupal url field in which I input any external url of an MP3 file hosted on Twilio Server and I then use html5 audio tag to render it as an audio file in node display. Everything looks fine until my client asked me to calculate the duration of the audio and display it as a column in my views.

Is there any way I can achieve this?

Thanks!

getID3 can be used to calculate the size of the file.

$fileinfo = getID3_analyze(drupal_realpath($name2));
$playtime_sec = round($fileinfo['playtime_seconds'] / 60);

//Generate playtime in minutes (for display only), @type String
$playtime_mins = $fileinfo['playtime_string'];

use the following modules to integrate with views.
https://www.drupal.org/project/computed_field
https://www.drupal.org/project/getid3


Show field twice in node page I created a custom bundle (content type) and I've created fields

One of those field is a file type field, is a video file, stored in the private storage. I installed the videojs module to allow to watch the video.

I need to show this field twice in the node page. One in the generic file formatter that allows the user to download the file, and I also need to play the video. I decided to set up as generic file formatter and customize the twig template to show again with the video player.

I achieve to show twice with the settings formatter (generic file) with this code in the node--mybundle--full.html.twig template

{{ content.field_sd_video }}

I thought it would be something easy like field+formatter:

{{ content.field_sd_video|videojs_formatter }}

But I can't find a simple way to achieve this.

You can do this in UI, UI and code mixed, code only and in html:

Display Suite

Install the module Display Suite and configure this in UI.

Extra Field

Use the hook hook_entity_extra_field() to get an extra field in Manage Display. You need hook_ENTITY_TYPE_view() to copy the data (in this case the file) into the new field.

Clone field in code

See
How to display a field twice in a view mode?

The last has the least overhead, but is not customizable and you have to define the field settings yourself. If you configure the second field temporarily in UI and export the view mode to yaml this helps to find the settings you need in code.

Place link html in template

Or if you want a quick solution in the template and you only need a simple formatted file link you can get the file url from the node and put it in html markup:

Example Video


How to make CSS and JS both load in the footer We have a library slick_carousel in our mytheme.info.yml and mytheme.libraries.yml defined in our sub-theme (see below).

How can we make the CSS and JS both load in the footer? Currently only the JS file is showing in the footer.

Current mytheme.libraries.yml:

slick_carousel:
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css: { type: external, attributes: { async: true } }
  js:
    //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js: { type: external, minified: true  }
  dependencies:
    - core/jquery

We have tried, but didn't work. We need to do this without a module.

Removing dependency on core/jquery.
Change theme to component under css.

You can just add 'scope' option and pass either 'header' or 'footer' as the value.

slick_carousel:
  css:
    theme:
      slick.min.css: { type: external, attributes: { aysnc: true }, scope:footer }
  js:
    slick.min.js: { type: external, minified: true, scope: footer }
  dependencies:
    - core/jquery


Customizing filter criteria search of a view I've got a view with an exposed to users filter criteria ajax search. I want to customize it somehow and link a specific search phrase to a specific node.

any idea on how to do that? any way around without getting my hands dirty with coding?

use hook_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
if ($form['#id'] == 'views-exposed-form-search-page...'
$form['my_link_element'] = array('#markup' => l(t('Seacrh word taken from form_state'),'node/5'));


load balancing multiple horizontal drupal instances I've developed a REST WebAPI using the Services module. It works fine. I have a client of that API with projected usage requiring I horizontally scale my Drupal instance. Note that due to the nature of my API, requiring significant CPU and GPU resources, I can not use cloud servers. Also, due to the nature of my API, the Drupal instances have to run on Windows OS. (My application requires software only available on Win64.) I have a fairly beefy server in a co-location now, and for this ambitious client I am planning to horizontally scale my hardware in the following manner:

One CentOS server running HaProxy as the front end load balancer,
Two to start, with more added as needed, Windows Server 2008 R2
servers hosting Drupal,
One CentOS database server providing a single database for the
multiple Drupal instances,
One CentOS database server running in replication mode in case DB
server 1 dies.

My questions have to do with how the HaProxy load balancer works. I'm assuming that the sessionIds created by the Drupal instances will be unique from one another. Does the load balancer look at the sessionId and route all requests to the same server that produced that sessionId? How would a REST WebAPI communication work if load balancing caused each API request to go to a different server? Does any and all data referenced by the WebAPI have to be stored in the database because I can't insure that multiple API requests for the same resource will be routed to the same Drupal instance?

Having multiple webservers behind a load balancer/reverse proxy is quite common for Drupal and well supported. Varnish is typically used in the Linux world because that thing is just insanely fast when being able to actually use it, meaning anonymous visitors. Which is obviously not the case for your site.

Sessions are stored in the database by default, so that's not a problem. The only other thing that needs to be shared across all servers is the public files directory and any other like the private files if you're using something like that). In most cases, a shared/distributed file system like NFS is used for this although there are some more advanced approaches. On one site where I'm involved is the file system provided by yet another server that is an NFS-mount on the Drupal servers (so access there is slow) and is being distributed under a different domain by Lighthttpd. But again, that is probably not so relevant for you as you're not going to server lots of images and css files, I guess.

As mentioned by rocketeerbkw, there are cache backends for Memcache, Redis and others. So far, Ive only used Memcache but I recently started to look into Redis and it looks very promising but I'm not sure if it is available for Windows. However, it would be possible to set up a separate Linux server to be used for the cache. Drupal 7 relies heavily on caches, being able to get them off the database is very important for two reasons:

Tools like Redis and Memcache are designed for fast key based lookups and they keep their data always in memory to make the lookup as fast as possible. They have also built in support for automatically cleaning up old cache data if the configured limit gets closer.
Maybe even more important, it helps to get database load down. Once you have the basic setup in place, adding additional webservers is easy. Once you start reaching the limits of a single database server, things get much more complicated and you need to look into things like master/master replication (Drupal 7 doesn't really gain much from master/slave environments).

So, it's basically just your own API that you need to take care of. If possibly, you need to make sure that everything is always available from all servers. You can use either the databse, the file system or something else (Drupal can also use MongoDB to store certain data, e.g. fields). If that is not an option, then you will need to use sticky sessions so that users always end up on the same instance. You should however really try to avoid that because if one of the server fails then all users which were on that server need to re-connect to another server, possibly losing data.


Disable 3rdparty hook from custom module once Im using the menu_trail_by_path which does a pretty good job for most of my URL's, however in a custom module I'm setting the breadcrumbs directly (drupal_set_breadcrumb in a page callback). These crumbs get messed up due the menu_trail_by_path module (sort of overwritten I guess =/)

This happens because menu_trail_by_path sets the crumbs using hook_page_delivery_callback_alter which is called after the page callback apparently.

I would like to keep my custom crumbs in the page callback as it has all the required (dynamic) data available.

Hero we go.. how on earth can I disable the page_delivery_callback_alter hook from the menu_trail_by_path module... once? I.e. for the current runtime /request only.

Thanks!

Roland Franssen

You could implement hook_module_implements_alter() to avoid a hook implemented by a module is invoked. The problem is that Drupal saves in cache the list of modules implementing a hook, but you can change the list of hooks implemented by modules back to the original one.

function mymodule_implements_alter(&$implementations, $hook) {
  if ($your_condition && ($hook == 'page_delivery_callback_alter')) {
    $old_implementations = &drupal_static(__FUNCTION__, array());
    if (empty($old_implementations)) {
      $old_implementations = array_merge(array(), $implementations);
      unset($implementations['menu_trail_by_path']);
    }
  }
}

function mymodule_exit() {
  $old_implementations = &drupal_static('mymodule_implements_alter', array());
  $implementations = &drupal_static('module_implements');

  if (!empty($old_implementations)) {
    $implementations['page_deliver_callback_alter'] = $old_implementations;
  }
}

This code works only in the case hook_exit() is invoked, which is normally done in drupal_page_footer().

You should be sure mymodule_implements_alter() is executed after the implementations made from other modules, in order to preserve the changes done from other modules.


I am looking to export webform submissions to cck instead of typing each submission in Drupal 6? I have close to 150 submissions on my webform but had to change to content type midway , is there a simple way to export those submissions to a cck content type and map those fields instead of typing each one out.

Thank you

You could try:
First export the data to csv.

Then, import with feeds.


How to render in template file with some conditions? I want to use render function but I don't want to show all the data which is there in the particular field. So how can restrict something from rendering in template file. Scenario is:

I have reference one field to another contentype, and I am rendering field in template file. But problem is even though the referenced node is not published, that data is displaying in the rendered field. So how can I restrict like if node is published then only I want to display that data.

One more concern is if it is possible with inbuilt functions only that will be great that saves my time of writing code and designing the data.

You should be putting the business logic of deciding what you want to show (or hide) in a preprocess function in your template.php and make use of the show and hide functions to specify what you want rendered.


How to place an Ubercart order on behalf of another user? I would like to ask if it is possible to assign another UID, different from that of the currently logged in user, to an order under checkout process (e.g. via rules)?

Any idea how to do that? Thanks.

If you'd like to change ownership during checkout, probably not, or not without reworking some core UC code; there are likely to be permission problems if you switch the user owner before order completion.

Changing the ownership of a UC order is a trivial change.

$order = uc_order_load($order_id);
$order->uid = 1234;
uc_order_save($order);

But, the core Ubercart rules integration do not support a rules action that changes order ownership.  So in order to use rules you'd need to build a custom action there. Also, because aforementioned permission problems, you'd likely need to use an event that occurs when the purchasing user no longer needs to own the order.

In summary, the above code is somewhat of a starting point, but you're looking at tripping over UC's order ownership enforcement if you go down this route.


Why does updating newly added field collection on hook_field_collection_item_insert fail? The main goal is to create product & product display using drupal 7 &
drupal commerce when a user with a certain role add a new field collection.

What I'm trying to do is when a new field collection is added :

access host entity fields and retrieve some datas
do some custom stuff
update 1 value of a field collection which is a field
reference to product

Steps followed :

I'm using hook_field_collection_item_insert to access newly created field collection.
I call a function which create a product (using commerce modules suites). Above steps works just fine.
Then I call a function that update the current field collection field by adding a value which is a reference of product created in function my-module-create_product().

$fc_wrapper->save(TRUE); is failling to save with the following error :

Exception: Unable to save a field collection item without a valid reference to a host entity in FieldCollectionItemEntity->save() (line 520 of ../mysite.local/docroot/sites/all/modules/contrib/field_collection/field_collection.module)

I've done some search so far without any success.

I can't figure out the fix for this, some direction or any information that will help to solve this issue will be much appreciated.

Below a simplified code that I'm using :

function my_module_field_collection_item_insert($field_collection_item) {

    $item_id = $field_collection_item->item_id;
    //dpm($item_id);

    //Check the field collection bundle & if it's just have been created
    if ($field_collection_item->field_name == 'field_my_field_collection' && $field_collection_item->is_new == TRUE) {

        //Access host entity
        $node_wrapper = field_collection_item_get_host_entity($field_collection_item);

        //Do custom stuff with host entity fields
        //...
        //set $product_type, $price, $extras values

        //Call a function that create product
        $product = my_module_create_product($product_type, $price, $extras);

        //Product creadted
        if ($product) {

            $product_display = my_module_create_product_display($product, $item_id);

        } else {
            throw new Exception('Product creation as failed...');
        }
    }
}

//Function that create product
function my_module_create_product($product_type, $price, $extras) {
    //create product
    return $created_product;
}

//Function that create product display
function my_module_create_product_display($product, $item_id) {

    //Note that loading existing field collection here works but it not what I need
    //Loading created field collection
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $item_id);

    if ($fc_wrapper) {

        if ($fc_wrapper->field_product_ref->value() == NULL) {

            //Setting product reference
            $fc_wrapper->field_coaching_product_ref->set($product->product_id);

            //Only need to save the current field collection
            $fc_wrapper->save(TRUE);

            //I've tried bellow still don't work either
            //$fc_wrapper->save();
            return $fc_wrapper->getIdentifier();

        } else {
            //Product display already exist
            return FALSE;
        }
    } else {
        throw new Exception('Exception... ');
    }
}

You can only set the host entity while creating the field collection item (as your exception also states).

What you can do however is use $fc_wrapper->value()->updateHostEntity('node', $node); before you save the $fc_wrapper.
For that to work you will first have to load your host entity node of course (node_load() will suffice).

Hopefully this gets you on your way.


YAML Form Conditional Page Is there any option in YAML Form to create conditional page? There is already conditional fields option. But I can not find conditional page option.

What actually I want to do is to take some additional information on another page of the form if there some specific value is selected.

I was recently at the NYC Drupal meetup where the maintainer mentioned this exact feature. He said that it is on the road map, but it does not exist yet. That said, he is very open to patches :)

Incidentally, please note that the YAML form module was renamed to Webform.


Where in the MySQL database schema is the URL alias for a group relation? I am building a report outside of Drupal that pulls data from a Drupal 8 database.  The report shows titles of different nodes and I want to link those titles to the web page for that content.  This is working fine if I use the standard /node/X path, but I would like to use the URL alias.  I don't want the url alias of the node itself (which I did find thanks to this Which mysql tables contain the URL Alias path data? post).  Our content is related to groups, so I want to use the URL alias that is created as part of the group entity relation.

At first I checked the url_alias table, using this query to look for the node id in the source field, but I didn't find the alias set up for that node :

select u.alias
from url_alias u
where u.source LIKE '%4806%'

Then I tried to check the group tables.  I only find 5 tables starting with group in the MySQL schema, and I didn't find the URL alias for the entity reference in any of them:

group_content
group_content__group_roles
group_content_field_data
groups
groups_field_data

Does anyone know where that URL alias from the group relation is stored in the MySQL schema?

As Clive stated in the comment, all aliases are in the url_alias table.

You should join it with the og_membership table, to take the url alias of the node's group.

So, for a node with id 100, the script should look like:

select u.alias
from og_membership og, url_alias u
where concat('node/', og.gid) = u.source
and og.etid = 100 and og.group_type like 'node'


Same website but different logo for large screen and small device? I would like to have two different logos on the same website. One for large screen and one for small screen ( mobile devices )

I am using D8

Thank You

There are multiple ways to do this through CSS media queries. See example below.

.classname {
   @media all and (min-width: 768px) {
     background-image:url('image2.png');
   }
   @media all and (min-width: 320px) {
     background-image:url('image1.png');
   }
}

Helpful links

Responsive Images
Working with breakpoints

If you use the module and breakpoints from your theme you can probably just wrap the logo in a div class so you can control the padding or other CSS attributes. Just make sure to find the correct image styles per breakpoints and multipliers.


Adding images to the right sidebar Can anyone please tell me, using very simple terms, how to add an image to the right sidebar?

Upload image to server using FTP or via some file manager module, like IMCE, elFinder, etc.
I strongly suggest put it in somewhere inside /sites/default/files (sub)directory.
Navigate to admin/structure/block/add to start creating new block
Set empty title
For body field select format 'Full HTML' and enter code
<img src="/sites/default/files/YOUR_IMAGE_NAME.jpg" alt="IMAGE_DESCRIPTION"/>
From region selection list, select 'Sidebar second' or similar
Below you can set the details of where block will be displayed (optional)
Click 'Save' button


"Strict warning: Only variables should be passed by reference in eval()" when concatenating several text fields I am using Computed Field to concatenate a few text fields into one value. The text fields are pieces of a street address (the street address, the city, the state, and the zip code). When using the code below, I receive the error below.

COMPUTED CODE:

  $entity_field[0]['value'] =
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_address'))) . ', ' .
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_city'))) . ', ' .
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_state'))) . ' ' .
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_zip_code')));

DISPLAY CODE:

  $display_output = $entity_field_item['value'];

ERROR:

  Strict warning: Only variables should be passed by reference in eval()
  (line 1 of
  /home/mysite/public_html/sites/all/modules/computed_field/computed_field.module(468)
  : eval()'d code).

How can I resolve this issue?

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_address')));

=>

$items = array_pop(field_get_items($entity_type, $entity, 'field_address'));
$entity_field[0]['value'] = array_pop($items);

You have to store result of function in variable and pass it to another function, instead of pass function to function.

Passing by Reference


Page Navigation issue after executing a jQuery Using JSinjector, i included a jQuery and made use of a function. I wrote a query inorder to display the external link within a certain div section (within our site). My code goes here

 (function ($) {
       Drupal.behaviors.YOURTHEMENAME = {
              attach: function(context, settings) {
              $('.div-classname a').click(function(){
              var url = $(this).attr('href');
              var height = $('#div-id-name').height();
              var width = $('#div-id-name').width();
              $('#div-id-name').replaceWith( "'<object data="+url+" width="+width+" height="+height+"/>'" );
               return false;
             });
           }
         };
         })(jQuery);

In concise, the above query does the functionality - " whatever the hyperlinks within the div class (div-classname) when clicked the corresponding website opens within the div with id (as div-id-name). Previously, div-id-name region has a content but when the hyperlink is clicked, jquery executes now the content (within the div-id-name) is replaced with the corresponding site.

Everything goes well the query works..

But my problem here is after the content is replaced with the corresponding link, now when i press the back button - rather than loading the previous page or the website's home page it redirects to the browser's home page (i.e., either google.com or whatever).

What might be the problem? Is there any thing link configuration issues? or do I need to include any code (query)..

I m using Drupal 7

Disable the click function for the more links div.

$('.div-classname a').on('click',function(){.....});

$('.more-link a').off('click');

This is the perfect solution.


Creating custom bread crumb trails (Drupal 7) How would one create a custom breadcrumb such as this:

For a given page such as a node or organic group page in Drupal 7?

I don't know anything about Organic Groups, otherwise I'm using Path breadcrumbs and Custom Breadcrumbs.


Move all files and folders from a directory to another directory I am unzipping some files and folders from an upload but the zip contains the files and folders one directory too deep. So currently they are located

path-to-folder/anotherdirectory/

When I need them to be located at

path-to-folder/

I have tried using the PHP rename function but get an error stating http 'wrapper does not support renaming in...'

Does anyone know the Drupal way to do this please

Sounds like you are trying to rename files by specifying their Url. You can't do that. You have to specify the path to the file. It's a PHP issue rather than a Drupal issue. Try this instead:

rename($_SERVER['DOCUMENT_ROOT'].'/path-to-folder/anotherdirectory/filename.ext', $_SERVER['DOCUMENT_ROOT'].'/path-to-folder/filename.ext');


Show specific field(s) from created content-type Question might be easy, but I have a problem. I created a content-type (page), made it as a block with Node Block module, put this block in content. But it prints all stuff: title, authored by, date and so on. But what I nead is to print only body. But there might be another case, when I want to print also a title.

So the question is in general, how to print fields that I want from content-type,  maybe there is a module for this or a more convenient way.

I'm using latest Drupal 7.

Thanks!

You can configure this as a per content type level, not for each node in particular.

Edit the content type, go to Node Block settings and under Default view mode select a convenient value. Then, click on Manage presentation tab and select the same value you set previously under Default view mode, and finally configure the fields and positions you want to be rendered.


Dynamic default value for select list I am trying to make a reservation system for equipment in a laboratory.
People reserve equipment by creating "reservation" nodes that are tagged with the taxonomy term "Equipment".
In the "create reservation page" the referenced taxonomy field is a dropdown list.

On the other hand I have a table view with all the equipment with its corresponding taxonomy term.
I would like to have in a third column a link to the "create reservation page" and  I would like that in the "create reservation page"  the corresponding taxonomy term in the dropdown list is already selected.
Any idea how to succeed?

The Prepopulate module allows you to construct a special URL inside your table view that, when clicked, will prepopulate the correct taxonomy term on the "Create reservation page".

The special URL will looking something like this:

http://www.example.com/node/add/reservation?edit[field_equipment_term_reference]=123

You need to:

Download and install the Prepopulate Drupal module.
In your table view, add the Taxonomy Term ID field (if not already added).
In your table view, add a Global Text custom field.
In the Global Text field config screen, specify the text "create reservation page" and then expand the rewriting section, and turn the field into a link, with link destination of node/add/reservation?edit[field_equipment_term_reference]=[tid].

Please note:

the [tid] is the substitution token from the field added in step 2.
replace field_equipment_term_reference with the real machine name of the taxonomy term reference field you're using on the Reservation node.


How to get update to check Feature Server I have a custom module hosted on a feature server. When I update Drupal how can I get it to check the Feature Server to see if there is an update there?

In the back of my head I thought it was something you could add to .info. However I can't find an example.

You're looking for project status url, which is a property that can be used in your module's .info file:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.


Preferred way of adding new setting to all fields in a View? I'd like to add a new setting to all fields in Views. In other words, when you click on any given field in the "Fields" list, you get a popup with the selected field's configuration options. I would like to add a new settings element here.

If this was just about adding a new setting to a specific custom field handler, then I would just create a new field handler class and have it extend views_handler_field. Then, I'd make my setting available by first defining it in option_definition() followed by adding a new form element in options_form(). However, I'd like the new setting to appear for all fields regardless of field handler.

What I've done so far is to simply provide an implementation of hook_form_views_ui_config_item_form_submit() to add the new setting. I'm adding my custom form element here as well as my own submit handler. In the submit handler I make sure to save the setting in $form_state['handler']->options in my submit handler.

However, is that the right way to go about it? Is there another way which Views facilitates and which would let me do things a little more clean so that I do not have to "mess" with the options array in my own submit handler, but rather have Views to actually know about my added universal field setting?

I wrote the module Views Label Tooltips based on my technique to achieve this, and here's a post explaining it: http://thereisamoduleforthat.com/content/recipe-extending-views-handlers-without-subclassing


drush core-config causes 'Permission denied' When I use command as follow:

drush core-config

and then enter

1

a error displayed:

sh:/etc/php.ini: Permission denied

how to solve this problem?

You are trying to edit a system level file (ex. /etc/php5/cli/php.ini) using Drush and you don't have access to it at your current permission level. You need to login using an account with higher permissions or use sudo.


Can I hook a form from a custom module? I have a form function called mymodule_join_form in MyModule and differentmodule_form_mymodule_join_form_alter in DifferentModule. It's not being called, though (I put `echo 'hello';die;)

I can get to it using form_alter with if (form_id == 'mymodule_join_form'), but shouldn't the first way work?

if it's a form alter you should take a look at http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7

Also clear cache and look if you have enabled de módule.

Have you tray with a dpm('hello world') with devel module enabled?

oskar


How do I get the translated node type of a node? I am trying to use the node type name in page.tpl.php for certain content types.
Actually, we have modified the article type and renamed it as News. It's name is News in all languages but in Spanish, where it is Noticias.

The translations are defined under Structure>Content Type>Article.

I tried to use this code :

if(!empty($node) && $node->type == 'article'):
  print node_type_get_name($node);
endif;

but the node type is always printed as News, even on Spanish pages.

I tried wrapping this in a t() , but no change.
Am I doing something wrong here ?
Thanks for your help !

I have edited html.tpl.php

I have added this code before starting the body tag in order to replace body css classes with translated

<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>

after this modification, you can search css class name in translate page and put a suitable translation for it.

so final html.tpl.php is

<?php

/**
 * @file
 * Default theme implementation to display the basic html structure of a single
 * Drupal page.
 *
 * Variables:
 * - $css: An array of CSS files for the current page.
 * - $language: (object) The language the site is being displayed in.
 *   $language->language contains its textual representation.
 *   $language->dir contains the language direction. It will either be 'ltr' or 'rtl'.
 * - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
 * - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
 * - $head_title: A modified version of the page title, for use in the TITLE
 *   tag.
 * - $head_title_array: (array) An associative array containing the string parts
 *   that were used to generate the $head_title variable, already prepared to be
 *   output as TITLE tag. The key/value pairs may contain one or more of the
 *   following, depending on conditions:
 *   - title: The title of the current page, if any.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site, if any, and if there is no title.
 * - $head: Markup for the HEAD section (including meta tags, keyword tags, and
 *   so on).
 * - $styles: Style tags necessary to import all CSS files for the page.
 * - $scripts: Script tags necessary to load the JavaScript files and settings
 *   for the page.
 * - $page_top: Initial markup from any modules that have altered the
 *   page. This variable should always be output first, before all other dynamic
 *   content.
 * - $page: The rendered page content.
 * - $page_bottom: Final closing markup from any modules that have altered the
 *   page. This variable should always be output last, after all other dynamic
 *   content.
 * - $classes String of classes that can be used to style contextually through
 *   CSS.
 *
 * @see template_preprocess()
 * @see template_preprocess_html()
 * @see template_process()
 *
 * @ingroup themeable
 */
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

I hope my post can help you.


Add custom content to custom layout Panels Is it possible to add custom content to a custom Panels layout?

Specifically, I've created a layout with a couple of columns for a content type called 'Stuff' and I always want to add the same images in a certain column of the teaser (that means every node of the 'Stuff' content type has to contain these images). I created several custom content panes with these pictures, but I don't know how I can use them in the custom Panel layout or the content type.

Any ideas? Or is there a better way to achieve my goal?

You could place the images in a mini panel. Changes to the images would be done in the mini panel and would affect all nodes.

In Panels you can activate the Node view variant and create a panel (with a selection rule for the content type: Stuff). then use your Panel layout and place the mini panel in the column you want the images.

All nodes of the type stuff, should now use your layout with a mini panel holding your images. You can easily change the content of the mini panel and reuse it on other parts of your site.

Hope I understood your problem correct.


drupal link not working on live server after moving from localhost i have moved my drupal site from localhost to live server but all links and contents are not access able and it gives (404 Not Found error was encountered while trying to use an ErrorDocument to handle the request).

i have tried clearing all caches, session and watchdog tables
replacing all localhost links on the exported sql file with live site name
change database connection info on setting.php file
still i have no luck.

This sounds like missing .htaccess file. Check if this file exists or not. If not, upload a standard drupal htaccess file.

You can use this one maybe. https://github.com/drupal/drupal/blob/7.x/.htaccess


How to make state/provinces list dynamic on user profiles/registrations? with international addresses? I have a site with international users, and I'm using location, user locations, and Google geocoding to show their locations on a map.

I'm using the US as the default for addresses, as most of my users are US based. The issue that I have is that the state/provinces drop down doesn't update the list for a different country until after the form is saved. The effect of this is that the newly registered users has to go back into their account an update their address if it isn't in the US.

Is there anyway to make the state/provinces list dynamic? that is to have the list match the country selected while the user is registering?

One solution to this is to email the user and remind them to update their address, but this seems like back UI and laziness.

Is there some way to refresh just the location fields before the form is submitted if it cannot be dynamic?

So, I'm not sure how to approach this and any advice would be appreciated.

So, there's a patch for this. The last patch used against the 3.x dev module provided the desired results. Dynamic States list patch


Is there any alternative of node_save to update database fields in iteration? In Drupal 7, we have big product catalog where we need to update price and stock frequently via Cronjobs.

If we update only 5000 prices then also it takes around 20 min.
In each iteration we use node_load() and node_save() functions to update for each product in database.

It seems that these functions are consuming more memory and taking more execution time to just update 1/2 fields in database.
It's drupal's API, so it would be integrated to some other stuff (like node revision) so I doubt that we can simply replace node functions with direct queries.

But I think, this scenario would be common when we manage large product catalog in drupal.

Can anyone suggest better/optimized approach for this scenario where it doesn't break the integrity with drupal platform?

you can use entity module. This module proves entity_matadata_wrapper API which allows you to load and save fields of nodes. The following code is an example of altering a node's title.

$nodeWrapper = entity_metadata_wrapper('node', node_load($node->nid));
$nodeWrapper->title->set(t("Saved by Entity Save"));
$nodeWrapper->save();

entity_matadata_wrapper is not limited to nodes. As you can see in it's signature you must specify the element which in your case it is node.


Is alternative available in back end for drush migrate-import "ID"? I have been migrating the contents using the migrating source csv, tools and plus modules

As followed the instruction, I have to use the drush command drush migrate-import 'ID' to complete the migration process.

Is there any option available in backend instead of using the drush command.

We can achieve this, without using the Drush Commands

  drush migrate-import 'ID'

After the import process,

$migration = "Migration ID"
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import();

If you dont want to use Drush Commands, then Create the custom module and use this above command.


Overriding node output I'm currently creating a website on Drupal 8, even if it's still in RC3.

I've been swimming in the sauerkraut since few days now and I still cannot figure it out how to override node output as I could do in Drupal 7.
Because Drupal 8 is not as used as Drupal 7, it's tough to find answers on Google.

So, I'd like to do the following in my twig file(s):

    <?php if ($field_images) { ?>
    <?php
      $img_url = $field_images[0]['uri'];
      $img_alt = $field_images[0]['alt'];
      $img_title = $field_images[0]['title'];
    ?>

      <a data-lightbox="galleryWrapper" href="<?php print image_style_url('lightbox', $img_url); ?>">
        <img src="<?php print image_style_url('album_thumb', $img_url); ?>" alt="<?php echo $img_alt; ?>" title="<?php print $title; ?>" class="media" />

    <?php } ?>

I've seen that I could, as in Drupal 7, override a template file with a specific filename, such as: "field--node--field-images--gallery.html.twig".

The thing is that I don't know where to create my variables that will be available for my twig files (MYTHEME.theme?).

I've already tried this in "field--node--field-images--gallery.html.twig":

{% if multiple %}

    {% for item in items %}

        {#  Before was {{ item.content }} instead of the 5 following lines  #}
        {% if item.content.url %}
          {{ item.content.image }}
        {% else %}
          {{ item.content.image }}
        {% endif %}

    {% endfor %}

{% else %}
  {% for item in items %}

      {#  Before was {{ item.content }} instead of the 5 following lines  #}
      {% if item.content.url %}
        {{ item.content.image }}
      {% else %}
        {{ item.content.image }}
      {% endif %}

  {% endfor %}
{% endif %}

I've tried to access to "url" with {{ item.content.url }}, because {{ content }} seems to call "image-formatter.html.twig", which contains the following:

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

As you can imagine, it doesn't work.

And, that's another issue, but I've already tried to dump variables but I got this famous WSOD (White Screen Of Death). So, that's very difficult to know what this $variables contains.

The fields you are looking for are under '#item', for example:

 {{ item.content['#item'].title }}

To set variables for twig put a theme_preprocess_field() function in  MYTHEME.theme.

To examine variables use kint (this is in the devel module):

{{ kint() }}
{{ kint(items) }}


Ajax error on dependent dropdown. Drupal 7 I am trying to get the following dependent dropdown to work, however I constantly get the following error. So far could not figure out what the problem is. I was wondering if anyone has had a similar problem and might have the solution for it.

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path: /?q=system/ajax StatusText: OK
  ResponseText: stringstring(1) "2" array[ {"command":"settings",
  "settings":{"basePath":"\u002F", "pathPrefix":"",
  "ajaxPageState":{"theme":"bartik",
  "theme_token":"Ghiw-ikiaoP9ioC23jfb6h1vvIuA4G_nb3NBGO0mfEA"},
  "overlay":{"paths":{"admin":"node\u002F*\u002Fwebform\u000Anode\u002F*\u002Fwebform\u002F*\u000Anode\u002F*\u002Fwebform-results\u000Anode\u002F*\u002Fwebform-results\u002F*\u000Anode\u002F*\u002Fsubmission\u002F*\u000Anode\u002F*\u002Fedit\u000Anode\u002F*\u002Fdelete\u000Anode\u002F*\u002Frevisions\u000Anode\u002F*\u002Frevisions\u002F*\u002Frevert\u000Anode\u002F*\u002Frevisions\u002F*\u002Fdelete\u000Anode\u002Fadd\u000Anode\u002Fadd\u002F*\u000Aoverlay\u002Fdismiss-message\u000Auser\u002F*\u002Fshortcuts\u000Aadmin\u000Aadmin\u002F*\u000Abatch\u000Ataxonomy\u002Fterm\u002F*\u002Fedit\u000Auser\u002F*\u002Fcancel\u000Auser\u002F*\u002Fedit\u000Auser\u002F*\u002Fedit\u002F*",
  "non_admin":"admin\u002Fstructure\u002Fblock\u002Fdemo\u002F*\u000Aadmin\u002Freports\u002Fstatus\u002Fphp"},
  "pathPrefixes":[  ], "ajaxCallback":"overlay-ajax"}}, "merge":true},
  {"command":"insert", "method":null, "selector":null, "data":"\u003Cdiv
  id=\u0022second-select-box-replace\u0022\u003E\u003Cdiv
  class=\u0022form-item form-type-select
  form-item-second-select-box\u0022\u003E\u000A  \u003Clabel
  for=\u0022edit-second-select-box--2\u0022\u003EChoose
  \u003C\u002Flabel\u003E\u000A \u003Cselect
  id=\u0022edit-second-select-box--2\u0022
  name=\u0022second_select_box\u0022
  class=\u0022form-select\u0022\u003E\u003Coption
  value=\u00227\u0022\u003ECountries\u003C\u002Foption\u003E\u003Coption
  value=\u00223\u0022\u003EUniverse\u003C\u002Foption\u003E\u003C\u002Fselect\u003E\u000A\u003C\u002Fdiv\u003E\u000A\u003C\u002Fdiv\u003E",
  "settings":null}, {"command":"insert", "method":"prepend",
  "selector":null, "data":"", "settings":null} ]

Here is the code:

function form_new_term_step_two($form, &$form_state){

    $first_options = _step2_first_options_select_box();

    $selected = isset($form_state['values']['first_select_box']) ? $form_state['values']['first_select_box'] : key($first_options);
    //var_dump($selected);

    $form['first_select_box']= array(
        '#type' => 'select',
        '#title' => 'How do you categorize the term ?',
        '#options' => $first_options,
        '#default_value' => $selected,
        '#ajax' => array(
            'callback' => 'ajax_step2_select_callback',
            'wrapper' => 'second-select-box-replace',
        ),

    );

    $form['second_select_box'] = array(
    '#type' => 'select',
    '#title' => 'Choose',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => _ajax_example_get_second_dropdown_options($selected),
    '#default_value' => isset($form_state['values']['second_select_box']) ? $form_state['values']['second_select_box'] : '',
  );

    return $form;
}

/*
 * All the Submit and Callback fucntions
 */
function ajax_step2_select_callback($form, $form_state){

    return $form['second_select_box'];

}

function _ajax_example_get_second_dropdown_options($selected= Null){

    $results =  taxonomy_get_term_by_name($selected);
    $tid = array();
    foreach ($results as $objs){

        $tid = $objs->tid;

           }

    $terms = taxonomy_get_children($tid);

    foreach ($terms as $term){

        $options[$term->tid] = $term->name;

    }

    return $options;
}

You need to remove the line

'#options' => _ajax_example_get_second_dropdown_options($selected),

Then, put your function call and update the #options on some condition. So, something like this:

if(isset($form_state['values']['first_select_box'])) {
  if($form_state['values']['first_select_box'] == 'something'){
    //the contents of your _ajax_example_get_second_dropdown_options function here
    //and instead of returning something... just SET #options to your new output.
    $form['second_select_box']['#options'] = 'new stuff';
  }
}

Furthermore, most of the time people will not even show the second select box until the first one is filled out with something useful for the second. In that case, you can set the #type of the second select box to 'markup' and then in that above if statement SET the #type to select.

$form['second_select_box'] = array(
  '#type' => 'markup',
  '#prefix' => '
',
  '#suffix' => '
',
);

if(isset($form_state['values']['first_select_box'])) {
  if($form_state['values']['first_select_box'] == 'something'){
    //the contents of your _ajax_example_get_second_dropdown_options function here
    //and instead of returning something... just SET #options to your new output.
    $form['second_select_box']['#type'] = 'select';
    $form['second_select_box']['#options'] = 'new stuff';
    $form['second_select_box']['#title'] => 'Choose';
  }
}


Field values added programmatically dispear after a certain time I created a module that creates a block to show a schedule information. I need taxonomy terms to configure the block. I want that those terms are filled with preconfigured values when I install the module.

I have in my config/install folder the definition of my taxonomy:

core.entity_form_display.taxonomy_term.schedule_channels.default.yml
core.entity_view_display.taxonomy_term.schedule_channels.default.yml
field.field.taxonomy_term.schedule_channels.field_channel_id.yml
field.storage.taxonomy_term.field_channel_id.yml
taxonomy.vocabulary.schedule_channels.yml

Here the content of the file field.storage.taxonomy_term.field_channel_id.yml:

langcode: en
status: true
dependencies:
  module:
    - taxonomy
id: taxonomy_term.field_channel_id
field_name: field_channel_id
entity_type: taxonomy_term
type: string
settings:
  max_length: 50
  is_ascii: false
  case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

Also in my schedule_block.install I have:

class schedule_block_class{

  const schedule_block_channels_terms = array(
    array(
      'name' => 'Brava',
      'field_channel_id' => 'BRA001'
    ),
    array(
      'name' => 'DJazz',
      'field_channel_id' => 'DJA001'
    ));
  const schedule_block_channels_vid = 'schedule_channels';
}

function schedule_block_install(){
  $schedule_block_terms = schedule_block_class::schedule_block_channels_terms;
  $schedule_block_vid = schedule_block_class::schedule_block_channels_vid;
  foreach($schedule_block_terms as $schedule_block_term){
    $term = Term::create(array(
      'name' => $schedule_block_term['name'],
      'field_channel_id' => $schedule_block_term['field_channel_id'],
      'description' => '',
      'parent' => array(0),
      'vid' => $schedule_block_vid
    ));
    $term->save();
  }
}

function schedule_block_uninstall(){

  $schedule_block_terms = schedule_block_class::schedule_block_channels_terms;
  $schedule_block_vid = schedule_block_class::schedule_block_channels_vid;
  $terms = array();
  foreach($schedule_block_terms as $schedule_block_term){
    if($terms_name = taxonomy_term_load_multiple_by_name($schedule_block_term['name'], $schedule_block_vid)){
      $terms = array_merge($terms, $terms_name);
    }
  }
  foreach($terms as $term){
    $term->delete();
  }
  $taxo = \Drupal\taxonomy\Entity\Vocabulary::load(schedule_block_class::schedule_block_channels_vid);
  if(!is_null($taxo)){
    $taxo->delete();
  }
}

When I install my module, my taxonomy vocabulary is created and my terms are loaded with my values

... BUT ...

After about 24h the values have disappeared. Checking in the table taxonomy_term__field_channel_id confirms that there is no more any values. I still have my taxo vocab, and all the needed tables are present.

Why the values are not permanent?

(Re comments)

That's the reason then. Those fields being in state, which means drupal thinks they were deleted and is trying to delete conent in them.

Remove them from there. Probably OK to drop the whole rows, check all the other fields in there. You might have some deleted field tables that you need to clean up manually.

I've seen someone else have this problem, what we couldn't figure out is how it happened. Please open a core issue (probably critical) and try to describe what you did.. delete fields, config import, create through manual config import. Anything you can think of that might have caused this.


Entityform send email to entity referenced node email I have a content type "Business" which has a field "Business Email".

I have an entity form with an Entity Reference field that allows a user to select mutliple businesses, leave a message and click send.

I need to send an email to the "Business Email" field of all referenced Businsess in the submission.

I have set up a Rule to react "After saving a new entityform submission" which checks "Enity has field:Business Email", and then sets up a send mail, but I am having trouble actually getting the value for business email and looping through it. Has anyone achieved something like that that can lend a hand?

Your rule should first use condition "Entity has field" on your entity reference field from the form -> the field where user selects businesses. In this case your form submission is the primary entity that your rule will target.

And then you'll have to loop through selected businesses and extract business email from each business that was selected by user in that form submission.

You can use components for getting email field out of your business entity or you can install "Conditional Rules" module (CR), which will allow you to write all the logic in rule's "actions" section without using components.

So your rule (if you installed CR) would be as follows:

Events: After saving a new entityform submission

Conditions: 1) Entity has field [entityform:field-select-business]

Actions:  Your actions will look something like this.

Loop: here you loop through your Entity Reference field -  [entityform:field-select-business]. You cannot loop through your Email field directly - every email is taken from refernced entity.

IF - here you will select conditional "Entity has field" Entity: [list-item], Field: [field_business_email] <- your email field. This brings email field into the rule's scope, otherwise your rule can't see the email field. This part is not possible to achieve in Actions section of a rule without "Conditional Rules" module.

And in the end - nest "Send Email" action under IF condition and you should be good to go.


Dynamically create fields based on integer value I have a requirement that I need to dynamically create x number of fields based on a supplied int value from a text box.

Example: There is a software content type. A user goes to add a new piece of software into the system. They received 11 keys/licenses with their purchase. The users enters 11 into a textbox, and then 11 license key fields display. The users enters in the 11 license keys and saves.

Hopefully that makes sense? Just looking for help deciding which fork in the road to take..

you should look into
Licensing

This module is useful for people that plan on integrating a software
licensing system on their site.
Features Out of the box, it provides the following:

Ability to generate, edit & delete unlimited unique license keys.
Ability to export your keys into a CSV document, which you can mail merge and distribute with physical copies of your product.
Ability for users to 'register' their key when they sign up for a drupal account, or by visiting a page when logged in.
Users can have multiple keys registered to one account, and they are all displayed on their user page.
Provides views functionality for default and custom reports.
Brandable license keys like XXXX-BRAND-XXXX-XXXX-XXXX
This module does provide functionality out of the box, however - it's power is in the hooks it provides which allow you to extend this
further.

Commerce Product Key

This module lets sites implementing the Commerce module, attach
product keys to orders. Product keys / Vouchers are strings of text
that are used to unlock or activate a piece of software.


How do I change the theme? I'm using the Dashboard module that comes with Drupal core. For roles that are not administrator, it is empty (permissions are set). I'm pretty sure it is because the theme isn't viewable. (Other roles do not see the backend theme.)

How can I change the dashboard theme to a custom theme?

For users who have access to Dashboard, remove their access to "use admin theme"; then they will by default use your theme.


Adaptivethemes and panels - how to create custom layout? I am building my site using panels , mini panels on every page.
In addition, I am using the panels everywhere modules.
The theme I am using is: "Adaptivetheme".

I every page I built (using page manager and panels), I chose a panels layout of "AT responsive panels" 3 or 2 columns, depends on the page.

can I change the ratio of the columns of the layouts, so it will be, for examples 20/55/25, instead of the default 25/50/25?

Panels - how to create custom layout?

In Panels, (or Adaptive), find the directory layouts directory.

In it, each layout has it's own directory with a couple of files in it.

Copy any of these directories, rename all the files to the new name of the directory, and you have a new plugin.

Also see the comment for the function at_get_plugins which provides Ctools specific integration so you can subtheme AT and have new layouts in your subtheme.


Drupal 7.x - Webforms and nodes I am using the webforms module and created a new webform.
Now my problem is... after I have created a specific content type, I would like to diplay this webform...

Imagine: Create a new event with title, start, end und location.

After this, Visitors should see the webform below:

webform contains attend=yes/no, name, email and a submit button that sends an email.

How can I achieve that?

Thanks!

Are you going to use the same webform for all your node events?

Then maybe you should consider creating a url pointing to your webform with parameters. In your webform you can catch the parameters with %get[parameter].

Although I should warn you that when I tried something similar I had this problem: Ampersand does not get urlencoded and breaks my GET parameters


How do you update the default value for a field programmatically? How do you update the default value for a field programmatically?  I know you can get the field instance info by calling field_info_instance, but how do you update that info?

The field_update_instance() function is the standard method

  Updates an instance of a field.

You can take the array returned by field_info_instance(), make your changes, then pass it back to field_update_instance() and the changes will be saved.


Attaching a block to a view create with the User type I have created a view using the User type.  The view has 2 entity relationships to a location content type and a manager content type.  With this I have setup contextual information relevant to the user's location and manager.

Now I need to add a generic video into the view as well.  I have created a video content type and have it displayed using mediaelement.

My question is how do I add this content to my user type view?  I am not sure if I am missing a really obvious way of doing this :p

I initially thought that I would be able to create a separate block view for the video then attach it to the original user view - but no luck there.

The way I found around this is that in the the fields I added a Global View.  Now the video is treated just as a field.


D7 Simple form with an items catalog grid table I need a form with a simple items catalog, user will enter quantities for each item and it will auto calculate sub total and total using javascript.

I am looking something like this:

Name: _

Email: _

Address: _

please select your items:

ID | Name   | Price | Quantity | Sub Total

1  | Item 1 | $10   | [_]  |

2  | Item 2 | $10   | [_]  |

3  | Item 3 | $10   | [_]  |

Total               |

[Submit]

Is there some module available to develop this kind of form, or I'll have to develop some custom module? I tried with Webform module but with no luck.

Thanks

I did it myself with the help of webform, webform_table_element module and by implementing a couple of hooks and a little jQuery snippet. A complete howto can be found here:

Drupal 7 Webform with an item catalog table element

Thanks.


Preprocess a twig template file I don't fully understand how preprocessing works

I have a twig template /themes/custom/client/templates/content/node--myfile.html.twig that I want to alter

I want to show/hide a part of that template depending on a field display with the machine name field_display stored in the matching content type called Project and with the machine name project_machine_name.

So I well understand I have to use hooks in order to do this, but I don't understand how I am supposed to name the hook functionnality neither how I'm supposed to access the data stored from the content type into the hook to alter the template view.

I know the hooks goes into the .module file. Actually I already have some of them, but I don't understand them properly. The only things I know for sure is that the function name must start by the module name

function my_module_SOMETHING_SOMETHINGELSE() {

}

So the issue is: how to name the hook function in order to alter the template ? I guess I understand the name is some kind of standard structure which will tell drupal if the function needs to be called before a specific action.

How to retrieve data stored from the display field of the content-types Project?

Thanks for your assistance.

Preprocess hooks are named MY_MODULE_preprocess_TEMPLATE_NAME, in your case:

function my_module_preprocess_node__myfile(&$variables) {}

Notice how I replace the template's dashes with underscores in the function name.

Now you can get the display variable from $variables['node']->field_display->value.


Services won't authenticate email address used as username I've installed the Email Registration module because I want my site's users to be able to register an account, and use their email address as their login username. This works great on the web login, however I've built an app to log users into my Drupal site as well using the Services module. When I try and log users in with their email address username, access is denied (whereas when they log in via the website, it authenticates just fine). Any idea why this might be?

The Email Registration module doesn't create any service resource. Also it doesn't change user login resource of the Services module that allows users to login just with their names.
I have implemented user email and name login solution with this custom service:

  /**
 * Implements hook_services_resources().
 */

function custom_mail_login_services_resources() {
        return array(
   'custom_email_login' => array(

        'actions'=>array (
        'mail_login' => array(
        'callback' => 'get_mail_login',
        'access callback' => 'user_is_anonymous',
        'args' => array(
            array(
            'name' => 'data',
            'optional' => FALSE,
            'source' => 'data',
            'type' => 'array',
            'description' => 'Name or email',
            ),
     ),
    ),
   ),
   ),
  );
}

  function get_mail_login($data) {
  global $user;
  $username = null;
  if ($name = db_query('SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:mail)', array(':mail' => $data['mail']))->fetchField()) {
      $username = $name;
  }elseif ($name = db_query('SELECT name FROM {users} WHERE LOWER(name) = LOWER(:name)', array(':name' => $data['mail']))->fetchField()) {
      $username = $name;
  }else{
        return services_error(t('No user with this email or name exists!'), 403);
 }
 if ($user->uid) {
    // user is already logged in
    return services_error(t('Already logged in as @user.', array('@user' => $user->mail)), 406);
  }

  // Check if account is active.
  if (user_is_blocked($username)) {
    return services_error(t('The user %name has not been activated or is blocked.', array('%name' => $mail)), 403);
  }

  // Emulate drupal native flood control: check for flood condition.
  $flood_state = array();
  if (variable_get('services_flood_control_enabled', TRUE)) {
    $flood_state = _user_resource_flood_control_precheck($username);
  }

  // Only authenticate if a flood condition was not detected.
  if (empty($flood_state['flood_control_triggered'])) {
    $uid = user_authenticate($username, $data['password']);
  }
  else {
    $uid = FALSE;
  }

  // Emulate drupal native flood control: register flood event, and throw error
  // if a flood condition was previously detected
  if (variable_get('services_flood_control_enabled', TRUE)) {
    $flood_state['uid'] = $uid;
    _user_resource_flood_control_postcheck($flood_state);
  }

  if ($uid) {
    $user = user_load($uid);
    if ($user->uid) {
      user_login_finalize();

      $return = new stdClass();
      $return->sessid = session_id();
      $return->session_name = session_name();
      $return->token = drupal_get_token('services');

      $account = clone $user;

      services_remove_user_data($account);

      $return->user = $account;

      return $return;
    }
  }
  watchdog('user', 'Invalid login attempt for %username.', array('%username' => $username));
  return services_error(t('Wrong username/email or password.'), 401);
}

You have to put this code into your custom_mail_login.module file and add custom_mail_login. info file. Module name is custom_mail_login.
Then enable this module and custom_email_login mail_login resource in admin/structure/services/list/your_endpoint/resources.

You have to send json request {"mail":"useremail@address.com", "password":"password"}. The parameter "mail" is an email or user name.


Drupal 7: Duplicated and Extended values on hook_preprocess by Drupal I'm trying to pass variables from my module to a template. Everything is working fine, but the variables passed to the view appear to be modificated.

Callback to generate and fill the view:

 function mycallback() {
    //(...)
      //var_dump($members);
      return theme('team_members', $members);
    }

Contents of $members:

array
  0 =>
    object(stdClass)[55]
      public 'mid' => string '1' (length=1)
      public 'name' => string 'LLUIS' (length=5)
  1 =>
    object(stdClass)[18]
      public 'mid' => string '2' (length=1)
      public 'name' => string 'OSCAR' (length=5)

This is the hook:

function global_preprocess_team_members(&$variables) {
  //var_dump($variables);
  $variables['members'] = $variables;
}

The content of $members is the following one:

array
  0 =>
    object(stdClass)[55]
      public 'mid' => string '1' (length=1)
      public 'name' => string 'LLUIS' (length=5)
  1 =>
    object(stdClass)[18]
      public 'mid' => string '2' (length=1)
      public 'name' => string 'OSCAR' (length=5)
  'content' => null
  'theme_hook_suggestions' =>
    array
      empty

Somehow, content, theme_hook_suggestions has been added to the array, but there is more.

Finally, when I print the results on the template file (tpl.php) via var_dump() again:

array
  0 =>
    object(stdClass)[55]
      public 'mid' => string '1' (length=1)
      public 'name' => string 'LLUIS' (length=5)
  1 =>
    object(stdClass)[18]
      public 'mid' => string '2' (length=1)
      public 'name' => string 'OSCAR' (length=5)
  'content' => null
  'theme_hook_suggestions' =>
    array
      empty
  'members' =>
    array
      0 =>
        object(stdClass)[55]
          public 'mid' => string '1' (length=1)
          public 'name' => string 'LLUIS' (length=5)
      1 =>
        object(stdClass)[18]
          public 'mid' => string '2' (length=1)
          public 'name' => string 'OSCAR' (length=5)
      'content' => null
      'theme_hook_suggestions' =>
        array
          empty
      'members' =>
        &array
  'zebra' => string 'odd' (length=3)
  'id' => int 1
  'directory' => string 'sites/all/themes/global' (length=23)
  'classes_array' =>
    array
      0 => string 'team-members' (length=12)
  'attributes_array' =>
    array
      empty
  'title_attributes_array' =>
    array
      empty
  'content_attributes_array' =>
    array
      empty
  'title_prefix' =>
    array
      empty
  'title_suffix' =>
    array
      empty
  'user' =>
    object(stdClass)[9]
      (...)
  'db_is_active' => boolean true
  'is_admin' => boolean true
  'logged_in' => boolean true
  'is_front' => boolean false

I know Drupal adds some variables here (e.g. user session), but as you can see, my array has been added twice. One in the variables root, and another one inside the members variables (with the extra fields I do not want).

What am I doing wrong?

I thing the ideal situation is having the members variable inside the variables without the extra content (only once).

Do you have any idea?

This bit is the problem:

$variables['members'] = $variables;

When you declare named variables in your theme function they are passed in as named keys of the $variables array. So when you call your theme function:

// Note the array wrapping the passed variable and also the 'members' key of the array. This is required in Drupal 7.
print theme('team_members', array('members' => $members));

This is what you'll get in your preprocess function:

$members = $variables['members']; // This contains the original member array passed to the theme function as the named variable 'members'.

What you're doing at the moment is overwriting $variables['members'] with the $variables array itself, so all you're really doing is adding an extra array around the variables array.

Try putting the members that are passed into the preprocess function into a different variable:

$variables['custom_variable'] = do_something_to($variables['members']);

and outputting that one in your template file:

print $custom_variable;

I think that's what you're trying to do, have a look at hook_theme() for more information :)


use a custom view mode in node.tpl With Display Suite we can make custom view modes other then Teaser to use through out the site (in views for example). This is working fine and very nice!

However, using the custom view in a .tpl file does not work (where $teaser is confirmed to work).

Notice: Undefined variable: custom_view_mode_one in include() (line 92 of /home/dev/drupal-7.x/sites/.../node--custom-content-type.tpl.php). =>

do i need to register this in template.php even though it is already registered on the page and usable everywhere else?

$teaser is being passed in from template_preprocess_node().  DS just makes the view mode via a hook_entity_info; it doesn't wire it into the themeing system.  You need to do something like this:

function MYTHEME_preprocess_node(&$variables) {
  $variables['custom_view_mode_one']
    = $variables['custom_view_mode_one'] == 'custom_view_mode_one';
}

You could also be smart by using a entity_get_info('node'), and get all of the view modes, and set similar variables.

Note that you should already have a variable called view_mode available in your template, too.


Drupal 8.3.1 CSS and JS aggregated by default I just installed Drupal 8.3.1 and created my own theme. I have both 'Aggregate CSS files' and 'Aggregate JavaScript files' unchecked. Also, in my settings.local.php I have:

/**
* Disable CSS and JS aggregation.
*/
$config['system.performance']['css']['preprocess'] = TRUE;
$config['system.performance']['js']['preprocess'] = TRUE;

Yet, Instead of having all the css style sheets in head and all the JS files at the bottom of the page, I have 4 aggregated style sheets in head and one aggregated js file at the bottom of the page.

Any idea what is causing that?

If you want to disable aggregation, you need to set these variables to 'FALSE' instead of 'TRUE'.

If you are interested in disabling cache for development purposes, you can find more information in the following response: https://drupal.stackexchange.com/a/183397/27068


Delete content problem in Multilingual site with module Global redirect I have a multilingual mini site with 2 pages/nodes with 6 languages enabled. I don't have the translation for some language on some pages. I was hoping global redirect would help me with this by redirecting the user to the default language when the translation doesn't exist. This part only works partially but this is not not my concern for this thread.

At the beginning I added missing translations by putting the English version instead. When I learn the existence of the module Global Redirect I decided to delete those missing translation. I downloaded and activated Gloabl Redirect and started to delete the nodes which had a bad version. But when you do so, it does not delete the node of the language you selected, it deletes the default language node!!

So in other words if I have a node in English (default) and go to Content and select the delete link of the Spanish translation it will delete the English version and keep the Spanish version!! A by-product of this is to change the default language to the next on list...

Is it a know bug? What can I do to fix this other than NOT using Global Redirect? Did I do something wrong?

If not already in use, I recommend using the i18n module instead of global redirect (which is imo more a SEO module) which let set you a fall back for not (yet) translated pages as well.
With this module you can also translate menu entries, path-settings, taxonomy terms etc. (even the site name and the site slogan (when using together with the variables module)).

Greetings krueschi


URLs with trailing slash say site in maintainence mode, others don't, site isn't in maintenance mode Something very strange has happened and I'm at a complete loss as to how to go about working out the cause.

I used Backup / Migrate module to restore a backup of my live site's database (let's call it somesite.com) onto my dev site's database (let's call it dev.somesite.com) after copying the files over.

I visited dev.somesite.com/admin/ and was surprised to be told it was in maintenance mode. I did the usual maintenance mode fixes: drush vset maintenance_mode 0, checking that the contents of variable > maintenance_mode in the database was i:0;, but it still showed as maintenance mode.

A little trial and error later, I discovered that dev.somesite.com/admin did work, and it seemed having a trailing slash in the URL would show the maintenance mode page.

What could possibly be causing such a strange behaviour? My first thought was, since it's a URL formatting issue, there might be a mistake in my .htaccess file, but it looks fine and hasn't changed.

Update: a little more testing seems to show that this only happens for URLs the user doesn't have access to. For example, dev.somesite.com/admin/ while logged in gives the expected user access error, dev.somesite.com/about-us/ while not logged in redirects to dev.somesite.com/about-us and then works fine, but dev.somesite.com/admin/ while not logged in gives the maintenance page not the access denied page.

So, it's not as serious a problem as I first thought, but it's still strange and smells like a sign I might have misconfigured something which might in turn have more serious consequences elsewhere - but I don't know what this could be. I've looked at my Global Redirect settings and they look fine.

Have you already cleared the cache? Maybe it's just that
Try putting this code $conf['site_offline'] = 0; into settings.php to see what happens :)


Use a custom module to add JS to every page in Drupal 8 How can I use a custom module to add JS to every page with Drupal 8?

I've found lots of example scattered over the internet that maybe used to work but no longer work.

Assume the custom module is called example.

First create a example.libraries.yml file in your module root folder like this:

example:
  version: 1
  js:
    example.js: {}
  dependencies:
      - core/jquery

Next in example.module use hook_page_attachments() too add your JS to every page:

/**
 * Implements hook_page_attachments().
 */
function example_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'example/example';
}

So now the custom module has 4 files:

example.module
example.info.yml
example.js
example.libraries.yml

hook_page_build() and hook_page_alter() are now deprecated so can no longer use them.

There is a page drupal.org on adding CSS and JS using a custom module with more information.


connecting words with a integer field in a content type I would like to have a content type with the following behavior.

A dropdown list with words that can be selected, when a user selects on or more words these words are added to the node. But every word should have an integer value connected to it, and these values should also be stored in the node.

The problem i'm having is i don't know how to connect the word with the integer value.

This is for a site where there is a periodic maintenance to equipment. The used spare parts in the maintenance would be the words, the integer is the price of the maintenance part. Afterwords i would create a view to add the total value of the integer so the technician can easily see how much the total value is of the used spare parts.

It's quite simple, really. Create a content type for parts. Use title for part name, remove body, add integer field for price.

In your "maintenance" content type, create Entity reference to parts. That's all. Views are able to use Entity references ad views relationships, so sum of prices will be doable.


What's hook_node_view() alternative? I am using Drupal 8 Beta 14 and I want to edit the node object in teaser view mode. As hook_node_view is removed in Drupal 8. What's the alternative hook or some other way that I can use to edit the node? Is it hook_ENTITY_TYPE_view or hook_entity_view or some other thing?

Thank you.

hook_node_view() hasn't really been removed, the way it's invoked has just changed. As you mentioned, it's now handled by hook_ENTITY_TYPE_view().

So you can either use:

hook_entity_view()

or

hook_node_view()

The latter would make more sense if you're targeting nodes specifically.


Does pre-populated body for content types in Drupal 7 affect performance too? From highest rated answer of this post (Drupal 6 case):
Does having too many content types negatively affect site speed and performance?

It is said that:

  Sharing fields among the content types does affect the performance.

But when creating new content type in Drupal 7, the body field will be pre-populated. When many content types created, if not deleted, this field will be shared among all content types.

This is the body field as seen in admin/reports/fields:

The question is, does it affect performance? and what is the best to do for performance? Do I need to delete the pre-populated body?

tl;dr: No.

What happened in D6 when you shared a field, was that it got moved to it's own table.
This became irrelevant with D7, as all fields are now stored in separate tables, which was a very controversial decision, due to the performance effects this has.

If you want to increase performance, you can read some more here: How do you improve drupal performance.


How can I hide or show fields using states with hook form alter We have been using Field States UI module with some success, but the Comparison Value does always not work for multiple values, I have tried to modify the valuse right in the entity_form_display.node yml file but no luck. I will also try the Conditional Fields module for D8. I also want to try to do this using code. I am trying an example using hook form alter taken from this post. But I cant get it to work. https://stackoverflow.com/questions/35380720/drupal-8-conditional-field. Should I be using drupal_process_states instead? Here is my code, I have two term reference fields field_test2 and field_test3. If you select the term id 15 from field_test2 then field_test3 will become visible.

use Drupal\Core\Form\FormStateInterface;

function mymodule_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_page_form' || $form_id == 'node_page_edit_form') {
    return;
  }

  if (isset($form['field_test2'])) {
    $states_when_category_is_design = array(
      'visible' => array(
        ':input[name="field_test2"]' => array('value' => '15'),
      ),
    );

    if (isset($form['field_test3'])) {
      $form['field_test3']['#states'] = $states_when_category_is_design;
    };
  }
}

It seems you re using the Drupal 7 syntax. For Drupal 8 this is slightly different.

You can implement hook_form_alter() as follows to change the visibility state of a form element as follows:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_article_edit_form') {
    $form['field_other']['#states'] = [
      'visible' => [
          'select[name="field_reason"]' => ['value' => 'other']
      ]
    ];
   }
 }

This will make the field_other field visible if the other option is chosen in the reason select list.


which hook to change the node order in a view? I have a custom view but now I want to put the nodes created by a specific user role on top.

I want to do this using code so I can easily implement this throughout multiple web pages.

I'm thinking to alter the query or to put an array sort before the nodes are rendered.

But I don't know which hook would be useful for this.

edit:
using hook_views_pre_render as suggested by Jimajamma

function vacancies_views_pre_render(&$view) {
  dsm($view->result);
  $view->result = array_reverse($view->result);
  dsm($view->result);
}

But that doesn't change the order of the nodes in the view ( putting a dsm($view); in the if statement ensures me that it is this view that is called. )

You can use View's prerender hook to modify the view's results anyway you want.

For example,

function YOURMODULE_views_pre_render(&$view) {

   if ($view->name=='xyzzy') {

      // modify/sort the $view->result array to your heart's content here
      // for example, reverse it...
      $view->result=array_reverse($view->result);

   }

 }

Basically $view->result is an array of row results, so, just go through it and grab the rows you want first, then follow that up with the remaining rows.

ADDITION:

I created a quick view and did the above reversing and it certainly reversed the order so I am not sure what you are doing ever so slightly wrong to not see similar behavior on your site.