What's the proper way of working locally with freshly created features? I have recently started to using Features, it was due time.

Once thing I started to wonder, is, once you created your feature locally, what's the best way to work with it. I first thought that creating the feature was enough and once it was there you could use it as such, but disabling the newly created feature doesn't remove everything the features exports, so it doesn't behave the same way as if you installed the same feature on a plain site.

Is that on purpose? If so why? What are the details I should consider for working with Features on the initial site.

How features store settings

Features that are created locally have all there setting and content in the database as they where there before you export them to the feature, as an example if you created a view it will reside in the database even if you exported it to a feature.

as for features enabled on another site it will store every thing in the database when enabled except for ctools exports, which in this case even if you disable or uninstalled the feature those sittings will persist in the new site database, an example a strongarm (variable) will still be set even after you uninstall the feature.

as for settings using ctools exports they will not be added to the database unless you have override them, as an example if you had a view exported through features it will disappear if you have disabled the feature since it only exist in code.

Conclusion

Features do not delete any thing in your database if uninstalled, except for true exportables that can only reside in code without the need to be in the daatabse to work.

Suggested features workflow

When creating a feature on you local development machine it is a good thing to enable it to see if the settings in your database and the settings in the feature does match and be aware if they do change.

As for removing things added by the feature you can add a hook_uninstall manually to your feature .install file and remove or delete what ever you like just like a proper module will do when uninstalled.

More info about this issue:

https://www.drupal.org/node/1732766#comment-6382244
https://www.drupal.org/project/configuration


Shopping cart not cleared after checkout I have had several customers who have been able to make changes to previously placed orders. Even though the order status is set to pending after checkout is complete and their payments are processed, they are able to go back into the shopping cart (which should be empty but is not) and delete items from the cart.  They then believe that the payment amount will be adjusted to reflect the new total of items left in the cart, but of course it will not, as the original amount has already been charged to their card by Elavon. Why does the cart still contain items already ordered? How do I prevent this from happening?

This looks like a permission issue. Check the permissions page admin/people/permissions and make sure only relevant roles can edit orders.

By default, only the following permissions should be granted to authenticated users, and to any customer role you may have created  :

Create Order orders, optionally Create orders of any type
View own Order orders, optionally View own orders of any type

About the items remaining in shopping cart after checkout, have you tested yourself ? I'd more believe your customers edited orders from their orders page if they had permission to... Else, a custom rule or a custom module may cause that behaviour.

As explained in drupalcommerce.org

  At the heart of Drupal Commerce is the ubiquitous Order. This Order is
  first created when a user adds a product to a cart. The Order is
  actually the "cart" when it has a status of "Shopping Cart."

Cart is only one of the possible states of an order.


Is there any rule when to use panels and when to use templates in drupal 7 I want to know about the panels and templates use cases as i am confused when to use panels and when to use templates as each page can be designed by both the ways then which is the best solution.
 As we can easily layout both the things through html css.

Simple rule:

If you want to add some other blocks, content panes, or other information that is related but not included in content; you need to use Panels.
If you want to display the content in a custom way and all information you want to display is already included in content, then you don't need Panels, use a template.


How to use views and LDAP query to get a list of names in a webform? I am using Views, LDAP query, Webform Views, and Webform to try and produce a webform that -- along with a bunch of other stuff in the webform -- has a select list of names, with emails associated, from our ldap server. So far I have gotten a View page with all the names, but I don't know how to condense that to not just be a giant list (un-collapsible) in the middle of a webform. So any idea how to do this or some similar solution so that the person filling out the form can find a name in a list of names, and for either them to see the email in a list and select/write it in another field, or for them to just select a name from a select list and have that selection effect the results(like providing an email to go with the name)?

Some other info -- the LDAP data has names and emails, as well as a variety of other information that would be useful to the people reading the results. Also, I have tried using feeds, and ldap feeds and was unsuccessful, but I would be happy if there was anyway to use both of those as well.

If you have a valid ldap query with names and emails your basically there with Views and LDAP.

You want to make a custom webform component in a module using PHP code. You can use views_get_results to get the results of the LDAP view as an array.

Then just build a webform component as you would a Forms API select widget with your values.

You then tell the webform to use your component in the UI.


How to pass values directly from THEME_NAME.info to THEME_form_system_theme_settings_submit() Does anyone know a smarter way to load given settings from the THEMENAME.info file for the submit function only, than to create another "ghost"-form calling theme_get_setting() ? I would like to prevent the ghost form, since there is no input needed.

I only need some settings from the info file in the submit state.

You do not need to use a form to save these values.
variable_get() and variable_set() functions will make it much easier to set the value and retrieve it.

However, if you still want to pass the information via the theme's .info file, you can do as follows:

Add your custom variables to the .info file

EX:
my_awesome_theme.info file:

name = my_awesome_theme
core = 7.x
dragons_exists = 1
how_to_catch_a_dragon[] = "Be a dragonlord"
how_to_catch_a_dragon[] = "Tell him to surrender"

Drupal will ignore these extra stuff during normal module/theme scanning.

To get the value, you can it like this:

$data = drupal_parse_info_file('sites/all/themes/my_awesome_theme.info');

You can use functions like drupal_get_path() to get the correct path.
$data will contain the values from the .info file.
For example,  the above .info file will yield

Note that drupal_parse_info_file() doc mentions that you should NOT use this method to store arbitrary data.

  Parses Drupal module and theme .info files.

  Info files are NOT for placing arbitrary theme and module-specific
  settings. Use variable_get() and variable_set() for that.

Update:
If you only need to pass some variable from the form, and not necessarily from the .info file, just store the value in $form_state.
As long as you don't overwrite some existing values, $form_state['values'] for example, it will work just fine.

Also, consider using a form element of #type => value. User will not see anything at all, not even a hidden form element. You can access this value from $form_state['values'] nevertheless.


How to hard code to login as admin? In the past, I developed a Drupal site in my localhost. After that, I uploaded to production site. Everything was OK.

Recently, my HDD was died. So, I lost my Drupal site source code. I downloaded my production site on localhost.

I cannot log in. I think the problem is cookies.

How can I force Drupal to get my login by adding some code lines?

You have the possibility to edit the current password locally.

You should take a look at Resetting the administrator password with sql-query. It is possible with some commands and SQL queries to change the current password for your admin user (UID=1).


How can you reference taxonomy term by another field in Yaml file? I created my own Yaml file with fields inside to migrate nodes.

I run into this problem.
If I use the feeds module, I can set (during mappings) that a given field (taxonomy term reference field) can be referenced by any other field from my site. The term name is therefore assigned based on the value in the reference field.

If I use Migrate CSV module, how do I set this in Yaml file?
This is my Yaml:

uuid: bf1e53ae-6a95-48f2-8888-4b928e6e33ea

id: testovacimigrace2
label: My own migration !!!!!!!
migration_group: migration

source:
  plugin: 'csv'
  # Full path to the file.
  path: 'modules/custom/migrace/assets/csv/upload1.csv'
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  ids:
    - ID

process:
  title: title
  field_email: email
  type:
    plugin: default_value
    default_value: submitlawyer

destination:
  plugin: entity:node

Every term in my taxonomy called "fishes" has its own field with a unique number.
My CSV contains a column called fish that does not contain a term name but its unique number (ad.1)
I need to assign the correct term by using this unique number.

Here is a simple migration for looking up a taxonomy term by name based on the text in a CSV.

taxonomy_field_name:
  plugin: entity_lookup
  source: name_of_source_column
  value_key: name
  bundle_key: vid
  bundle: name_of_taxonomy
  entity_type: taxonomy_term

For example, if you have a taxonomy called fishes, and your CSV has a column called fish, and your node has a field called field_fish which is an entityreference to a taxonomy term of the fishes vocabulary, and there is a taxonomy term "Carp" with entity ID 14

field_fish:
  plugin: entity_lookup
  source: fish
  value_key: name
  bundle_key: vid
  bundle: fishes
  entity_type: taxonomy_term

Given a row in the CSV with "Carp" set as the fish, this will assign entity id 14 to that field.

Does that help?  I am not sure what you mean by "a given field can be referenced by any other field from my site".


How do I import blogs from Drupal 6 to 7? How can I import blogs that were created in a Drupal 6 site to a Drupal 7 site? I'm not looking to upgrade the Drupal 6 site because the Drupal 7 site is a complete redesign of the old one and I wanted a clean start. I would like to not have to manually copy all of the blogs to the new site.

You should use the excellent Migrate module for this. Another quick way to do this, is using the Feeds module, which lets you import data using RSS and a variety of other formats.


Twig theming boolean issue I have a boolean for the status of a page on whether it is new or not. If it's selected, I want the following code to take effect.

{% if fields.field_new.content %}
  <div class="info--details__new">
    {{ fields.field_new.content }}
  </div>
{% endif %}

This works fine for when it's selected. However, if I unselect it, it still displays the div with the info--details__new class only empty.

I'd like for this div to not be displayed when this boolean isn't selected but can't seem to figure out how to do this in my twig template.

What's the best way to go about doing this so that my empty div doesn't show up when the boolean is unselected?

This is in my views-view-fields--VIEW-NAME.html.twig file.

As discussed in the linked topic use database values to check for booleans in a condition. In a View template you'll find for each row the entity the row is based on in row._entity, from which you can get the raw field values:

{% if row._entity.field_new.value %}
  <div class="info--details__new">
    {{ fields.field_new.content }}
  </div>
{% endif %}

Even if it works with debugging turned off, you still depend on how you've configured the rendered output and this is not good practice, if a small change in UI can break the code.


display list of pages of content type using views + edit and delete option I've installed the Views Bulk Operations module (VBO). Using this I want to create a block/page to  load all the pages of particular content-type. But it should include options like update + check boxes, edit/delete. See the screenshot below.

I couldn't find the built in view 'content', so I've to create from scratch. Please give me solutions.

I got the solution by installing Admin VBO Views module


Saving a field of type 'text_format' as a system setting variable I'm attempting to give my content editors the ability to change a variable for a custom module. This variable can have html. I don't want to require them to have any knowledge of HTML, so I want to give them the ability to have our wysiwyg (CKEditor provided by the CKEditor module) at their disposal. However, as of now, the data does not save as a variable. I've read in a few places (D.o, stackexchange) that I needed to do something like this:

  $form['foo']['bar'] = array(
    '#type'     => 'text_format',
    '#title'    => 'Bar',
    '#definition' => 'Foo Bar',
    '#default_value' => variable_get('bar', ''),
    '#weight'   => 1,
    '#format' => 'filtered_html',
    '#required' => FALSE,
  );

This does not work out-of-the-box with a system_settings_form($form). A var_dump shows this after a save:

array (size=7)
  '#type' => string 'text_format' (length=11)
  '#title' => string 'Bar' (length=7)
  '#definition' => string 'Foo Bar' (length=74)
  '#default_value' =>
    array (size=2)
      'value' => string '' (length=0)
      'format' => string 'filtered_html' (length=9)
  '#weight' => int 1
  '#format' => string 'filtered_html' (length=9)
  '#required' => boolean false

From this, you can see that 'format' saves correctly, but 'value' does not. What am I missing?

Also, if there is a better way to do this, please do tell.

The following worked for me; the #default_value is expecting a string but the text_format form element is stored as an array.

$barvalue = variable_get('bar', array('value' => '', 'format' => NULL));

$form['foo']['bar'] = array(
'#type'     => 'text_format',
'#title'    => 'Bar',
'#definition' => 'Foo Bar',
'#default_value' => $barvalue['value'],
'#weight'   => 1,
'#format' => $barvalue['format'],
'#required' => FALSE,
);


How to define and use an external database connection in a custom module I'm developing a module that will rely heavily on external database queries. Is there a best practice for defining and using an external database connection throughout a module?

This page tells me how to make the connection, but not where to put it in a module (specific hook?) so I only have to define it once. Also, is it always necessary to do "db_set_active('YourDatabaseKey');" or can I pass an argument that will set the db to use? I'm using Drupal 7.

There's no particular place to put this code (hook or module), you just put it where you need it.
So it should go just before your queries on the other database and just after to set back the default DB.

If all your module will rely on the external DB just put it a the beginning of the first function called for your module and at the end of the last function.

Of course every one of your function should be executed on the external DB and nothing must have to query the default database without switching back.

This following code would fail:

db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

$node = node_load(123); //This would fail on the external DB.

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();

You should switch back and forth:

db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();
$node = node_load(123); //Query made on the default Drupal DB.
db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();


Module code not firing I have a custom D7 module that I have placed in sites/all/modules/custom/mymodule folder. It appears on the modules page, and when I enable it, there are no errors.

The only code inside of it is:

function mymodule_init() {
  exit;
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  var_dump($form_id);exit;
}

Yet, neither of these cause an exit. If I place an exit outside of these functions, it definitely exits.

What is the issue?

Edit: Info file contents:

name = My Module
description = Form modifications for user forms (register, login).
core = 7.x
version = 7.x-1.0
dependencies[] = html5_tools
dependencies[] = elements

Your version string is wrong, and shouldn't be manually included anyway, but that wouldn't cause this issue.

Drupal searches recursively for modules. I just recreated the same set-up that you had, and after a cache clear (do this by visiting admin/config/development/performance and clicking "Clear all caches").


Does CAPTCHA Module still disallow page caching? I'm trying to manage spam entries into my websites' contact forms. Currently using the Drupal Captcha module for Drupal 6. http://drupal.org/project/captcha

Based on this report: http://3dg.me/web/drupal-caching-incompatible-with-captcha - I learned that page caching can interfere with the operation of the module. Is this still relevant? Does this apply to allow image captcha based modules?

Yes. The Captcha module is still incompatible with Drupal's caching. In fact once the captcha modules is enabled it gives you a nice warning on Drupal's performance settings page that says:

 The CAPTCHA module will disable the caching of pages that contain a CAPTCHA element.

Most challenge/response modules like this will disable caching. Take a look at something like the honeypot module. It helps in deterring spam bots from completing forms on your Drupal site. It basically inserts a hidden form field to Drupal (or other) forms with a field name like 'homepage' (you can set it to whatever you want). End users don't see the field, so they don't fill it out. But spam bots (usually using prewritten scripts) do see the field (usually), and add something to it. The Honeypot module detects this and blocks the form submission if there's something in the field. It does this without disabling cache.

Note: The Honeypot provides two methods. The timestamp method does disable caching, so use the Honeypot method.


How to import Image alt, titles or File description? Hello Drupal Community,

In a Product display i have image and file fields, I was wondering if there is a bulk way to import image alt text and image title or File description?

I used feeds to import images and multiple Files into product display but i cant find a mapping options to link alt, title or file description.
Also i was considering it is possible with VBO by executing arbitrary PHP script.

Any assistance would be appreciated.
Thank you
Darius

One way to deal with this issue is to use the ImageField Tokens module:

  The ImageField Tokens module extends the default functionality of
  Image fields adding the ability to specify default values and use node
  tokens in the Alt and Title text.

The module Token is required. After you install and enable the modules, you configure its settings in the field properties for each individual content type.


What hook do I use to add a field to a content type after it was programmatically created? I have a module that created a custom content type with some fields.

Now I need to update the content type with a new field and wanted to know what hook do I use? As of now my content type was created via the .install file but need a way to process the changes without uninstalling and re-intsalling the module. My .install file

function example_node_install() {
  $t = get_t();

  // Define the node type
  $example_node = array(
   'type' => 'example_node',
   'name' => $t('Node Example'),
   'base' => 'node_content',
   'description' => $t('This is an example node type.'),
   'body_label' => $t('Example Description')
  );

  //Add defualts
  $content_type = node_type_set_defaults($example_node);
  node_add_body_field($content_type);

  // Create the field
  $field = array(
    'field_name' => 'item_description',
    'cardinality' => 1,
    'type' => 'text',
  );
  field_create_field($field);

  // Create the instance map description.
  $instance = array(
    'field_name' => 'item_description',
    'label' => 'The item description.',
    'bundle' => 'example_node',
    'entity_type' => 'node',
    'widget' => array(
      'type' => 'text_textfield',
      'weight'  => 2,
    ),
  );
  field_create_instance($instance);

  //Save Content Type
  node_type_save($content_type);
}

Any guidance will be appreciated.

Try the hook_update_n function
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7

You would define a hook_update_n function in your install file in which you place the functionality to add your field to your content type.
See for example:
http://cgit.drupalcode.org/entity/tree/entity.install#n35

After added this functionality run http://example.com/update.php

A second option would be to use the features module to export your content type to a feature and when you are making changes in the UI to that content type (like adding a field for example) you can export the content type again to the feature and deploy that feature to your other (live) environment and revert the feature (which will bring the new code (the newly added field) into the database.


Cancel vote when user is deleted Is there any way to cancel user votes (if there are any) when I completely delete a user account?

Thanks kiamlaluno for the first guide. I'm really lost about writing even a mini-module.

Here's the code for what i was needing:

// Cancel / subtract user vote from 'poll_choice' table, when user account is cancelled.
// The code (db_update) which subtract users vote is a copy from poll.module
function MODULE_NAME_user_delete($account) {
    $uid = $account->uid;
    $votes_id = db_query("SELECT chid FROM {poll_vote} WHERE uid = :account_id", array(':account_id' => $uid))->fetchAll();
    foreach ($votes_id as $vote_id) {
        db_update('poll_choice')
        ->expression('chvotes', 'chvotes - 1')
        ->condition('chid', $vote_id->chid)
        ->execute();
    }
}

This is for MODULE_NAME.install. We need it to make sure poll_vote table is not update before this module function is executed.

function MODULE_NAME_install(){
  db_update('system')
    ->fields(array('weight' => -1))
    ->condition('name', 'MODULE_NAME', '=')
    ->execute();
}


Error when applying patch I seem to getting an error when trying to apply a patch and I'm a bit stumped on where I am going wrong if anyone knows that would be fantastic - I need to apply this patch: https://www.drupal.org/files/issues/media_entity_image_thumbnail_problem_2767501_13.patch

I am inside the mysite/public folder where I have placed the patch file and then try to run:

git apply media_entity_image_thumbnail_problem_2767501_13.patch

It doesn't seem to do anything so I then run:

$ patch -p0 < media_entity_image_thumbnail_problem_2767501_13.patch

can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/src/Plugin/MediaEntity/Type/Image.php b/src/Plugin/MediaEntity/Type/Image.php
|index 09b9655..398d3c0 100644
|--- a/src/Plugin/MediaEntity/Type/Image.php
|+++ b/src/Plugin/MediaEntity/Type/Image.php
--------------------------
File to patch:

it seems to have an isssue with: @@ -7,6 +7,7 @@ use Drupal\Core\Datetime\DrupalDateTime; should I be placing the patch file somewhere else?

Yes. The patch needs to be placed inside the media_entity_image folder alongside the media_entity_image.info.yml file. And then you should be able to execute

patch -p0 < media_entity_image_thumbnail_problem_2767501_13.patch

without any issue.

If you are using composer- I would highly encourage you to use the cweagans/composer-patches composer package. Details at https://groups.drupal.org/node/518975


After update 8.7.0 seven admin theme can't find icons I updated my Drupal 8.6.15 > 8.7.0 After updated page not found error keep coming. (I attached photo below)

It happens only in Admin theme, when I change admin theme to default theme, errors are gone. I installed a new test site with 8.7.0. but no error has happened. I tried to change core folder, theme folder. and icon files are still in the same location. I'm really confusing now. I tried to revert older version of drupal core. when it happened errors are gone but my drupal has problem. (DB is still has information of newer version I guess..) I think path of icon is wrong. error shows me wrong location.

I guess nothing wrong with new core version. but something has happened with my previous settings which I never know. anyone can help me?

Suggestions

I see that you are new to the community, so welcome. Here are some suggestions:

Make sure you performed the updates correctly (preferably using composer)

I see that you've already cleared cache (:

See if the files are actually there in your file system.

If you're not getting this problem on your dev env and only getting it on your server, see if the files are getting uploaded properly.
I had a similar problem and the reason was because of a .gitignore entry which was ignoring the icon files, so they were not getting committed and as a result, they were not being uploaded to the server.

If the SVG files exist on your server, see if you can access them by typing an absolute URL to those files

If not, then maybe there's something in your .htaccess or in your server config which is preventing you from seeing SVG files.

If all of the above don't work, please post a comment and I'm sure me / someone else will surely help.


How drupal keeps revisions for some content types only In Drupal 6 for some content types when editing a node its replicated and keeps revisions for that content type by keeping vid (version id) for that in the table, But for some other content types it wont make new table entries when editing that content types . How is it like that ? Or is there any criteria to keep revisions for some content type only ?

update from comment

The revision information can be done when creating a  content type item itself , but how come its auto selected for some content types ?

2nd update

When creating a new content type i can see the options as follows :

But as you can see , revision settings is inside submission form settings  but **its disabled** here , how i can set revisions for particular content type only for some content type only .

For D7:

admin/structure/types/manage/YOUR_CONTENT_TYPE

You need to tick the checkbox "Create new revision" for saving revisions of any content type you want.

For D6:

administer/content management/content types/edit/workflow

Thanks!


Putting footer region under body tag I'm fairly new to drupal and this is my first time posting on stackexchange. Constructive critisism and feedback are more than welcome.

All regions in my custom theme are placed inside the body tag from html.html.twig file. Is there any way to create a region that is located underneath the body?

The markup should look something like this:

header region block(s)
...
footer region block(s)

Right now the way it's rendered it looks like this:

 header region block(s)
  ...
 footer region block(s)

I'm on drupal 8.6.
Thanks in advance,
Geordi

Best practice dictates that you should not put the header or footer outside of the body tag. All visible content on your site goes inside the body tag.

Correct HTML syntax looks like this (here is a basic example):

<head>
  <title>My Drupal site</title>
  <!-- Other metadata goes here -->
</head>
<body>
  <header>
    <!-- Top of the page content goes here -->
  </header>
  <section>
    <!-- Main body content goes here -->
  </section>
  <footer>
    <!-- Footer content goes here -->
  </footer>
</body>

See this page for some extra details https://www.w3schools.com/html/html5_semantic_elements.asp

I know this doesn't technically anwer your question, but I feel this is a "correct" response in regards to what information will be most helpful.


How merge two different views on single page? How can I merge two different views on single page by displaying value with common filter condition for both views.

Ex: I have view1 and View2 and now I want to display both views on single page and filter condition if I select Id card number from View1 along with view1 fields the respected linked users in view2 should display.

Views Global Filter

  Use Views Global Filter on sites that feature multiple Views. You want
  the views to be driven by the same filter selection, for instance a
  country, a date range, a search term or even proximity to a post code.
  These views may be on the same page or scattered across several pages
  on your site, however you want to offer the visitor the convenience of
  setting the filter for all these views only once, for instance when
  they first land on your site. Views Global Filter implements the
  picked once, operates site-wide (POOS) principle. This means you can
  place anywhere on your site a selection widget (drop-down, check boxes
  etc) to globally filter all or some of your views. When the user picks
  a value from the global selector, the value is invisibly passed as a
  contextual filter to whatever views you like, even when these reside
  across multiple pages. This avoids you having to duplicate filters and
  avoids the visitor having to re-select their choice as they go from
  page to page.

Combine two views on one page


Looking for something similar to "Views selective filters", just with "inactive" instead of "removed" The Views Selective Filter module reduces the filter items in a views exposed filter to only those having actually results.

I'm searching something similar, but I don't want to hide the options with no results, instead I want to make them inactive (shown greyed out).

The exposed filter list I have is just a vocabulary with some category terms.

Is there a module for this somewhere out there? Or how can I achieve that?

How are you going to gray out items in a combobox? If using Better Exposed filters module to replace the combox with some other widget, you can easily use Views Selective Filters and some Javascript to do the magic.


Show only used taxonomy terms in exposed filters I have an exposed filter for tags on my view. I want this filter to only show show used tags. I found some drupal 7 options like this one and the Views Selective Filter but can't seem to find a good drupal 8 option.

Can anyone help me out with a solution for this?

As Adrian said it was possible to change the code in the article a bit to make it suitable for Drupal 8. Here is my solution:

function MODULENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //id of the form you want to alter
  $formId = 'views-exposed-form-agenda-page-1';
  //field tags
  $select_field = 'field_tags_target_id';

  /**
   * Apply the form_alter to a specific form #id
   * the form #id can be found through inspecting the markup
   */
  if ($form['#id'] == $formId) {
    $available_terms = _get_available_terms();
    if (isset($available_terms)) { // Unset the existing list and add new one with available terms.
      unset($form[$select_field]['#options']);

      if ($form[$select_field]['#options']['All']) {
        $form[$select_field]['#options']['All'] = '- Any Term -';
      }

      foreach ($available_terms as $available_term) {
        $tid = $available_term[0];
        $name = $available_term[1];
        $form[$select_field]['#options'][$tid] = $name;
      }
    }
    else { // Unset all options except '- Any -'
      unset($form[$select_field]['#options']);
      $form[$select_field]['#options']['All'] = '- Any Term -';
    }
  }
}

function _get_available_terms() {
  //table name of tags field
  $node_tags_table = 'node__field_tags';

  $db = \Drupal::database();
  $query = $db->select($node_tags_table, 'nft');
  $query->distinct();
  $query->join('taxonomy_term_field_data', 'tname', 'tname.tid = nft.field_tags_target_id');
  $query->fields('nft', ['field_tags_target_id']);
  $query->fields('tname', ['name']);
  $result = $query->execute();

  $term_list = [];
  while ($row = $result->fetchAssoc()) {
    array_push($term_list, [$row['field_tags_target_id'], $row['name']]);
  }

  return $term_list;
}


AJAX HTTP error on wsclient REST service I'm trying out the wsclient in Drupal 7 and whenever I attempt to test the the transaction to another API using REST I get the following error:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText:
Fatal error:  Call to undefined method HttpClient::__getLastRequestHeaders() in /home/dmwbm/www/sites/default/modules/wsclient/wsclient_tester/wsclient_tester.inc on line 143

Looking at the error it appears that this is an attribute required by the SOAP service. The SOAP examples are the only ones that work and the REST ones do not.

A friend suggested running this suite on simplytest.me so that I could isolate what is conflicting in my drupal install. Wouldn't you know, this message is output on this clean Drupal install.

Googling I see this error in a bug fix from two years ago. I must be doing something wrong in that this error should have been fixed by now and shouldn't show up in my install or simplytest.me. What obvious thing am I overlooking? thx, sam

It appears that both examples provided by the author no longer work, most likely because the API's changed. See link to author page above.


Multiple forms on the same page are causing conflicts? I have the following code.

function mymodule_get_node_create_or_edit_form($nodeType = '', $inputNode = null, $prepopulationFields = array())
{
  if (empty($inputNode))
  {
    $values = array(
      'type' => $nodeType,
    );
    $values = array_merge($values, $prepopulationFields);
    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->create($values);
    $form = \Drupal::service('entity.form_builder')->getForm($node);
  }
  else
  {
    $form = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity($inputNode);
    $form = \Drupal::formBuilder()->getForm($form);
  }

  return \Drupal::service('renderer')->render($form);
}

I use this function to create edit forms for a node. So I can, for example, create a form that can be used to create a form:

print mymodule_get_node_create_or_edit_form('page', null, array());

Or I can get the edit form:

$node = node_load(1);
print mymodule_get_node_create_or_edit_form($node->getType(), $node , array());

The problem is if I execute both on the same page. Eg:

print mymodule_get_node_create_or_edit_form('page', null, array());
$node = node_load(1);
print mymodule_get_node_create_or_edit_form($node->getType(), $node , array());

If I now make changes to node 1, instead of saving it, it creates a new node with the changes I made, Instead of actually editing the existing node.

I recently had the same issue and found a workaround in the corresponding Drupal core issue: The same form twice on one page with different arguments may process the wrong form when submitted.

The third comment suggests to enable FormState caching, and that worked great for me.

$form_state->setRequestMethod('POST');
$form_state->setCached(TRUE);


Embed two blocks in a block I have three blocks A, B and C and I need to embed the blocks A and B into the template of a block C.  Is it possible?

Yes, when you create a block programatically you can add any content inclusive another blocks.

In your block function you can do something like:

$blockA = module_invoke('block', 'block_view', 1);
$blockB = module_invoke('block', 'block_view', 2);
return $blockA['content'].$blockB['content'];


search from modify html output im having problems to modify html of drupal search form. Currently it looks like this:
<form action="/" method="post" id="search-block-form--2" accept-charset="UTF-8">

        Recipe Finder
        <input title="Enter the terms you wish to search for." placeholder="Search" type="text"
               id="edit-search-block-form--4" name="search_block_form" value="Search" size="15" maxlength="128"
               class="form-text">

        <input type="submit" id="edit-submit--3" name="op" value="GO!" class="form-submit">

    <input type="hidden" name="form_build_id" value="form-eHe5OqwUBJ_6iNuySpN1domgBeOYb4utKirLlh58QHY">
    <input type="hidden" name="form_token" value="ADv5U92njeULDgBszbJ6nDHTaGTxTEJMCCL2Qk3SAMk">
    <input type="hidden" name="form_id" value="search_block_form">

and i need something like this:
<form action="/" method="post">

                Recipe finder
                <input type="text" name="search" class="search" id="search">
                <button type="submit">Search</button>

        </form>

So i need to:

Change input to a button

Put that button in same div as input and label
I dont mind having this invisible elements and i know drupal needs them.

I know i need to use hook_form_alter for this but not rly sure how to do it.

I wanted to do the same thing and after struggling with all kind of hooks/theme functions, I finally found a solution directly inspired from bootstrap.

Here the 2 links of bootstrap implementation:

bootstrap_form_alter
bootstrap theme function

And for my purpose, I've created a custom module to implement a custom search block.
So in MYMODULE.module file, I've put:

/**
 * Implements hook_theme()
 */
function MYMODULE_theme() {
  return array(
    'MYMODULE_search_form_wrapper' => array(
      'render element'  => 'element',
    ),
  );
}

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    //other implementations in themes/MY-THEME/template.php
    $form['actions']['submit']['#attributes']['class'][] = 'element-invisible';
    $form['search_block_form']['#theme_wrappers'] = array('MYMODULE_search_form_wrapper');
  }
}

function theme_MYMODULE_search_form_wrapper($variables) {

  $output = $variables['element']['#children'];
  $output .= '<button type="submit" class="btn-foldingsearch">';
  $output .= t('Search');
  $output .= '</button>';
  $output .= '';

  return $output;
}

Anyway, you'll have to adapt it to your configuration. Hope it helps.


Using drush to install multiple sites, how? I'm executing the following commands in /var/www/html on a clean Ubuntu 14.04 installation:

drush dl --drupal-project-rename=Platform
cd Platform
drush site install standard -y --db-url=[mysql connection string]/drupal --site-name=Example1

This sets up the site and it's awesome (especially after fighting for two days with the web interface and silly errors).

But now I want to install a 2nd site on this installation:

drush site install standard -y --db-url=[mysql connection string]/drupal2 --site-name=Example2

I get an exception that says, "To start over, you must empty you existing database. To install to a different database, edit the appropriate settings.php file in the sites folder. To upgrade an existing installation etc. etc.".

Is it still trying to install to the original database, thus the reason why I'm getting this error? I created drupal2 prior to running this command, so there's an empty database that exists.

How would I go about fixing this error?

Is it possible to use 1 database for all sites with crush?

Edit: Creating a subdirectory in sites and using the --sites-subdir option in the site install command seems to have worked. Not sure how to point my browser to the site or how to use one database yet, but baby steps!

If you want to use 1 DB for multiple sites you should get https://www.drupal.org/project/domain. I haven't tried it yet, looks complicated to set up, so good luck =)

For pointing your site, this video might help, skip to 15:49 http://www.youtube.com/watch?v=Ea_Tqd-NrC4 It doesn't cover diff root directories for diff domains tho.


Alter Existing Route - Bypass/override entity permission I added a custom access check to a JSON API endpoint so that only users who provide a token can POST/PATCH updates on a media endpoint.  I followed this documentation in order to alter an existing route using RouteSubscriber:alterRoutes() and a custom access check.

Everything is working properly with my custom access check.  I have a custom condition which will either forbid or allow access based on a condition:

public function access() {
   $valid = $this->validateToken($token);

   if ($valid) {
     $access = AccessResult::allowed()
   } else {
     $access = AccessResult::forbidden('The access token is invalid');
   }

   return $access;
}

If the user does not fulfill the appropriate condition, then access is denied through my custom access check.

However, if the custom access check allows access, the default entity permissions are still being applied.  I get a 403 Forbidden error saying:

The current user is not permitted to upload a file for this field. The following permissions are required: 'administer media' OR 'create media' OR 'create [machine_name] media'

When I allow access, I want whichever user who provided the correct token to be able to create a particular entity (including anonymous users).  How do I override the entity permission system so that whoever fulfills the condition has access to create the entity?

Can I dynamically add the permission to this user to create this particular entity for just this request?

Right now in my alterRoutes() function I am setting a requirement for my _custom_access.  Do I also need to set an additional requirement for _entity_access or _entity_create_access?

Drupal uses both route access and entity access. You need to add your access check in hook_entity_access() because the media entity module is denying create access. Use route access for non entity pages.


Media: Specify display used for File field on content type's Manage Display tab I'm using the Media module (7.x-1.0) to support images and videos. According to the latest best practices I've been able to find, you're supposed to use a File field on your content type to display the media. For example, add a field called "Media" of type File to the Article content type, then use the "Media file selector" widget.

That part is fine, but I'm struggling to actually display the attached file. On the "Manage Display" field for the Article content type I only have four options (shown below). None of these map to any of the display modes defined for File entities (via the File entity module included in Media 7.x-1.x).

I've looked through the issue queue for Media and found some similar questions, with no solutions. There appears to have been a "Media" formatter available for the now deprecated "Media Asset" field type which allowed you to choose which File display mode should be used. This isn't available for the File field type, which is what Media recommends you use.

Has anyone been able to successfully choose a File display mode for a File field using the Media module?


Get view machine name programmatically I am using a code

<?php
print $view->display['view_machine_name']->handler->options['title'];
?>

I put machine name in view_machine_name and everything work but I have few displays with different machine names and in other cases I still print same title. Can I get a function which takes the view machine name?

You can try views_get_page_view() function, Which return Views object and you can get current views name on  $views_page->name


print out multiple values of a taxonomy field In a taxonomy I have some fields for the terms. To print out 1 of these fields in a node.tpl I found this code:

<?php $term=taxonomy_term_load($node->field_hotel_tx_atmosphere['und'][0]['tid']);
$result=field_view_field('taxonomy_term',$term,'field_tx_headline','text');
print render($result); ?>

But this way I get only the first value - there are multiple terms selected.

How can I get all selected terms printed out?

0 in $node->field_hotel_tx_atmosphere['und'][0]['tid'] means that you are taking only first term so you should loop through array to get all terms.

I recommend entity_metadata_wrapper (available with Entity API module):

$wrapper = entity_metadata_wrapper('node', $node);
foreach ($wrapper->field_hotel_tx_atmosphere->getIterator() as $delta => $term_wrapper) {
  // prepare and render field value:
  $result = field_view_field('taxonomy_term', $term_wrapper->value(), 'field_tx_headline', 'text');
  print render($result);
}

or build a View to display selected data in the right way.


Unable to set file upload destination private when programmatically creating new content type with file field I am creating a module to upload video to an in house media converter - as part of the module installation I create a new content type called "user video" which has a file field as part of it.

I need to set this file field so it saves to the private files directory, however I am unable to do so. I can create the content type and add the file field - but never manage to get the upload destination to be private.

Sometimes I am able to change this via the admin interface, but sometimes this option is greyed out.

I have included the code below and would be grateful for any assistance.

//Create the file upload for the video to be converted
  $field_name = 'uploaded_video';

  //  Create the field definition array.
  $field = array(
   'field_name' => $field_name,
  'type' => 'file',
  );

  $field = field_create_field( $field );

 //  Create the field instance definition array.
  $instance = array(
      'field_name' => $field[ 'field_name' ],
      'entity_type' => 'node',
      'bundle' => 'user_video',
      'description' => 'A field for uploading video and audio content.',
      'label' => 'Video to upload',
      'settings' => array(
          'file_extensions' => 'mp4 avi wmv qti mov',
          'uri_scheme' => 'private',
          ),
      'widget' => array(
          'type' => 'file',
      ),
  );

//  Create an instance of the field and bind it to the bundle.
field_create_instance($instance)

If your issue is that the radio buttons are greyed out when trying to select the 'private' folder.

I needed SQL access for this one;  I emptied the SQL table that relates to the field that stores the images.  In my case deleting all items was not enough and I need to manually remove all rows from the table and then put them back after the next stages.   in my case table field_data_field_upload_private files .


Menu subitems only displaying on a single page I have several menu items in our main menu, and each of them has several sub-items. All of them display correctly EXCEPT one - this particular menu only displays the top-level menu item, unless you're actually on the page that the top-level item links to - then it displays all the dropdown sub-items.

The only difference in the non-working menu is that the sub-items link to external sites, rather than internal pages.

Here's the menu setup:

The Featured Exhibitor menu works - i.e. the dropdown displays on all pages. The Contact menu doesn't work - on all pages, all you see is the top-level Contact link. When you click that and are taken to /contact, the menu suddenly displays all the dropdown links. Because the sublinks are to external sites, there are no issues with node permissions or anything, and even if there had been, at least things would have been consistent (they wouldn't have displayed anywhere if the user didn't have access.)

Here's the menu displayed on /contact:

We've tried switching the theme to see if there was something funky about ours, but it does the same thing no matter what template we try. Any idea what would cause this?

EDITED TO ADD

When I look at the rendered source, the subitems of the contact menu are not included on pages other than /contact. So it doesn't seem to be a style issue.

So it turns out that the particular theme we're using relies on the Show as Expanded option on the top-level menu items to determine that it should display as a fly-out.


How do I deal with discounts/refunds and a payment gateway to achieve accurate reporting for accounting? First off, this seems like a fairly basic function required for ecommerce.

I was presented with a question today:

  "Will our new website give reporting so accounting can be done from within the website?"

The answer: "Yes! With Commerce Reporting module and Views."

Then came the followup question:

  "Great! So we will be able to add partial refunds, full refunds and discounts to existing orders within the site, have our payment gateway (PayPal) receive the discount/refund requests and have all of this show up in our reporting exports?"

The answer to that: "UMMMMMMM........"

Simple example: Customer purchases two items. Item #2 was a mistake. Customer requests a refund via good old fashioned email. We are presented with a question: Does the refund get issued from within Drupal Commerce or within the payment gateway?

What are the solutions for dealing with this?

Does the company still have to rely on the payment gateway (and its ever-changing, unstable export features) for reporting? If so, how does Drupal account for any changes made to an order (i.e. refunds, manual discounts)?

If not, how do I set up Drupal Commerce to get the reporting accurate to include refunds and any line item price corrections?

Step 1 - Enable Commerce RMA
First of all, you need to get something in place to enable the tracking/registration of such refund requests within the Drupal Commerce ecosystem. For that, the Commerce Return Merchandise Authorization module appears to be the best alternative available today. Some more details about this module (from its project page):

This module aims to extend Drupal Commerce with the Return Merchandise Authorization functionality. It's built on top of the nice Entity API library and using its own Entity Type (CommerceReturn).
Feature list:

Exposes a return of goods workflow on customer side.
Ability to separate products that can and cannot be returned
Ability to specify a return period, after which the ability to create an RMA is not available.
Provide an Admin UI to manage customer returns. Admin can remove or add product and change the prices of returned product.
Ability to customize the customer reasons on both product and product type levels.

Step 2 - Create custom Rules reacting to Rules Events about a CommerceReturn
By using the Commerce Return Merchandise Authorization module, you'll get the CommerceReturn entity types available. And because of those entity types, it opens up all sorts of custom business logic you may want to implement by using the Rules module. That will allow you to build custom rules that react on the typical entity-related Rules Events, such as:

After deleting a CommerceReturn.
After saving a new CommerceReturn.
After updating an existing CommerceReturn.
Before saving a CommerceReturn.

Step 3 - Create custom Views about CommerceReturn entities
As per those CommerceReturn entities, you also get out-of-the-box reporting (and even charting ...) capabilites by simply using the Views module. So for anything that is not already covered by Commerce Reporting, just create the required custom Views.
Step 4 - Create work-arounds for payment gateway limitations
I'm not aware of any solutions to also automagically take care of the payment gateway processing for such refunds. Especially because I think that there is no way to refund part of a transaction.
However, if you have the Rules module available (see above), you might create custom rules with Rules Actions that (eg) transform such CommerceReturn entities in (e.g.) User Points (piece of cake), so that they can be used to get discounts on future transactions.
Summary
The above is not a perfect/complete solution, but at least an improvement as compared to the  "requests of a refund via good old fashioned email" (as in your question). Actually it would at least keep track of such outstanding refunds to be processed.
PS: I'm assuming this is about D7.


After module installation, updating translations still at 0% I installed Drupal 8.5.6, in French. It seemed to work well, apart from no CSS working, but I corrected by unchecking CSS aggregation in the performance settings.

I decided to install some modules, one by one. Every time I install a module, after I click on the Install button, I get this.

After waiting more than 2 minutes (which is abnormal to me), I click on the Extend link to see if the module I am trying to install has been installed. The module seems to be installed, since it is checked, but it is not working.

So I uninstall that module, and try installing another module, but I get the same result.

Notice that the first modules I tried installing were the Coffee and Admin Toolbar modules. They get installed properly offline.

I have also noticed that using Drupal 8.2.5 everything is fine.

Is there any version problem, or am I doing something wrong?

I changed the PHP version using on the host to PHP 7.1.

After a few time doing something else, I went back to the issue. In fact a lot of JavaScript was not working correctly.

Then I decided to go back to Configuration -> Performance and unchecked JavaScript aggregator and saved that configuration. See the image below :

Now everything works fine!!!

Now I can use admin toolbar's dropdown menu as well as coffee and all the other stuff is working well.

And thank you for reading me.


How can I distinguish the first image in an image field in a Twig template? I have a custom field formatter for an image field. The Twig template for the image field is the following:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Each image is then formatted by the following template:

But what I want to do is to format the first image of the field in a different way. I found how I could change the for loop in the template and use loop.first to treat the first image differently. But the formatting I want to change is in the inner template that formats each image, the one I call with item.content. In the outer template for the entire image field I can distinguish the first image, in the inner template I have no idea how to check for that or how to transfer that information from the outer to the inner template.

Any idea on how I can solve this and format only the first image in a different way?

This code in a node.html.twig template will display only the first value of an image field that has multiple values:

{{ content.field_yourfieldname.0 }}

This will only display the second value:

{{ content.field_yourfieldname.1 }}

Source

Edit: apparently that wasn't really the question, my apologies.


How to disable one specific translation page? How can I disable only one page in English on a Drupal 7 site, without disabling the Danish page?

I'm using Multilingual - Internationalization module.

Since translations in D7 are new nodes, you can simply Unpublish the English node, while keeping the Danish one Published.


Remove search form from search results page I have a search box in a sidebar and I'm happy with it. I don't want Drupal to output another one on the results page. So far I've managed to remove it with the following code

function mythemename_preprocess_page(&$variables) {
    if(array_key_exists('page', $variables)) {
        if(array_key_exists('content', $variables['page'])) {
            if(array_key_exists('system_main', $variables['page']['content'])) {
                if(array_key_exists('search_form', $variables['page']['content']['system_main'])) {
                    unset($variables['page']['content']['system_main']['search_form']);
                }
            }
        }
    }
}

but it doesn't look very clean to me. Is there another way?

Write a form alter:

function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "search_form") {
     $form['#type'] = 'hidden';
  }
}


Multi-layer views results I'm not quite sure how to explain this but here goes. I want to have a link to a view that displays a collection of categories i.e. t-shirts, jeans, socks, sunglasses etc. I then want to (for example) click on t-shirts and be prestented with a list of all links to items/nodes that are t-shirts. Is views able to do this 2 tier result?

Yes, you can do this with a Contextual filter in Views.

Create a Content View of your desired nodes, then add a Contextual Filter (I'm assuming your categories are actually Taxonomy terms referenced from nodes) for the Field with that Taxonomy reference.

Configure it with these options:
    When the filter value is NOT available
    Display a summary
    Format List
    Base path (you must enter the Page path if this isn't the first Page Display in your Views)
    Display record count with link
    More
    Transform spaces to dashes in URL

This way you get a list of term IDs that link through to a list of nodes tagged with those terms.

You probably want the term name to be displayed instead of the term ID. In that case remove the Contextual filter, we'll add the one for Taxonomy term Name, but we need a Relationship first for that information to become available.

So add a Relationship Taxonomy term referenced from field_category (or whatever the field is called in your case), require it if you don't want summary results without a category.

Then add a Contextual filter Name from Taxonomy term Category, it will use the Relationship we created, and configure it like above.


Display edit link for a node in a view when user has permission I have a view displaying fields from one node.

Is it possible to display a link for a user to edit the node if they are logged in and have the appropriate permission to edit?  Something similar to the tabs with edit displayed for a regular themed node would be nice.

In Views, there is a field you can add called Node: Edit link that will display a link to the edit page for the node, taking into account the user's permissions.


How do I invoke token substitution with Pet? I have to send some emails in a custom Drupal 7 module.

I'd like to use the PET module (Previewable email templates) to manage the templates and drupal_mail() to send emails because it already uses SwiftMailer to send emails.
The problem is that the body of the email I get from Pet has some tokens that I should replace before the email is sent.

How can I replace them?

This is the code I'm using.

$pet = pet_load('test1');

$params['format']= "text/html";
$params['charset']= "UTF-8";
$params['email_subject']= $pet->subject;
$params['email_body']=$pet->mail_body;

///$params['email_body']= <body with token replaced>

drupal_mail('myLib', 'customNotifications', 'xxx@gmail.com', language_default(), $params);

I've solved in this way:

// SOSTITUZIONE TOKEN DRUPAL
$l_oPetTemplate = pet_load('test1');
$l_TemParams2['pet'] = $l_oPetTemplate;
$l_aSubstitutions = pet_substitutions($l_oPetTemplate, $l_TemParams2);
$l_aEmailParams['email_subject'] = token_replace($l_oPetTemplate->subject, $l_aSubstitutions, array('clear' => TRUE));
$l_aEmailParams['email_body']=token_replace($l_oPetTemplate->mail_body, $l_aSubstitutions, array('clear' => TRUE));


I can't change the currency to € for the Drupal Commerce module I can't change the currency to €.

In admin/commerce/config/currency I set the currency to €. (see capture 1)

But the products still show the $ simbol.(see capture 2)

Is this a bug?

As StryKaizer commented I need to change it as well in every product. My problem is that I have many products. Is there any way to do it in the database through a query?

I've experienced this bug myself in an older version of Commerce.
Updating to the latest stable version of Commerce fixed the issue.

Also make sure to change the currency on your product(s) too, as changing the global currency won't change it on any already defined products.


Integer field type missing I am using Drupal 7.12 and are missing the field type "integer". I only have the fields

Boolean
List (Text)
List (Float)
LIst (Integer)
Long Text
Long Text and Summary
Node Reference
Text

Maybe I am overseeing here something very basic, but it should be there AFAIK.

Thx for help,

n3rd

Check and see if the core module "Number" is enabled. It requires the Field and Field SQL storage modules to be enabled as well.


How to sort nodes per domain with the Views module? I have to display nodes in different order(weight) inside a view per domain on a multi-domain site.

example:

on domain1: view-beverages => 1-Coca Cola, 2-Perrier, 3-Redbull, 4-IceTea ...
on domain2: view-beverages => 1-Perrier, 2-IceTea, 3-Redbull, 4-Coca Cola ...
...

I thought to use the module Flag Weights, but Flag is per user and not per domain.

Do you think I can do this by using "Draggableviews"?

Can I create a table view for each domain with Draggableviews to manage the order of the node by domain, and make the final display view chose automaticaly the "sort criteria" (Draggableviews : Weight) of the courant domain. I hope I am clear enough.

How can I do this, or there is an alternative?

You are right: Best ot achieve ordering in views-lists is indeed draggableviews. But beware that this doesn't work with all styles. I am not sure, since it is half a year ago I have needed it for a project, but I think draggableviews is made for tables in mind. But as far as I remember there was an additional module making it possible also for other listing styles.

But the rather real problem is not how to order the views list items. The problem is that you need 2 almost same but a little bit different views (page-views? or block-views?), and how to let the 2 views show up on 2 different domains. I assume you would like to have the kind of same page on the same path but on two different domains in two different orders. The problem here is, if you try to achieve this with overriding paths by 2 different views and different domain conditions, the filtering or conditioning of the view depending the domain will make some trouble... It will always try to load both views and will always take the first arriving and if the condition doesn't fit, it will not change to the other. This is not a bug. It is because of how overriding paths works.

Let me know if you have any idea how to achieve this last part. Maybe I can help then on some further steps on it. But in the moment I see the end of the road here.


Add property to ProductVariationType via hook_entity_type_build() Hy guys,

I'm trying to implement a simple stock management in my e-commerce. The ProductVariation will have a stock_quantity field used to track product availability.

I would like that stock_quantity field is shown only if user checks an enable_stock_management checkbox on ProductVariation bundle edit page. I.e. /admin/commerce/config/product-variation-types/default/edit

In other words I would like to mimic Submission form settings, Menu settings, Display settings functionalities of Node's bundles.

By Google-ing a bit I think that hook_entity_type_build() is the hook to use. But, once I'm in the hook what I'm supposed to do in order to add the property I need and display it in the edit form?

 /**
  * Implements hook_entity_type_build().
  */
 function commerce_warehouse_entity_type_build(array &$entity_types) {
     /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
     $entity_types['commerce_product_variation_type']-> # ... And now?;
 }

Ends up that hook_entity_type_build() is not the right way to implement what I want. I found a solution usign ThirdPartySettingsInterface, which every ConfigEntityBase implements.

First I've altered ProductVariationType form via hook_form_alter() in order to add a checkbox to the form and register a new #enity_builder.

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MY_MODULE_form_BASE_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var ProductVariationTypeInterface $entity */
  $entity = $form_state->getFormObject()->getEntity();

  $form['warehouse_management'] = [
    '#type' => 'checkbox',
    '#title' => t('Enable warehouse management'),
    '#default_value' => $entity->getThirdPartySetting('commerce_warehouse', 'warehouse_management'),
  ];

  $form['#entity_builders'][] = 'MY_MODULE_entity_ENTITY_ID_builder';
}

Then I've defined my custom entity builder function where I register my third party setting. Pretty simple! This article helps me out a lot.

/**
 * Entity builder for commerce_product_variation_type entity.
 */
function MY_MODULE_entity_ENTITY_ID_builder($entity_type, ProductVariationTypeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->setThirdPartySetting('commerce_warehouse', 'warehouse_management', $form_state->getValue('warehouse_management'));
}


Is there any way to "linux nice" a process to have less priority We have some high resource views that would have less impact on the overall performance if they ran at a low priority, e.g. linux nice'd to a low priority.

Well...

This is rather complicated to solve and probably not suitable for all available configurations. Given you don't reuse processes and the given php process terminates at the end of the request you can use proc_nice().

Next thing will be to be at the right spot to nice the process, does the heavy loading occur before executing? while executing? Also nicing the php process probably won't take any load of the mysql server or whatever other backend this process is requesting.

Looking at view::execute there's no way to distinguish at this point between cached views and uncached ones - so going that route we also have to nice processes which have a cache - probably something to think about.

Drupal 7 Implementation using hook_views_pre_execute().

/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(&$view)) {
  if($view->name=="machine_name_of_my_view") {
    // http://php.net/manual/en/function.proc-nice.php
    // Setting something higher would lead to idle only processing.
    // Please refer to the documentation of proc_nice and nice.
    proc_nice(9);
  }
}

Drupal 8 implementation using hook_views_pre_execute():

/**
 * Implements hook_views_pre_execute().
 */
function views_pre_execute(ViewExecutable $view) {
  if ($view->id() == 'machine_name_of_my_view') {
    // http://php.net/manual/en/function.proc-nice.php
    // Setting something higher would lead to idle only processing.
    // Please refer to the documentation of proc_nice and nice.
    proc_nice(9);
  }
}

Keep in mind that this solution requires quiet some constraints to work for you:

Heay load is actually in the php layer
proc_nice() is available (not all environments allow this)
dedicated php processes which terminates at the end


Mobile_Detect.php and Drupal How might I make use of this Mobile Detect php class in a D7 site? Rather new to this so I'm really not sure where this can be implemented.

I wrote a module to do just that, Mobile Detect:

  This is a lightweight mobile detection based on the Mobile_Detect.php
  library, which can be obtained from the GitHub repository.

  This module is intended to aid developers utilizing mobile-first and
  responsive design techniques who also have a need for slight changes
  for mobile and tablet users. An example would be showing (or hiding) a
  block or content pane to a particular device.

  This module is not intended (and never will be enhanced) to provide
  theme switching or redirection; other modules already provide this
  functionality.

There is also Context Mobile Detect:

  This is a Context module which integrates Context and PHP Mobile
  Detect library Mobile_Detect.

  Module preserve drupal page cache working.

And you can check out Mobile Switch:

  The Mobile Switch module provides a simple automatic theme switch
  functionality for mobile devices, detected by Browscap or Mobile
  Detect.

These all serve slightly different audiences.  Pick the one that best fits your needs.


Are blocks still cached when "Cache block" setting disabled but "Cache pages for anonymous users" is enabled? I have a site which contains a custom block.  The custom block contains a menu based on a sub-set of the site's main menu.  The problem is that main menu is very large (~1300 items), so generating this particular menu in the block, is quite costly. According to hook_block_info() the block is configured to use DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE caching methods.

If I go to the site's performance configuration page I notice that the "Cache block" option is disabled; However, the "Cache pages for anonymous users" option is enabled.

In such a situation would the block be cached or not? If it is cached, then would that only be for anonymous users?

TL;DR yes

Well, not per se. But page it appears on is cached, including that block. There is no separate item for the block in any cache in situation you described, but it won't be recreated anyway. Code for it won't be executed. And yes, in default Drupal configuration page caches works only for anonymous users.


Why is jQuery .focus not firing? In the code below, the first alert() fires, but the second one never fires when I click the textfield assigned with the 'clear' class.

Does anyone have a clue why this happens?

(function ($){

   alert('TEST 1');
   var clearMePrevious = '';

   // Clear input on focus.
   (function ($)('.clear').focus(function() {
     alert('TEST 2');
     /*
      if ($(this).val() == $(this).attr('title')) {
        clearMePrevious = $(this).val();
        $(this).val('');
      }
      */
    }(jQuery));

}(jQuery));

The problem is just in the inner code, as $document.ready() fires the TEST 1 alert.

I have tried different variations of (function ($){}); and function (jQuery){});.

Your formatting made me twitch, so I fixed it up for you.

Drupal JS Coding Standards

Also you weren't using a behavior, so I fixed that too:

Javascript in D7

(function ($) {
  Drupal.behaviors.textFieldClearer = {
    attach: function (context, settings) {
      var clearMePrevious = '';

      // clear input on focus
      $('.clear').focus(function() {
        if($(this).val() == $(this).attr('title')) {
          clearMePrevious = $(this).val();
          $(this).val('');
        }
      });

      // if field is empty afterward, add text again
      $('.clear').blur(function() {
        if($(this).val() == '') {
          $(this).val(clearMePrevious);
        }
      });
    }
  };
}(jQuery));


Block cache depending on current node and its last modification time I am building a module with a block that outputs some informations from the current node.

When i return my render array i managed to get the cache as "node dependent" using (maybe not the best method ?) :

        '#cache' => [
            'contexts' => [
                'url',
            ],
        ],

The blocks are showing up the right contents on the right pages, but if i modify my node and it's fields, the block content remains pulled from the cache and is not updated with the latest values.

Is there anything to add in the #cache array or a way to invalidate this specific cache when node gets updated ?

See my answer to a similar question here: Passing current node ID to the block template

In short, use the plugin context system to get the current node injected. It will automatically ensure that the right cache tags and contexts are added, based on where node is coming from.

Depending on what information you need exactly, you could also consider using the default entity view blocks provided by ctools. That allows you to view the node in a given view mode.


More multiple add to cart buttons drupal commerce I want to be able to have multiple add to cart buttons on 1 page for example for selling music like this. Example!

It appears that you're looking for something that is decribed in detail in Multiple products per Add To Cart form (product kits/packages) also.
And that issue is what was the inspiration for the Commerce Product Bundle module (available for D7, but only as an alfa version for now). Here is a excerpt from its project page:

You can define products that consists of other products. They are all combined in one add to cart form. The form works like the core add to cart form with all the fancy selection and ajax magic. So the customers can make their selections as usual. The difference is, that the products from mulitple reference fields were presented on one add to cart form.
The bundle is then represented by one order line item. This allows the maximum compatibility with other modules such as shipping or payment modules.


access the node id of a field collection How do I access the node id of a d8 field collection that is attached to the node in  hook_preprocess_field(&$variables)?

It works for me. You can do it as follows-

/**
 * Function hook_preprocess_field.
 */
function [theme_name]_preprocess_field(&$variables) {
  if ($variables['field_name'] == [FIELD_COLLECTION_NAME]) {
    if ($variables['element']['#entity_type'] == "node") {
      $node_id = $variables['element']['#object']->id();
      //Rest of the code.
    }
  }
 }

Hope it works for you too.


Change the number of returned results in a taxonomy item list? Clicking a taxonomy term in a Node leads to a URL like taxonomy/term/7 with a list of nodes with that taxonomy term. However, my Drupal installation is only showing 3 nodes/page in that list. Is there a way to customize the number of results the default taxonomy term search shows?

The Views module has a default View for that page. If you enable it you can adjust it the way you want like you would normally do with Views.

Without Views: see comments.


node_view not picking up view mode, always printing full I have the following code:

$form['commerce_fieldgroup_pane__group_event_information']['field_event_information']['und'][0]['#markup'] = drupal_render(node_view($eventInfo['event']), 'teaser');

and for some reason, its printing out the node fine, but not printing the correct view mode, its always using full.

I think you have a misplace parenthesis.  You have

$form[...] = drupal_render(node_view($eventInfo['event']), 'teaser');

The view mode should be a parameter to node_view() and not drupal_render():

$form[...] = drupal_render(node_view($eventInfo['event'], 'teaser'));

As a side note, I don't think you need to explicity render the node and stuff it into a #markup.  node_view() returns a render array with a #theme already defined, so you should be able to do:

$form['commerce_fieldgroup_pane__group_event_information']['field_event_information'][LANGUAGE_NONE][0] = node_view($eventInfo['event'], 'teaser');


Connect Content Type with Related Taxonomy Fields using Template I have a Content Type displaying correctly using a template, pulling out the fields to appropriate locations.

I now want to pull in related information from two separate taxonomies. I have a term reference to each Taxonomy setup as a field in the Content Type.

I have the taxonomy fields mapped out in the template, but the output is empty. I believe it is because I need to define a relationship somehow.

My current direction is to create out a view using EVA and render it to the template (which is poor for performance), but I am struggling to figure out how to define the relationship to the node.

Please provide examples of how you would approach this problem.

For context, Content Type is a job listing. Taxonomy B is information about the respective company. Taxonomy C is information about the respective city the job is in. Both Taxonomies can be made into Content Types if that helps.

I solved this by creating two new regions in my theme underneath Content, then I created a View with two blocks: one for taxonomy B and one for taxonomy C.

The view pulls in taxonomy fields using the relationship: Content: Taxonomy terms on node.

I have setup the URL pattern for my content type to be contentTypeA/taxonomyB/taxonomyC. By doing this, I was able to reference the correct term by using a Contextual Filter: Content: Has taxonomy term ID.

The Contextual Filter was a little tricky for me. As it was coming from the URL at a specific level of the path, I found that I could access taxonomyB through the path component 2, and taxonomyC through path component 3.

Under WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED I used Specify validation criteria as the respective taxonomy term.

Finally, using Term name converted to Term ID allowed it to see the plain english term name in the URL path.


Building a Views Filter I want to build a filter for a custom module I built and have integrated with views. In essence, the module allows you to define types of relationships between different nodes. I'd like to create a filter for this so that I can display nodes of a certain type of relationship.

I'm not finding any documentation that describes filters in more detail and explaining the various parts to them. The API documentation is horrific in this regard.

Can anyone suggest a good resource/article on building View Filters in detail?

Have you tried http://views-help.doc.logrus.com/ or the advanced help module?

Edit::
Unfortunately there is no deeper documentation that I know of. I wrote a custom field handler and got most info from other handlers that came with views. I would recommend looking at the views/handlers directory, especially all files beginning with 'views_handlers_filter_'. At least that is what I did.


Can I run a site on AWS Elastic Beanstalk for PHP? I'm looking at AWS Elastic Beanstalk.

Does Drupal 7 run on AWS Elastic Beanstalk for PHP?

Any extra info regarding caching and performance (e.g. comparison with PressFlow, or Memcache) is welcome.

Yes, we are currently running site build on Drupal 7 on AWS Elastic Beanstalk for PHP.

I am strongly recommend to install and configure memcache for best performance.
PressFlow is not required replacement for standard Drupal 7 core (but for Drupal 6 is).

Also sites/default/files folder must be mounted from S3 bucket (read here how to manage it https://sites.google.com/site/truthkos/home/tutorials/amazon-web-services/working-with-ec2-instances/setup-a-s3-connection-to-ec2-instance-via-fuse)

For anonymous user Varnish will dramatically increase site performance.


On account creation, the message is not displayed I try to register in my site; after a successful registration, I get redirected to the home page, but the following message is not displayed.

  Thank you for applying for an account. Your account is currently pending approval by the site administrator.

  In the meantime, a welcome message with further instructions has been sent to your e-mail address.

The standard core mail functionality is used, and no hook or rule is used for that registration.

Why doesn't the message appear?

I tried changing theme, but the message is still not appearing. Furthermore:

The $message variable is available in the template file
I am not using the Boost module; I am using the Mime Mail module to get HTML emails

How do i customize the message in some hooks?

A workaround would be to manually create message in hook_user_insert, with code like:

function mymodule_user_insert(&$edit, $account, $category) {
  drupal_set_message(t('Account created, wait for approval.'), 'status');
}

Alternative place is hook_entity_insert:

function mymodule_entity_insert($entity, $type) {
  if ($type == 'user') {
    drupal_set_message(t('Account created, wait for approval.'), 'status');
  }
}

Problem is - it is possible that the same error will hide this one too. Benefit: it's easier to experiment with small custom hook, than to debug core.


Search results issue I am using the drupal's built in search module, for this I have copied the search-results.tpl.php in my theme folder. Now I have to add images for search results too and also want to custom theme the template file. For images I have used the following approach:
In my template.php:

function MyTheme_preprocess_search_result(&$variables)
{
if ($result['node']->type == "content_type") {
 $node = node_load($result['node']->nid);
 $prod_image = field_view_field('node', $node, 'machine_name_img', $display = array());
 $variables['image'] = $prod_image;
}
}

and then in search-result.tpl.php:

<?php if($prod_image):?>
    <?php print render($prod_image);?>
<?php endif; ?>

but its not working, can anybody knows how do I get the images related to search results, and how can I theme search results?

You're using the wrong var name. In your preprocess function you're using $variables['image'] = $prod_image; to set the var. Whatever element name you use in the the $variables array will be the name of the var in the template. So in your case it should be:

<?php if($image):?>
    <?php print render($image);?>
<?php endif; ?>


How to specify Google Chart API options for altering generated charts when using the views integration? I have a series of pie charts being displayed through Views and the Views Dataviz module. I've also experimented with other chart modules that use the (interactive) Google Charts charting engine.

When these charts are generated through their integration with the Views module, I wonder how I can alter the chart output by using the options in the Google Chart API (options such as colour, legend, font size, etc).

I've looked in the code of individual charting modules, but I'm not sure where I can customize the output of the charts.

Finding an appropriate charting module

To create charts in Drupal, consider the Comparison of Charting Modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the modules mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module (confusing names, I didn't invent them). Though there are other alternatives in that comparison that might be a better fit for this specific case.

Selection criteria

The license that comes with the related charting library (engine) in each of these modules, should be considered also (open source or not, license fee, etc). It is one of the (important?) selection criteria for deciding on the module to go for.

Some other typical items to consider are:

Possible privacy concerns.
Yes or no support for saving charts in PDFs (usually supported by PHP based libraries, and not supported by JS based libraries).
Flash based libraries should be avoided if charts are to be displayed on mobile devices.
Some libraries (like the Google flavors ...) require a working internet connection (not always available in local DEV environments ...).

Available options specific to the Charts module

The Charts module is possibly one of those "other charting modules" that you experimented with. For the Charts module, the currently closest answer (solution?) you can find is described in issue #2209467. And the closest solution to get this to work, is as described in comment #4 (which also includes an interesting patch). Be aware of the current status of that issue, i.e.:

the patch only works for Highcharts (as charting engine), the Google Charts counterpart of it is still missing (and prereq for adding this feature to the Charts module).
it is related to the Charts API (which is different from the Views integration). So after the Charts API feature gets delivered, some more (minor?) work is needed to also make it available within the Views integration of the Charts module.

So only considering the Charts module as an alternative, and applying the suggested patch is not sufficient. But at least it should help somehow to understand what the missing pieces are. And maybe inspire somebody to submit 1 (or more) additional patch(es) to make it complete?

Disclosure: I'm the author of the comparison and charting modules mentioned above, I hope this does not violate the site's policy on self-promotion.


How to use Rules to limit the number of searches to pull data from a remote API? I have a custom views query plugin that pull data from a remote API.
I use this plugin to save all information so user don't have to enter all details anymore.

User inputs value to search filter and all mapped data is displayed on the page.

I want to limit the number of attempt allowed to a user of 3 searches every 24 hours. So in a day, user can have 3 attempts to make a successful query of data from the remote api. Then, there might me a warning message that appears on the page after those failure attempts. Each day is equivalent to a calendar date.

$vats is where user input value is set in the view search filter. This value is an integer.

$vats = isset($filters['vat']) ? $filters['vat'] : NULL;
$Vid = $vats[0];

$result = CVRClient::get($Vid, $country, 'Unit Testing');

Here's the path of my view page with arguments:  query/query?vat=12345678, 1st 'query' is the sitename and 2nd is the menu path name.

Can this be achieve by Rules? If yes, I would appreciate if someone can guide me ways to do it.

Preface
You added an interesting comment below your question, part of it is like so:

All users is registered via Keycloak and page will redirect to Drupal site after its successful registration. This redirected page is the custom view plugin created. For users to be able to add its company details. And so users will enter their VAT # to get data from the CVR Register. ...

Followed by this extra comment:

query/query?vat=12345678. First 'query' is the sitename, then 2nd is the menu path name

So you have a relative path like in this example /query?vat=12345678. And therefor the answer to your question (= Can this be achieve by Rules?) is Yes, Si, Oui, Ja ... Read on for more details to guide you ...
Solution
You may want to try the "Rules URL argument" module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

So with that you can use Rules to (let's say) "monitor" the usage of that path by an authenticated user. Some more details about the custom rule you could create for this:

Rules Event: drupal is initializing (sorry, that's probably the only one that you would be able to use).

Rules Conditions (pick whatever fits, and/or mix however you want):

user has a specific role (or the negation of it).
check the current path (verify if it starts with query).
check if URL argument vat= is present.

The only thing left to do is to think of something appropriate for some Rules Action(s) to be performed, knowing that you do have these crucial data available:

the current user who tries to use this path again.
the actual value (=12345678) that was used.

Obviously, at a minimum you'd want to add a Rules Action to perform an appropriate "redirect" if the 3 attempts have been used on the same day already.
You'd have to do some more homework/refinements, but here is a blueprint of a basic solution that could work:

Solution 1 (easiest approach to implement):

Use the Flag module (eg with 3 none-global flags labeled like attempt 1, attempt 2 and attempt 3).
Add a Rules Action to flag the user with the relevant flag (corresponding to the number of succeeded attempts before).
Add an extra Rules Condition to verify that not all flags have been used (with the same flagging date!).

Solution 2 (= my recommended approach, though a bit tougher to implement): Use the Message module to create a custom activity log, to log each event where the actual URL has been used (with success). And improve the Rule above to add a rules condition to count the number of such messages (= custom activity log records) created already in the last 24 hours.

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


Hiding view filter option based on another filter selection I have a view with search criteria and the search criteria looks like below:

Age group(options: new born, toddler, pre-school)
Classroom (options: NA, potty-trained, transition, not-trained) All these filter fields are check boxes.

When I select 'new born' as age-group, all of the classroom options should be hidden/disabled except NA option When I select 'toddler/pre-school' all of the classroom options should show up again except NA option

I am using the below code for doing this:

$('#edit-field-agegroup-value-1').click(function() {
    if( $(this).is(':checked')) {
        $("#edit-field-classroom-value-3").prop('disabled', true);
     } else {
        $("#edit-field-classroom-value-3").prop('disabled', false);
     }
    });

This code is working fine. However, when I submit the refresh button the page refreshes and the disabled fields show enabled again. Any help on how this can be fixed?

Run the check on page page load, not just on click:

 ... wrapped in the usual Drupal boilerplate

disableFilter($('#edit-field-agegroup-value-1'));

$('#edit-field-agegroup-value-1').click(function() {
    disableFilter($(this));
});

function disableFilter(element) {
    if( element.is(':checked')) {
        $("#edit-field-classroom-value-3").prop('disabled', true);
     } else {
        $("#edit-field-classroom-value-3").prop('disabled', false);
     }
}


How to format CCK fields printed in custom template I have managed to print date and dollar amount CCK fields on a custom print.tpl.php template file (associated with the Printer, email and PDF versions module), but they are showing up in a different format than how I have them displayed in the CCK field itself.

The date is showing up like this:  2012-06-01 00:00:00
Instead of like this: June 1, 2012

And the dollar amount is showing up like this: 10000
Instead of like this: $10,000

Here are the code snippets:

    <?php if(isset($node->field_invoice_due_date['und'][0]['value'])) {
          print $node->field_invoice_due_date['und'][0]['value'];
   }
 ?>

    <?php if(isset($node->field_invoice_amount_to_bill['und'][0]['value'])) {
          print $node->field_invoice_amount_to_bill['und'][0]['value'];
   }
 ?>

Can anyone direct me on how I can change those two snippets to output their values in the formats I need?

Thanks!

You'll need to preprocess these elements into the template and format them to the way you want.

Let's take this practical example.  Let's say we have a content type of 'blog' and we wanted to preprocess the same variables as above to be used in the template file...

/**
 * Preprocess variables for node.tpl.php
 *
 * @see node.tpl.php
 */
function theme_preprocess_node(&$vars) {
  if ($vars['type'] == 'blog') {
    if (isset($vars['field_invoice_due_date'][0]['value'])) {
      // Makes June 1, 2012 format from the time provided
      $vars['date_format'] = date("F j, Y", strtotime($vars['field_invoice_due_date'][0]['value']));
    } else {
      $vars['date_format'] = '';
    }
    if (isset($vars['field_invoice_amount_to_bill'][0]['value'])) {
      // you can use whatever function to format the money value, this is just an example.
      $vars['amount_to_bill'] = "$". number_format('%i', $vars['field_invoice_amount_to_bill'][0]['value']);
    } else {
      $vars['amount_to_bill'] = '';
    }
  }
}

if your moving these fields into a custom template, than you can preprocess with this hook as well:

 /**
 *
 * Implements hook_preprocess
 *
 * @param $variables
 * @param $hook
 */
function hook_preprocess(&$variables, $hook) {
  if ($hook == 'custom_template') {
    // do your preprocess magic here, you can find the variables by either dsm() or print_r()
  }
}

then, in the template do this:

<?php print $date_format; ?>
<?php print $amount_to_bill; ?>


Drupal: node_load() in php file - load via ajax i try to load a node in Drupal 7 in a php file, which will be loaded with ajax.

my php file looks like this:

require_once '../../../includes/bootstrap.inc';
$i = 16;
$content = node_load($i);

The include of bootstrap.inc works fine, but this file returns 'PHP Fatal error: Call to undefined function node_load()'. i guess i've read that the function node_load needs the bootstrap.inc file, but it doesnt seems so.

Is there any possible way to use the node_load function right without 'register' a module in drupal - i just want to load a self made php file, which just returns the content of a node - without the template!

Rather than using a custom php file you should attempt to solve the issue "the drupal way" via a custom module or in your template.php... Please see my answer in this question.

It explains how you can add to the original url to change the template (or create a blank template so it is only node data presetned).


How to display configuration updates when deleting fields programatically I am working on a module that adds it's needed fields automatically when you enable it's function  in the UI for specific entity types. It also deletes it's needed fields when you disable it's function for an entity type. (I'm not talking about when you enable the module)
We are doing this with the following on a checkbox form that displays the entity types that can have the function:
foreach ($values['product_variations'] as $key => $value) {
  foreach ($neededFields as $neededField => $data) {
    $field_storage = FieldStorageConfig::loadByName('commerce_product_variation', $neededField);
    if (!$field_storage) {
      FieldStorageConfig::create([
        'entity_type' => 'commerce_product_variation',
        'field_name' => $neededField,
        'type' => $data['field_type'],
        'settings' => $data['settings'],
        'cardinality' => $data['cardinality'],
      ])->save();
    }
    $field = FieldConfig::loadByName('commerce_product_variation', $key, $neededField);
    if (!$value) {
      if ($field) {
        $field->delete();
      }
      continue;
    }

This works fine, except that (from what I understand) Fields API automatically deletes the FieldStorageConfig when the last instance of a field is deleted. This would not be a big deal except when the FieldStorageConfig is deleted programmatically, any view that has these enabled fields will be deleted along with it. Whereas if you delete the fields manually though the UI, the view will just be disabled as this was added in this issue.
Even if I were to address this behavior when deleting programmatically, I would still like to display the message when there are changes to the configuration as we are still removing field instances which can result in the loss of data.

Are you sure you want to delete the field?
This action cannot be undone.

Configuration Updates
The listed configuration will be updated:

Is there an EventSubscriber to display this message, or would I need to copy the source code for this and add it to my module?

As discussed in the comments the solution, in most cases, is to add the field storage to the config/install folder of the module specifying persist_with_no_fields: true.
core/modules/block_content/config/install/field.storage.block_content.body.yml
langcode: en
status: true
dependencies:
  module:
    - block_content
    - text
id: block_content.body
field_name: body
entity_type: block_content
type: text_with_summary
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: true
custom_storage: false

Then the configuration updates will be displayed when the module is uninstalled.
Sometimes the dependencies on the module disappear after configuration saves because Drupal is optimizing duplicate dependencies. Then enforce the dependency for this configuration item. See How to properly manage field types for a content type created by a module?


How to add field to menu I want to add a description field to my menu and and use it in front.

I managed to have a text_format field for my description (in /admin/structure/menu/manage/main) but when I click on save, that field is empty.

function HOOK_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'menu_edit_form') {
    return false;
  }
  $form['field_menu_content'] = array(
   '#type' => 'text_format',
   '#title' => t('Description'),
   '#format' => 'full_html',
  );
}

In hook_form_alter() add a submit function:

$form['#submit'][] = 'my_module_menu_edit_submit';

Where you store the field:

function my_module_menu_edit_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $config->set('main_content', $form_state->getValue('field_menu_content'))
    ->save();
}

The main menu is hard coded in the settings name. If you want this to work for all menus, you can try to get the menu name from the form. I did not investigate where you can get it.

When you build the form field you also need to get the field value from config. More information: https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api


Date Filter Between Date Odd Behaviour Hello i am having problems showing nodes created between '8 days ago and 38 days ago' in my Views filters.

filter Node: Post date: is between
 An offset from the current time such as "+1 day" or "-2 hours -30 minutes"
Min: -8 days
Max: +38 days

Im not getting the required behaviour. if i trim it down to

Min: -3 days
Max +5 days

it seems to be filtering. With my original -8 and + 38 though its showing all the nodes. Am i doing something wrong?

Thanks

I had a similar type of issue and managed to fix it by changing back to "Single Filter" and adjusting the filter value type to what I wanted to use in "Grouped filters" type. I then went back to "Grouped Filter" and my date filters suddenly started working.

Alternatively, you can just delete the filter and add it again, and try set it correctly from the start.

Hope that helps.

p.s. using Views 7.x-3.6