ESIs with Varnish 2.1.5 for Anonymous Users We're trying to configure our sites running D7 to use ESIs with Varnish 2.1.5, and having a hard time figuring this out.

We have a file /test.php that is being included in the template via esi so it appears on all pages of our site. The call to the file is through (in the template)

<esi:include src="/test.php" />

Relevant vcl conf is:

sub vcl_fetch {
...
  // enable esi
  esi;
  // if url is test.php, set ttl to 15 s
  if (req.url == "/test.php") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 15s;
  }
}

The text from test.php appears when users are logged in, but does not appear when they are logged out -- which is what we're after. This is without the ESI module as that is for authenticated users.

Try turning off Anonymous caching and see what results you get (caching should be handled by Varnish).

Go to admin/config/development/performance
Uncheck Cache pages for anonymous users


How To Enter Data Into A Custom Drupal Entity? I have a question regarding entering data into custom entities

I have a usage case I believe is better for Drupal Entities than Content Types and Nodes.  I have installed Entity Construction Kit and used it to set up the structure for my entity.

What is not clear to me is how I go about getting data into my entity.  I assume we could do a mass CSV import via Feeds.  But what about making individual entries?  I'm looking for a way to enter the data through the Drupal Administration forms (i.e. Add Content > Entity Name) but that does not appear to be the case.

Are there additional modules out there that would give me the ability to do this?

Thank you for your time and assistance.

-- Chris

I think everyone suffers the same bewilderment on first meeting ECK. Its workflow is bonkers.

You begin by creating an entity type and optionally renaming the default bundle (which otherwise will have the same name as your entity). I recommend giving the bundle a unique name to avoid confusion in this rabbit warren interface.

Then from the list of entities, click into that entity and then into the bundle. From here you can manage fields - and add your data from the 'entity list' tab. There, the link to add new instances of your entity type will be at the top of the interface - "+ add [name of your bundle]" and the list there will effectively serve as a rudimentary content list for that entity until you can whip something up in views.

If you want to cut through the labyrinth and use a simple link to add your data, it'll be structured like this:

admin/structure/entity-type/[your entity name]/[your bundle name]/add


Is there any other way to create a "settings" node without having to create a Content Type? I need to create something like a node with settings. This will have custom fields, images, etc... Just like a content type, but without having to create one of them.

Why? I think it's strange having to create a content type when I need to create only one node with that structure.

I know this sounds weird, but just wonder if there is another way?

Thanks

The clean way is to create a custom module or theme with settings you need.  Examples For Developers shows you how to do it.

If you need settings, you need them because something will use them. So just adding a proper form shouldn't be too big overhead. And if you keep your settings in a way that makes possible for field to cease existing, you need to add more lines of code to safeguard against such situations. You don't want that. It's disaster waiting to happen.


"basic page" content type: how would I restrict access to a page for only 1 role If I created content that is of "basic page" content type that is mapped to a URL path settings as an alias how would I restrict access to that page to only 1 role?

If the user is not logged on then how can I redirect the user to a login page and then after that send them back page to the originally requested page?

Note I only want to restrict access for this one page and not all pages that have "basic page" content type.

This can be acheived by using a combination of content access and login toboggan modules. You'll be able to restrict pages and prompt user to login to access them.


Resolving mysql error Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': I'm getting the integrity constraint violation error (as shown below). There indeed exists a row in file_manage table with uri=''.

So my question is can I simply delete this row entry from the table without any side affects? Additionally how this empty row could have been added here.

Error Output when I do "drush cron":

WD node: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0,                     [error

:db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
    [:db_insert_placeholder_0] => 0
    [:db_insert_placeholder_1] => 1
    [:db_insert_placeholder_2] => 1398243826
)
 in drupal_write_record() (line 7166 of D:\WORKAREA\work\htdocs\gij\includes\common.inc).

And here is the table row with empty uri:

mysql> select * from file_managed where uri='';
+------+-----+----------+-----+----------+----------+--------+------------+----------+
| fid  | uid | filename | uri | filemime | filesize | status | timestamp  | origname |
+------+-----+----------+-----+----------+----------+--------+------------+----------+
| 3356 |   0 |          |     |          |        0 |      1 | 1389353548 |          |
+------+-----+----------+-----+----------+----------+--------+------------+----------+
1 row in set (0.00 sec)

You can check whether the file is being used by another part of the system with the file_usage_list() function:

$file = file_load($fid);
$usage = file_usage_list($file);

If the returned array is empty, you can probably assume that it's an orphaned record, and safe to delete. But take a backup first, as always.


Where does the query table "taxonomy_term_data_node" come from? I'm troubleshooting a Views' query which uses taxonomy_term_data_node.weight, but  there is no table of this name. Actually, the table name is taxonomy_term_data as you well know. So how is this table reference made? I do not see that alias in the query.

SELECT node.title AS node_title, node.nid AS nid,
  taxonomy_term_data_node_1.weight AS taxonomy_term_data_node_1_weight,
  taxonomy_term_data_node.weight AS taxonomy_term_data_node_weight,
  'node' AS field_data_field_category_child_node_entity_type,
  'node' AS field_data_field_category_parent_node_entity_type
FROM {node} node

LEFT JOIN (
  SELECT td.*, tn.nid AS nid
    FROM {taxonomy_term_data} td
    LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
    LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
    WHERE  (tv.machine_name IN ('category_child')
  )
) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid

INNER JOIN (
  SELECT td.*, tn.nid AS nid
  FROM {taxonomy_term_data} td
  INNER JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
  INNER JOIN {taxonomy_index} tn ON tn.tid = td.tid
  WHERE (tv.machine_name IN  ('category_parent'))
) taxonomy_term_data_node_1 ON node.nid = taxonomy_term_data_node_1.nid

WHERE (((node.status = '1') AND (node.type IN ('group_by_test'))))
ORDER BY taxonomy_term_data_node_1_weight ASC, taxonomy_term_data_node_weight ASC
LIMIT 1000
OFFSET 0

taxonomy_term_data_node is the alias used for the SELECT that is part of the first LEFT JOIN.

LEFT JOIN (
  SELECT td.*, tn.nid AS nid
    FROM {taxonomy_term_data} td
    LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
    LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
    WHERE  (tv.machine_name IN ('category_child')
  )
) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid


How do I change the label and help text of the publishing status checkbox? We recently updated our site to Drupal 8.4 and the widget for publishing a node has changed from a dropdown to a checkbox. Now, how do I change the label and help text of the checkbox? It cannot be changed in the field UI.

You can use hook_form_alter() to change label and help text
Use devel module to debug the label and help text change accordingly.

/**
 * Implements hook_form_alter().
 */

  function hook_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'node_page_form'){
   kint($form);
   kint($form['status']['widget']['value']['#title']);
   $form['status']['widget']['value']['#title'] = t('Published status label changed');
  }
}

After applying above code for basic page node form i was able to see the change in label of published text to Published status label changed


redirect user to page where they clicked an "add node" link In several places on my site I use an "add node" link that lets users add a node (I'm using organic groups).  After saving the node, I'd like to redirect users back to the page on which they clicked the "add node" link.

I know how to redirect users to a specific page after saving a node, but that doesn't work in this case, as the add link shows up on several pages.

I've tried setting $form_state['redirect'] = false, but that also doesn't help as it puts users back in the node edit page.

Would be wonderful if anyone could point me in the right direction. Thanks!

EDIT: 2 minutes after I posted this I came up with the following:  Add Contact

This redirects the user to node 52, which happens to be the group page on which this add link lives.  This is a step in the right direction.  Would be even better if I could use a token in the link.

You can use Token Filter module and the following code should work:

Add Contact

Make sure that the token filter is available in the text format you are using.


How to set the default value of a CCK field I got a CCK field to select a currency; this field is not required, and the dropdown displays '-None-'. I want to change that.

There's the option to let PHP-Code return the value. It says:

return array(
    0 => array('value' => 'value for value'),
    // You'll usually want to stop here. Provide more values
    // if you want your 'default value' to be multi-valued:
    1 => array('value' => 'value for value'),
    2 => ...
);

So I tried with:

return array(
  0 => array('value' => 'my_text'),
);

Drupal now tells me:

The PHP code for 'default value' returned Array ( [0] => Array ( [value] => my_text ) ) , which is invalid.

I got a list of 4 currencies to choose from, which are the allowed values in my dropdown. What do I have to do to replace '-None-' with my own default?

In order for you to use PHP you must return a simpler array:

return array(
  'value' => 'my_text'
);

Also, if all you want is to set a default value, you don't need to use the PHP option.

First, define the allowed values (manually or via PHP, doesn't matter)
Then click save
Now click edit to go back to the form. Close to the top there will be a "Default Value" fieldset populated with the allowed values. Just select one!


Show/hide fields in a form based on the value of a checkbox Is there a way to hide a specific or specifics fields in Drupal when you create content until you checked a checkbox?

Now it looks like this:

I need something like this:

But I need some checkboxes to decide if I have a certain field to show or not. Like this:

(Fieldcollection item 'some information' is showing up now because I checked the checkbox before the label)

Is there a module for this?

What would be nice is if all fields only become mandatory if you checked a checkbox.

You can use module conditional fields if you want to do this node form


How to create a redirection programmatically? I try to create a redirection 301 with the redirect module. For example, I want to redirect an URL source to an internal URL through my custom module.

I want to create a redirection when I create a node. Import old content, create a new node and keep the old path.

Anyone have an idea?

If you want to store redirects in database use the module Redirect. This module provides a user interface to add redirects. The redirects are stored in a content entity, which you can also create programmatically:
use Drupal\redirect\Entity\Redirect;

  Redirect::create([
    'redirect_source' => 'redirects/redirect1',
    'redirect_redirect' => 'internal:/node/1',
    'language' => 'und',
    'status_code' => '301',
  ])->save();

You can do this at the time you create nodes from imported data or in entity hooks when inserting, updating or deleting nodes.


Show permission used I've on a drupal 6 site a custom module which generate a page, i send in that page a form.

When i try to test my form as an anonymous user, it doesn't work as i get:

  You are not authorized to access this page.

I've a hook_perm on my module and permission are activate for anonymous user, but that still doesn't work, even after "cache clear" or "rebuild permission".

So i must have another permission in conflict here that forbid me to show my form to anonymous user (as an admin, i can see it). Is there a way for me to print the "rights" that forbid me to access my form, to get a list of the permission used in a specific page?

I get an solution :
Exposed here in : https://drupal.org/node/109157

I had to add '"access callback"   => TRUE' to my hook menu (TRUE because i want anonymous user get access to the page).

function custom_createAccount_menu()
{
  $items["createAccount"] = array(
    "title"=>t('Create an account'),
    "page callback"    => "_custom_createAccount",
    "access callback"  => TRUE,
    "access arguments" => array("access createAccount content"),
  );

  return $items;
}

and that works.

@SavaryNicolas


Cannot do a `composer install` even though my minimum stability is listed as dev I am trying to build the master branch in my project after updating to 8.5.0, but am being met with an error from composer (which I did not get on my develop branch):

  The requested package drupal/focal_point 1.0.0-beta6 is satisfiable by
  drupal/focal_point[1.0.0-beta6] but these conflict with your
  requirements or minimum-stability.

In my composer file, I have:

"drupal/focal_point": "^1.0",

as well as:

"minimum-stability": "dev",

How can I fix this so TravisCI gets unstuck? It worked fine for the develop branch, and the master is now updated with it.

This may be incorrect per information in comments and because it contradicts Installing an alpha dev version with composer.

I think the issue here is that the beta6 is not ^1.0. If you updated the requirement to be "drupal/focal_point": "^1.0@beta", this would work fine.

Alternatively, you could call composer require drupal/focal_point with no version specified and it would install the beta6 version just fine. I believe this is where minimum stability is checked, but that would add a  require line in your composer.json different from what is specified in your question.


Check if the current user has permission to edit current node I'm using Nodeaccess module to add permissions on specific nodes.
 in my .theme file I want to Check if the current user has permission to edit the current node.

I've found it and working great.

  $node = \Drupal\node\Entity\Node::load(NID);
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $check = $node->access('update', $user);


How to hide taxonomy terms with no content How to display only those taxonomy terms that have content? Can this be done with the help of relationships or contextual filters?

If you  create a view to show terms, you can create a relationship for "Taxonomy term: Content with term". This will allow you to access all the nodes referencing each term.

In the configuration screen for the relationship, you can check the "Require this relationship" checkbox (see screenshot below). Like that, terms that are not referenced by any node will not be displayed.


Exposed form in block not found in block view drupal 7 I am facing an issue what I need is expose some fields for search criteria & put these search boxes/drop downs to my sidebar, I didn't find the option "expose from in block" in the Exposed Form section, I have a block view, It is showing on the view page but not on the block view why?

Is there any solution regarding?
Thanks

Have a look at the Views Block Exposed Filter Blocks module.

Views normally restricts exposed form blocks to page displays. So if you want an exposed form for a block display you either have to go with this module or you build your own block in code and embed the exposed form there.


Change theme template for one form I try to change a the theme template for one form. I do not want to use theme suggestions as I only want to use a different theme in one case, and if I add a suggestion, it is always used. (maybe I'm wrong.)

I'm doing:

in my controller:

$form = \Drupal::service('entity.form_builder')->getForm($entity);

$form['#theme_wrappers'][] = 'user_register_form_01';

return $form;

in my .module

function mymodule_theme() {
  return [
    'user_register_form_01' => [
      'render element' => 'form',
      'template' => 'user-register-form-01',
    ],
  ];
}

in user-register-form-01.html.twig:

<form{{ attributes }}>

  {{ form.field_1 }}
  {{ form.field_2 }}
  {{ form.account.pass }}
  {{ form.account.mail }}

  {{ form.form_build_id }}
  {{ form.form_id }}
  {{ form.actions }}

</form>

Everything seems to be rendered correctly, but the form does not work/submit. I think it is because attributes does not contain any action information. There is one more attributes variable inside form but I don't know how to call it as when I dump it it is prefixed with #

dump(form|keys) returns

array (size=49)
  0 => string '#attributes' (length=11)
  1 => string '#attached' (length=9)
  ...
  47 => string '#children' (length=9)

I don't know how to access this as form.#attributes doesn't work and form.attributes results empty.
Also this #attributes seems not to contain the needed form submission information. But it seems that inside #children the #attributes does.

I am thankfull for any hint or help.

Have you looked into the Context module for this (https://www.drupal.org/project/context)? One of the "reactions" is to change the theme. You can do it by system path.


Drupal 8, The file used in the Image field may not be referenced I am using managed file type to upload image in my custom form (Drupal-8). I am able to retrieve the given image while editing by using the below code

$form['image_field'] = array(
   '#type' => 'managed_file',
   '#title' => t('Image'),
   '#default_value' => array($fid),
);

While i am trying to save once edit, i am getting the "The file used in the Image field may not be referenced." error.

Please let me know to over come this error and let me what this error trying to convey.

Check \Drupal\file\Element\ManagedFile for answer, it appears that your file is being saved as permanent, but there is no entry in file_usage table:

if ($file = File::load($fid)) {
      if ($file->isPermanent()) {
        $references = static::fileUsage()->listUsage($file);
        if (empty($references)) {
          // We expect the field name placeholder value to be wrapped in t()
          // here, so it won't be escaped again as it's already marked safe.
          $form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
        }
      }
    }

If you want to store your files permanently, you need to make sure they've got usage entries, to do so, you can tweak you form submit handler a little bit, here's some quick example:

// get file fid wherever it is
$values = $form_state->getValues();
$fid = $values['my_file_field'];

// call file usage service and load file
$file_usage = \Drupal::service('file.usage');
$file = File::load($fid);

// set file status permanent
if(!$file->isPermanent()){
  $file->setPermanent();
}

// check file usage , if it's empty, add new entry
$usage = $file_usage->listUsage($file);
if(empty($usage)){
  // let's assume it's image
  $file_usage->add($file,'mymodule','image',$fid);
}
$file->save();


Why are existing entity reference fields not available to add to a media type? I have a number of existing entity reference fields in my site. The key one is a taxonomy reference field called field_search_terms. I would like to add this field to the Document media type. However when I go to manage fields for the media type my existing fields are not available.

It looks like I need to create a new field and any search that mixes content and media will need to have two filters.

Why is this limitation in place? Is there an issue I can follow to learn more?

I found the resources I was looking for with help from a comment by Clive:

A field can only be used on the same entity type. There is an open issue for this in the queue. According to the issue and my recollection this is a change from Drupal 7. If so it feels like a major regression.

The documentation is also incorrect at the time of this writing.


In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content? Using views-view.html.twig as a starting point, I can output {{ rows }}, but I want to loop through each field of each row to aggregate and style them.

In Drupal 7, I use dpm(rows) to locate (in the array) where content, label etc. But kint doesn't seem to provide me the same information. Can anyone help?

In views-view.html.twig is not appropriate to style your row and fields.

To style them first you need override template "views_view_'format_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).

Something like:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}

 {{row.content['#node'].getTitle()}}
 {# access fields #}

    {{ row.content }}

{% endfor %}

For style fields its better override field template.

For example field--node--body--article.html.twig:

{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}

{{ item.content }}

    {% elseif mode == 'teaser' %}

{{ item.content }}

    {% endif %}
  {% endfor %}
{% else %}

{{ label }}

    {% for item in items %}

{{ item.content }}

    {% endfor %}

{% endif %}


Authenticate joomla users to drupal website I know this is not 100% drupal question but It might be the case that someone has StumbleUpon this one before.

I would like to give the opportunity for people having an account on a Joomla website to login to mysite and create a very basic account(automatically) when doing that.
Something similar to facebookconnect.

Has anyone done this before?

One solution could be to use the connect module and find a way to expose the needed info on the joomla website.

I'm not sure on a module based solution, but i would just add a custom form submit function on the user_register_form and then code from there. Success would depend on how you can remotely authenticate with Joomla.


How can I detect if node is the last one from within node.tpl.php? There are a number of variables for the node.tpl.php template, like $id that contains the current nodes index number, but how can I figure out if the current node is the last index or how many nodes there are in the current listing?

(I'm using Drupal 7)

In general, it is not a good idea for Drupal objects to not "know" how they are being used on a page.  When you make them "self-aware" you introduce artificial dependencies that can make changes down the road harder to make, or inadvertently introduce bugs.

In you case, I would handle this in the views templates.  Out of the box, the last row should have a views-row-last class on it.

Otherwise, you need to implement a template_preprocess_node in your theme.  The view object will be available as $variables['view'].  You would need to add logic to check page, view name, etc, to make sure you are doing things in the right place.  Off the top of my head, I forget which properties you need to check; do a kpr($variables['view']) and poke around.


When more than one Shipping Rules applies, select the highest I am using Drupal 7 with Drupal Commerce to manage an eshop.
I have 8 product types and I manage the shipping per product type with price variations.
Product type 1 when price is lower than 50 euros has 5 euros shipping, product type 2 has 3 euros shipping when the price is lower than 30 euros etc
I manage doing that by adding rules after a product is placed at the cart , using
"Price comparison" and "Order contains products of particular product types" conditions, and action "Apply shipping rate to an order".

It seems to work fine but when I add multiple products from various categories, the shipping rule that prevails is the rule applied to the first product added to the cart.
What I want is to compare all Shipping rules and keep the one with the highest cost.

Is this possible?

Maybe Total amount of selected products comparison in Commerce Order can be used for that condition.
A temporary solution is to apply the rule which only allows one product per cart.


Rules Workflow: Data selector is invalid A website that has a workflow system based on Rules, as detailed here

Some of the rules use the condition 'User has role(s)', and all these rules now show the following error:

  Error: Data selector site:current-user for parameter account is invalid.

The condition must have been valid when it was created, or the rule would not have been saved.

The site uses Entity API 7.x-1.0-rc3 and Rules 7.x-2.2.

Any suggestions? Even deleting and recreating the rule does not work, as I cannot seem to find site-current-user in the Data Selector dropdown.

The problem was with the UUID module. Updating it to the latest version fixed this issue.

Similar problem at: Enabling UUID breaks rules config set by Ubercart.


How do I hide nodes tagged with a specific taxonomy term in views? I'm on d7. I  have a multi taxonomy term vocabulary that I allow users to add up to three terms. I'm using the flag term module and have a global flag set up to flag a term as hidden.
Ive set up a filter in my view that only shows nodes that have terms that are NOT flagged as "hidden".  This is working when one a node only has one term that is hidden, but when it has two or more that are not, it shows the node in my view. How can I make it so that if a node has a term flagged as "hidden" it doesn't show up in my view list even if it has another term that is not flagged?
Thanks.

You need to add a new filter to your view.

Filter criterion: Has taxonomy term
Vocabulary: Corresponding vocabulary
Operator: Is none of
And select the hidden term in the dropdown


Alter Exposed filter form I would like to know how to get parent terms only, for example "Ages 0-2" and also print in dropdown.

This is the structure of the form array.

Array(
  [#info] => Array(
    [filter-tid] => Array(
      [operator] => tid_op
      [value] => tid
      [label] => Term
      [description] =>
    )
  )
  [tid] => Array(
    [#type] => select
    [#options] => Array(
      [All] => - Any -
      [0] => stdClass Object(
        [option] => Array(
          [367] => Ages 0-2
        )
      )
      [1] => stdClass Object(
        [option] => Array(
          [2378] => -Infant
        )
      )
    )
  )
)

This is the code I am using.

  if ($form['#id']== "views-exposed-form-quick-find") {
    $test = $form['tid']['#options'];
    foreach ($test as $tid) {
      // It prints "Array" and the "Trying to get property of non-object" message.
      print $tid->option;
    }
  }

I do not understand why the "Array" text repeats; it could be I am not pointing to right array.

How do I remove all children which do not have "age 12 - 14" (see "-" in the middle not from start)?

What you obtain from that code is exactly what you should obtain.

The values you are getting from that control statement are:

$form['tid']['#options']['All'] is a string, and not an object. Trying to access $form['tid']['#options']['All']->option gives you a warning about accessing a property for something that is not an object.
$form['tid']['#options'][0] is an object, and it doesn't raise an error, but $form['tid']['#options'][0]->option is an array, and print $form['tid']['#options'][0]->option converts it in a string. That is why you see Array.
The same is true for $form['tid']['#options'][1].

To remove the array element that contains 'Age 12 - 14' from $form['tid']['#options'], I would use the following code.

foreach ($form['tid']['#options'] as $index => $tid) {
  if (is_object($tid) && !empty($tid->option) && is_array($tid->option) && in_array('Ages 12-14', $tid->option)) {
    unset($form['tid']['#options'][$index]);
  }
}

Notice that in_array() is case-sensitive. If you are searching for 'Age 12 - 14', but the string is 'age 12 - 14', the code doesn't remove the option.


Are the same node paths a problem? I created a website with Drupal 8 in 4 languages. When I access a node in the default (English) language, I get to a page with a path of e.g. localhost/contact, just as it should be. Now, when I switch to Japanese, I would expect it to be localhost/jp/contact, but it is localhost/jp/node/13 (the page does display though). Both nodes have the same path listed (/contact) when I inspect them in the administration area.

For the record, my language detection methods are set in this order, in case it matters:

Account administration pages
URL (note: URL path prefixes are configured)
Session
User
Browser
Selected language

How can I achieve the expected state I mentioned above? That is, having the same (relative) paths set for each language variant of a node, while the language part of the URL would ensure displaying the proper language version of the node and while the URL would be human-readable and not just the node ID?

You either need to make your aliases not language specific (you can only do that in the alias administration page right now, not in the node edit form) or you need to create one for each language.

If the alias shows up for all languages, make sure you made the path field translatable in the content translation settings, maybe something doesn't work correctly otherwise.

See https://www.drupal.org/node/2775275 for an issue to allow language-unspecific aliases. You could also use tokens to get the original language with pathauto to work around it.


How to track location of a sign-up form in a block? I have a newsletter sign-up form in a block that appears on many pages. When the form is submitted, I want to capture the current page.

The block and form are created in code. In the submit function, I am using drupal_get_path_alias() to get the current location. The block has no explicit caching set, so I believe DRUPAL_CACHE_PER_ROLE is assumed.

I had been thinking that although the block is cached for anonymous users, the submit function would still retrieve the correct location.

However, it doesn't seem to be working correctly. I always get a value for the path, but I believe it's incorrect in many cases.

What should I do to make sure I get a correct path on submit?

Update Mar 17 2014: I switched caching from the assumed DRUPAL_CACHE_PER_ROLE to DRUPAL_CACHE_PER_PAGE and that seems to have resolved the problem. Also, for the record, the problem looked like this: most sign-ups come from one page. But every once in a while a sign up will come from a different more obscure location on the site. What I was seeing was that "other location" repeated for the next x of signups (the number varied). So, in that respect, it did look like a caching problem.

have you fully tested your guess?  what you've described should work, AFAIK.

other options would include:

1) modifying the form to have a hidden value, set using drupal_get_path_alias() ...  it would set the value on load, rather than looking it up on submit.

2) a google analytics event tracker attached to the submit button the form.


How to preserve Drupal file permissions after compressing and moving as tarball? I seem to be frequently encountering a situation when I compress files of a Drupal site as a tarball from a production server to the public_html folder of my  local machine.

The permissions seem to get messed up and I usually end up with a filesystem not readable error and  deleting a few files in the sites/default/files directory during the process of changing the permissions.

How can I preserve these permissions when the folder is compressed and copied to a new folder or is it an issue with the permissions of the destination folder?

I move sites as tarballs between servers fairly often when I can't deploy with rsync or git.

According to the man page:

  -p, --preserve-permissions extract information about file permissions (default for superuser)

is the proper option to use.  However, this never works well for me.

Typically, I will just use normal tar options, and then run a script after the fact to fix things up.

The Securing file permissions and ownership article has a very good script.  As that gets adjusted from time to time, I am not going to reproduce it here.  It essentially does some find/chown/chmods on the tree to fix things up.

I would use this script as a starting point for your needs.  One thing that it doesn't address is having the private:// filesystem outside of docroot, which I always use.  I will also use 2775 as the permission for the public:// path, as well as a separate use for core/contrib and the site specific code.


How to display one image in multiple sizes across the site? I would like one image to show in different locations, for example:

Event in the Calendar (Cropped version of the image)
Homepage (if promoted to Front Page - as the full size of the image)

Is this possible using Drupal 7?

Thanks!
Izumi.

Imagecache module has been moved into core for Drupal 7

It's called Image Styles

I haven't used the module, but Image Formatter Link To Image Styles module exposes the Image Style presets in in the imagefield


Exposed filter for data and select field I spent all weekend trying to make this work, and couldn't figure it out.

How do I create a views exposed filter for date and a text list on a given node?

My setup - I have a view that is exposed as JSON with a task_name field, a date field, and a status field.

I have the date module installed in both Drupalgap as well as Drupal, and I'm able to get that to display correctly.

I've tried creating a select list for day, month and a year, as well as task status, and this seems clunky (four select lists takes up quite a bit of room - and I can't figure out how to collapse them - perhaps some sort of "collapse format"?)

But even if I do create them, there seems to be no way to have an interaction between them and the view content object. I tried grabbing the values of the select lists from the path of the views object, but there seems to be no way to do that.

My views code looks like this, almost an exact copy of the beer example:

function task_list_page() {
  try {
    var content = {};
    content['task-list'] = {
      theme: 'view',
      format: 'ul',
      path: 'tasks.json',
      row_callback: 'task_list_page_row',
      empty_callback: 'task_list_page_empty'
    };
    return content;
  }
  catch (error) { console.log('task_list_page - ' + error); }
}

What would I do to this to create an exposed filter for date and status, both of which are columns in the view? How would I make this filter compact and perhaps collapsible?

According to the docs here drupalgap.org/node/498 the filter should be added to your app when you create it in your view and then publish it. If those instructions do not work to create a simple filter, I suggest raising and issue over there.

As to Date filtering, I expect that only the select list exposed form items will transfer to your app out-of-the-box. If you want some custom UI elements such as jQuery mobile date picker to match the rest of your app UI, you will have to use a text field in the views exposed filter then edit the code on you app to call the UI element.

A lot of the time with similar things, I end up creating icon links in the header that act like filters and sorters e.g.

<?php
print l("<i class='icon icon-cancel-circled'></i>", "my/view", array('html' => TRUE, 'query' => array('sort_by' => 'created', 'sort_order' => 'ASC')));
?>

This makes an arrow up icon link (if you're implementing icons somehow) which will go to the view sorted by "created" "ascending".

Having an exposed filters form in an app is often too much for a small screen when a few icons will do, and this should transfer to your app in the header ok.


Why I can't I drop field_data and field_revision table in phpmyadmin? I wanted to delete a filed named MyField.

So I first deleted the corresponding record for MyField in field_config table and field_config_instance table.

And now I'm trying to drop these tables by using phpmyadmin.

field_data_field_MyField
field_revision_field_MyField

But even if I drop them they are still there.
It seems that they can't be droped.

Isn't it possible to delete fields directly in DB?

@hampercm explained why directly deleting records and tables from database is not recommended. It is so true that everyone is encouraged to use admin UI or Drupal API to remove the fields and field instances.

But, I guess you know what the best practise is and wanna do that by SQL query with some reason (e.g. company policy. YES, I faced this stupid requirement before)

You are on the right track. Drupal save field and field instances config in field_config and field_config_instance. BUT, Drupal also cache these data in cache table.

So, you need to truncate the cache table.


How to add item to cart programmatically, with attributes in Ubercart So I know how to go about adding an item to the cart with PHP like this;

$product_nid = 2;
$some_data = NULL;

  uc_cart_empty(uc_cart_get_id());

  $data = serialize($some_data);

  uc_cart_add_item($product_nid, $qty = 1, $data, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE);

but I'm uncertain how to add a product with a certain attribute/option such as if I have product "A" with options "1" and "2" I was hoping I could get a little help.
This is for Drupal 7, Ubercart 3.

Taking Chris's answer an putting it in Answer format for readability.

Figured it out, perhaps this will be of help for someone :)

$product_nid = 2;
$some_data = array('attributes' => array(
                   '1' => '1',
                  ),
             );
uc_cart_empty(uc_cart_get_id());
$data = serialize($some_data);
uc_cart_add_item($product_nid,
                 $qty = 1,
                 $data,
                 $cid = NULL,
                 $msg = TRUE,
                 $check_redirect = TRUE,
                 $rebuild = TRUE);


How do I control if an ajax webform has errors? I have a webform that sends an email upon submission. Ajax is enabled so when I hit submit and there are errors on the form they will show instantly. However if there are no errors I would like to hide the form along with the success message.

Some pseudo code (sort of):

Drupal.behaviors.sendMail = {
  attach: function (context) {

    $('#webform-client-form-340', context).ajaxComplete(function(event, xhr, settings) {
      if ($('.alert-errors').length == 1) {
        thisForm.highLight()
      } else {
        thisForm.hide();
      }
    });

  }
};

This doesn't work because the .alert-errors div is not yet there on ajaxComplete.
So how do I check for errors, highlight the form if they are present and otherwise hide the form?

I when I normally have to debug this I use

Debugging ajax with FIREPHP

  Explaines how you can debug ajax with FIREPHP


Delete the content of a field from all the node under a specific content type What would be  the best approach (preferably with GUI) to delete the content of certain fields from certain content types.

I am thinking of using rules but I cant configure to do it.

Ny ideas? Thanks

Views Bulk Operations, using the "Modify entity values" action.


views.view.unformated.html.twig taxonomy conditional if/else I am trying to get to the field_news_type term_id/label. I can print the field and I get the term label. Need guideance to be able to select which one I want to use.
{{ fields.field_news_type.content }} //prints the term 'Grid 2' which is correct.

I am trying to get either the label or term_id, so I can do a conditional. The below does not work. I have tried many variations. I have not found an answer that has produced a working result. Can someone guide me to finding the correct way to print this out in a views template page?
{% if fields.field_news_type.target_id == '2871' %}

I can use this for a node template page and it works...but not in the views twig file.
{% if content.field_research_focus_areas['#items'].getValue() %}

The code doesn't match the template, it's more likely from a views-view-fields.html.twig template. Then you could configure a separate field in Views UI to produce the output you want. Views fields are not a 1:1 match of entity fields, you can rewrite the entity content to whatever you want. Most times it's a better idea to put Twig in Views UI and not in Views templates.
If you really want to access raw field values, don't use the output of Views field plugins. Access field values directly through the node object:
{{ row._entity.field_ref.target_id }}

More info Access row value in template_preprocess_views_view_fields(&$variables)


Node Clone operation/tab missing for webform Node Clone 7.x-1.0+2-dev
Webform: 7.x-4.13
Drupal 7

I only see the clone operation available on 1 custom content type, and NOT on my webform content type.

I tried installing the node clone tab module, and the tab does not appear either.

Clone any node, clone own node permissions enabled for my role 'Administrator'.

Any suggestions for moving forward?

Besides simply enabling the Node Clone module and checking the permissions associated with it, you'll need to select which content types can be cloned.

To do so, go to /admin/config/content/clone

After enabling for the "webform" content type, you should see the clone link available near the contextual link / action tabs at the top of a webform page when signed in as an admin and viewing the page.


Manipulate a render array in hook_node_view I'm wanting to modify the contents of some fields at display time so looked at hook_node_view(), however, the $build array is not what I'm expecting, if I dump it with var_dump it is thousands of lines long and not in the format I'm expecting a render array to be, it includes all sorts of exciting things like SQL connection objects which are of no use to me but there is no obvious set of elements that I'd be expecting to see given the Drupal documentation. If I drill down the array, I can find the data I need, however, I can't see how to get this sorted in the correct display order.

If I add a simple tweak like

$build['title'] = ['#markup' => "Hello World"];

the node title is rendered correctly as the new value so I know I'm roughly in the right place.

Question, how can I get at the fields collection after extraction from the database and sorting into display order but before it hits the template as I need to be able to make changes at this point as future development will require potential output via differing templates.

Suggestions

Get the node from the $build (it should be in there somewhere) and build custom content for your field like $build['custom_field'] = [...].
Override the twig template for the field - this will let you alter the presentation of a particular field. Ex: implement node--field-custom-field.html.twig based on field.html.twig and alter the output of the field there.
Override the twig template for the entire node. Ex: implement node--article.html.twig based on node.html.twig and alter the output of the node there.

Let me know if any of these helps. More details on exactly what or why you want to alter stuff will be helpful.


How to prefill address field forms? I've been using the Prepopulate module for a while, and it works really well. It can't prefill an addressfield type field, though.

How can I achieve this?

Add something like this to your hook_form_alter() or hook_form_FORM_ID_alter():

  $form['field_address'][LANGUAGE_NONE][0]['#address']['country'] = 'US';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = 'Livermore';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = 'CA';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = '94551';


Show fields on webform based on a value in the session I want to use a webform to do a feedback form but want it to act on data provided by the user. That is, if the user has answered a question about location which is stored in a session, then I want to show a webform field, otherwise don't show the field at all. Any ideas on if this is possible and how to do it in webform?

Thanks.

try somewhere in your webform-form-[NID].tpl.php

hide($form['submitted']['your-field-name']);
if($_SESSION['your_value'] == 'what it should be') {
   show($form['submitted']['your-field-name']);
}


How do you pass page arguments from panels to a view? I'm creating an online store using Ubercart.  I have Views and Panels installed.  I'm using the Page Manager and Panels to configure each of my pages.  I've modified the default view to accept taxonomy terms as arguments.

My question is simple, "How do you pass arguments from Panels to a View?"

I followed the direction's at this URL, but, in the process, actually discovered a much better way (I posted the solution in the article, but I'm also going to post it here):

[a link] http://itscommonsensestupid.blogspot.com/2009/04/passing-arguments-from-panel-to-views.html)

I will post the best solution to this question in a couple of hours.

Example scenario:

There is a panel containing View Content Pane.

Panel URL: /panel_url

Example with argument: /panel_url/term_name

With BEF: /panel_url?category=123

How to set up (having existing panel and added Content Pane):

Add Contextual filter to the View.
E.g.: Views contextual filters taxonomy name
Change settings in 'View -> Pane settings -> Argument input' to load the argument 'From panel argument' (e.g. First).

Done.

In addition, if you're using Better Exposed Filters, you could do the following improvements.

To set the current active link based on the argument (if you're using select_as_links):

/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select_as_links(&$variables) {
  $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
  $selected = end((arg()));
  if (array_key_exists($selected, $options)) {
    $variables['element']['#value'] = $options[$selected];
  }
}

To set the current active link based on the argument (if you're using select):

/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'DROPDOWN_NAME') { // name of your select list
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}

To make the links SEO friendly, you can try something like:

/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path){
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}


Fix/force blocks in a region inside a tableDrag I'm trying to alter/patch/hack node_level_blocks (like the admin blocks overview page) so that some users are restricted in choosing regions for certain blocks. For instance the "New Content" view must always be in the Right region. The normal user can change the weight and add more blocks to that region, but they can't remove that block from that region.

What I did (I'm pretty close):

Form alter the <select> to that it contains only 1 option
Override Drupal.tableDrag.blocks.onDrag to fix and improve the standard tableDrag handler and make the row jump back to its forced position

That works, but the user can still drag the block around to regions it doesn't belong. (I don't have a demo online.)

How do I tell tableDrag to NOT let some blocks out of their original regions? I don't understand its 400 options...

The checking-magic comes from Drupal.tableDrag.prototype.row.prototype.isValidSwap and you can override that to add a custom validation. This solved my problem:

// onDomReady: override Drupal.tableDrag.prototype.row.prototype.isValidSwap to add swap-validation.
jQuery(function($) {
  if (Drupal.tableDrag) {
    var _isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
    Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(tr) {
      // Do standard tableDrag validation.
      var valid = _isValidSwap.apply(this, arguments);
      if (!valid) {
        return false;
      }

      // One of us?
      var $select = $('.form-select', this.element),
        loner = $select[0].options.length <= 1;
      if (loner) {
        // Can't swap with non-draggables, since that would mean a boundary.
        if (!$(tr).is('.draggable')) {
          return false;
        }

        // Can't skip over any rows, since that might be a boundary.
        var diff = tr.rowIndex - this.element.rowIndex;
        if (Math.abs(diff) > 1) {
          return false;
        }
      }

      return true;
    };
  }
});

All thanks to Mołot of course.


Theming Profil2 module i'm on drupal 7, using a premium theme "fundedvisual" and i'm trying to do some templates on a sub theme called "fundedvisual_subtheme".

I'm a noob in this, so maybe i did something wrong...

I have Profil2 module with 2 different profil types here the system names : "investor" and "project_creator".

i followed the answer of jeff_shamley in this post : Profile2 Template for edit page

i created a template.php file in "/sites/all/themes/fundedvisual_subtheme/" with this in it :

function fundedvisual_subtheme_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_profile_form') {
if ($form['#user_category'] === 'investor') {
  $form['#theme'] = 'profile2_investor_edit_form';
} else if ($form['#user_category'] === 'project_creator') {
  $form['#theme'] = 'profile2_project_creator_edit_form';
} else if ($form['#user_category'] === 'main') {
  $form['#theme'] = 'profile2_main_edit_form';
}
  }
}

function fundedvisual_subtheme_theme() {
  return array(
'profile2_investor_edit_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'profile2-investor-edit',
  'render element' => 'form',
),
'profile2_project_creator_edit_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'profile2-project_creator-edit',
  'render element' => 'form'
),
'profile2_main_edit_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'profile2-main-edit',
  'render element' => 'form',
),
  );
}

Then i made 3 files in "/sites/all/themes/fundedvisual_subtheme/templates" :

profile2-investor-edit.tpl.php
profile2-project_creator-edit.tpl.php
profile2-main-edit.tpl.php

with this in it :

<?php echo "pouet" ?>

Then i cleared the cache a million time :'D

Annnnnnnd nothing show up except the default system profile :/

Did i forget something ?
Thx in advance !

Edit : i wonder if i can just embed these forms pages in views it would be nice, instead of creating templates with that i could just modify my style.css

Edit2 : one of my comments : to be more precise i have a general page called "my account" and in it i have the header menu on the top, below an image with a title, below another menu bar and below the content of each "button" from that menu bar.
Each time i click on a button from my menu i want to keep that template, so if i click on "profile" in my menu bar, it should be exactly the same except the title and the content. Is that possible ?

If the whole point of this is to be able to add wrappers around fields, an alternate option would be to use the field group module. Here is a video tutorial on it.


Module's optional field config not imported on install I've got a module which contains a config/optional folder which has the content:

paragraphs.paragraphs_type.my_paragraph_id.yml
field.field.paragraph.my_paragraph_id.field_my_field.yml
field.storage.paragraph.field_my_field.yml
core.entity_form_display.paragraph.my_paragraph_id.yml
core.entity_view_display.paragraph.my_paragraph_id.yml

These files have been exported from an existing installation without uuid's. When I enable the module, the config does not import since the module paragraphs has not yet been enabled. When I enable paragraphs the paragraph type my_paragraph_id is created as expected. The field storage for field_my_field is also created, since I can create a new field based on the existing field field_my_field. Though, the field is not created on the paragraph itself.

I've tried moving the config files to config/install and then it simply works as expected; the field gets created on the paragraph just fine. But the module paragraph should be optional and only then the config should be created, therefor, I want it to be optional.

Why does the config/optional not install the field?

Optional config is only installed if it has an explicit dependency on a module that is being installed right now. Otherwise that configuration would be re-installed every time you install a module, even if it is something you chose to delete on a specific site.

The downside of that is that there are some grey areas of config that depends on config that depends on a module being installed that isn't found by this. Although that should also work but apparently does not in this case.

As a workaround, you can add an enforced dependency on the paragraphs module on those configurations that aren't being imported, then it should work. See https://www.drupal.org/node/2404447


Email validation in a custom module I am using the form API to create forms. How can I validate the email address without needing any separate module? I am just looking for out of the box functionality.

In a custom module, consider using PHP's built function for email validation: filter_var().

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}

This code will go into a validation function. A validation function can be added as an element to the form array (see the form API for details) that you linked to. If your module is named spade, for example, your form may be in function spade_form(). Your submit may then be put in function spade_form_submit(), and your validation would be in function spade_form_validate(). This is the default handler for validation.

See the following links for more information.

http://php.net/manual/en/filter.examples.validation.php
http://php.net/manual/en/filter.filters.validate.php
https://www.drupal.org/project/examples

The first example is exactly what you're looking for (and the example that I copied above). The last link contains the examples module, which has a lot of great form examples.


How do I render a form in a div through a javascript call I'm trying to load a form into a div using a javascript call. I can get the form in the div, but nothing works (autocomplete fields, wysiwyg fields, custom submit handler).
I know I must be missing something, but I can't figure out what it is.
What I have now to get the form:
$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');
$renderable = [
   '#theme' => 'my_form',
   '#form' => $form,
];
$rendered = Drupal::service('renderer')->renderPlain($renderable);

$response = new AjaxResponse();
$response->setData($rendered);
return $response;

I've also tried renderRoot instead of renderPlain, but to no avail.
The twig file looks like this (very simple):

    {% include 'header.html.twig' with {
        type : 'manual'
    } %}

        {{ form }}

Any help will be greatly appreciated.

You have to add ajax commands to the ajax response, using the unrendered render array:
$response->addCommand(new ReplaceCommand('#form-container', $renderable));

BTW you can only return a Drupal ajax response if you have triggered an ajax request via ajax.js. Outside of form submits you usually do this by adding the class use-ajax to a link. For custom js code see How to Trigger Existing, Non-Form Ajax from JavaScript Event


What is the difference between the "complete" and " checkout complete" order statuses? I am using the Drupal 7 Commerce module. I would like to execute a special code when the payment of the order is completed.
What is the difference between checkout complete and complete?
I googled and I found suggestions for these hook implementations.
First option
function mymodule_commerce_order_update($order) {
  if ($order->status == 'completed' ) {
    // ...
  }
}

Second option
function my_module_commerce_order_presave($order) {
  if ($order->status == 'completed' ) {
    // ...
  }
}

###Third option
I found some suggestions to implement hook_commerce_order_updated().
Fourth option
function mymodule_commerce_checkout_complete($order) {
  if ($order->status == 'completed' ) {
    // ...
  }
}

None of the above. You should be using hook_commerce_payment_order_paid_in_full(), which is always invoked the first time an order's balance drops to $0 or less.
Read more about it in commerce/modules/payment/commerce_payment.api.php.


How to determine if a View display is being used in a site? We have many Views and Views displays. Over 3 years of building the site we have many displays that are not being used. We would like to delete them and clean up the view but are concerned that a display might be used in the site. Is there a way of determining if a views display is being used on the site? I thought of different ways to check this:

A View display that is a Page will have a URL path. Check the path to see if it is working.
A View display that is a block display will be in Managed Blocks. Go to Managed Blocks and see if is placed in any region.
You can look at the view display machine name. And see if there are any twig templates that match that name.
Also do a grep search in our templates for the display machine name to check if it printed in a twig template.

If this is in Drupal 8, you can export all config and search for the display id in both code and config and you should be able to find if it is being used anywhere.


How can I extend a module and it's library with custom functionality? My client requested a modification to their slider that will enable two captions. I'm using the Views Nivo Slider module and believe I can accomplish what I want by modifying the module"s code and extending the Nivo js file. But because I am still learning Drupal, I'm not very familiar with the details of how modules work with JavaScript libraries.

I have gathered that in order to extend a Drupal Module it needs to expose hooks. But it doesn't look like this module does that, so I assume that I'll create a custom module with this modules code as the basis. I know hacking up an existing module code is not the "Drupal way", and I won't if there is another way. Is there?

Also, if I wanted to add another function to an existing library like this one, is there a method through the Drupal module framework to extend the js file without messing with the libray code?

Edit
Title changed to be more general.

I've tried the suggestion by @James Kirby and the field doesn't appear to be included in the markup when I inspect with firebug. Curious, how does the field get included to the slideshow output in your implementation if the fields are normally assigned through the "Views Nivo Slider" format settings? It doesn't look like I can assign divs or classes to the field through it's settings.

Here is what I am trying to achieve if possible. Example

Should I be researching my original approach?

i usually do this by adding fields to the sliders content type, then displaying them out through views then use css to position the text over the images


$is_front is not available in all templates As far as I know $is_front is a global template variable in Drupal 7 and therefore the variable is available in all templates.

Now for Drupal 8 it seems that this is no longer true. I tried to call for $is_front in page-title.html.twig and realized that $is_front was not available here.

Using template_preprocess_page_title(&$variables) I could add $is_front to the template.

*Why is Drupal 8 not providing $is_front in the same style as Drupal 7? And what would be the  way to check for frontpage in a template where $is_front is not available?**

It also seems that drupal_is_front_page() is not available anymore.

Should I go like:

  try {
$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();

 }

      catch (Exception $e) {
        // If the database is not yet available, set default values for these
        // variables.
        $variables['is_front'] = FALSE;
        $variables['db_is_active'] = FALSE;
      }

(taken from template_preprocess_page)

You almost answered the question yourself, you can add the variable to all templates with this code:

function theme_preprocess(&$variables, $hook) {
  try {
    $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  }
  catch (Exception $e) {
    $variables['is_front'] = FALSE;
  }
  // Ensure the cache varies correctly (new in Drupal 8.3).
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

For performance reason you can make a condition on $hook to only add the variable to the templates you need, and to avoid that the code is run twice for page.

Edit:

New in Drupal 8.3: Cache context for determining the Front Page


Login Redirect to Internal Path I am using Drupal-7 and I have installed login redirect module to redirect my page after login.

I read that this module allows redirect towards non-Drupal location.
So, does the Login redirect module is only for to redirect non-Drupal location? Can we redirect to the internal path thru login redirect module?

If this module allows internal path redirection as well, then what to write in Parameter Name?

For example, if we want to redirect it to google after login, then we have to write in parameter name like this:
user/login?destination=http://www.google.com

But, I am not sure about internal path. Can any one please guide me on that?

Thank You!

For internal path you can also specify user/login?destination="page name here"

will redirect to your internal path

For example you have a page called "contact-us" specify user/login?destination="contact-us" will automatically redirect to that page after login

Go through the README.TXT in login_destination module to get more info

hope this helps


Adding fields to Flag Lists I'm using the Flag Lists module to manage user wish lists. I need to add additional fields to the lists such as "body"
I go to /admin/structure/flags/manage/fl_template/fields add the required fields, save, rebuild flag lists, flush caches and attempt to edit existing flag lists or create new ones and I still only see the "title template."

When configuring flag(s) (using the Flag module), you can indeed attach fields to them. However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

If the above doesn't help (or if you've already configured your flag using a Confirmation Form), then you may want to look at Comment nr 1 in issue nr 2539868, which points to 2 more related issues.


exculde content type from search result even for admin Is it possible to disable specific content type from search result even from
administrator, I did for all user types except the administrator using
Search configuration module.

You can do what you're attempting if you implement Apache Solr which has all kinds of cool options - but that involves actually setting up Solr on your server which might be overkill if that is all you wish to achieve.


How to install another module when a module is being installed I have created a module (travel_list) that uses the Field Group module. I want the Field group module to be automatically downloaded and installed whenever the travel_list module is installed.

How can I achieve this?

If a module depends on another module, you have to declare it as a dependency. The way Drupal handles this, is through the *.info.yml files, which define the basic module attributes.

In 'travel_list.info.yml' add this key:

dependencies:
  - field_group:field_group

Doing that, whenever you install the module 'travel_list' it will enforce you to install 'field_group'; this means that if you try to install 'travel_list' module and 'field_group' is not installed, the installation will abort reporting that 'field_group' module is needed.

Developing an script that downloads and triggers the module installation is far away from good practices and can lead to a number of unpredicted situations, starting by the fact that the required modules of your Drupal are defined in the composer.json.


What's a good module for moderating content submissions? Drupal 7.x. I'm looking for a module where it allows me to moderate any content submissions prior to them being published. For example:

I have writers, editors, and publishers groups. I want the writer to create the content, then the editors MUST look over the content to check for errors/mistypes, and THEN publishers take a last look and push the content to be published.

Is there a module that can handle this task for Drupal 7.x?

The Workbench module will help you. You could set up some Rules to accomplish the same tasks.


Is there a common nginx conf for Drupal 7 sites? I've taken a look at Perusio's drupal-with-nginx repository and while I think it's impressive how extensive it is, it may be a little too advanced for me at the moment, plus I have several Symfony2 based sites live on the server and I don't to start making significant changes until I fully understand the configurations.

So I found this on a blog and figured it might do the job. Are there any common pitfalls with serving drupal 7 over nginx? Also, if the same Drupal installation was to power more than one site, would the configuration be any different?

server {
    server_name example.org;
    root /home/me/sites/example.org;

    index index.html index.htm index.php;

    access_log /var/log/nginx/example.org.access.log;
    error_log /var/log/nginx/example.org.error.log;

    location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

    location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

    # For drush
    location = /backup {
            deny all;
    }

    # Prevent user from accessing settings.php directly
    location ~ ^/sites/[^/]+/settings.php$ {
            deny all;
    }

    ## Replicate the Apache <FilesMatch> directive of Drupal standard
    ## .htaccess. Disable access to any code files. Return a 404 to curtail
    ## information disclosure. Hide also the text files.
    location ~* ^(?:.+\.(?:htaccess|make|txt|log|engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
            return 404;
    }

    location ~ \..*/.*\.php$ {
            return 403;
    }

    location / {
            # This is cool because no php is touched for static content
            try_files $uri @rewrite;
    }

    location @rewrite {
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1&$args;
            rewrite ^ /index.php last;
    }

    # Use an SSH tunnel to access those pages. They shouldn't be visible to
    # external peeping eyes.
    location = /install.php {
            allow 127.0.0.1;
            deny all;
    }

    location = /update.php {
            allow 127.0.0.1;
            deny all;
    }

    location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
            fastcgi_pass unix:/var/run/php5-cgi/php5.sock;
    }

    ## Drupal 7 generated image handling, i.e., imagecache in core. See:
    ## https://drupal.org/node/371374
    location ~* /sites/.*/files/styles/ {
            access_log off;
            expires 30d;
            try_files $uri @rewrite;
    }

    # Fighting with ImageCache? This little gem is amazing.
    location ~ ^/sites/.*/files/imagecache/ {
            try_files $uri @rewrite;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
    }
}

The main problem that Drupal 7 has with nginx is that Drupal is designed for Apache, and so many modules assume that Apache is installed (and you will always have a little blue entry on your "Status Report" that tells you that you can't use Upload Progress because mod_php isn't installed — annoying).

That being said, thanks to perusio and others, many modules have been created that deal more with nginx and tap into its functionality well. So far, I haven't run into any problem with nginx that would have been fixed by Apache, and nginx is far faster and has a much lighter footprint. This is shown by many benchmarks, but it's also my experience. It also has better integration with php5-fpm, which also outperforms mod_php.

As Drupal develops, it is becoming more backend agnostic. You can see this with 7's database abstraction layer that allows for more database backends, and so I assume that future releases will be designed with other web servers in mind.

So, there are no pitfalls that I've seen at all. You just have to pay a bit more attention to what some of the modules do, or at least what they say they do. If they mention .htaccess files, then make sure that you have corresponding entries in your nginx files that do the same thing. I haven't actually seen a case where nginx fails with a proper configuration.

Perusio's nginx configuration is absolutely amazing, but it takes quite a while to get through it all and understand it. You WILL need to customize it for yourself, and you might run into some problems that you'll need to fix if you use non-standard setups for things like imagecaching or advagg or some others. It also assumes that you're using more than one php-fpm pool. So you'll need to go through and pull out what isn't needed. But it is worth it to take the time to go through it all because you'll learn so much about how nginx works.

I've also ran into several errors with my nginx/drupal sites because I have a tendency to use php-fpm 5.4 or 5.5. The errors have nothing to do with nginx but with Drupal functions themselves as Drupal is just really finishing a transition to requiring php 5.3. If you look around the issue queues, however, you'll find several patches and other solutions to fix modules to work with newer versions of php.

At the end of the day, I would recommend that anyone who is starting with a fresh server use nginx instead of Apache. It's just better.


loading a view in popup hi i'm trying to display a view in a popup but unable to get a solution. i tried

colorbox node module
popup views integration module

Is there any better way to display a view as a popup ?

If I need to display a view in popup, then I will use ctools module.
Ctools provide Modal dialog functionality to display element in modal.

You need to follow below step for the same:

Create a custom module.
Create Menu item which will interact with ctools modal.
Define ajax callback for the menu item and return HTML of the modal using ajax.

You can check working example (http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7)


Attaching libraries in modules I'm trying to attach a library in a custom shortcode but it doesn't show up neither using render array nor using attach_library twig function.

  class MyTimeline extends ShortcodeBase {
  public function process($attributes, $text, $langcode = Language::LANGCODE_NOT_SPECIFIED) {
    $output = [
      '#theme' => 'my_timeline_theme',
      '#attached' => array(
        'library' => array('my_timeline/timeline')
      ),
    ];
    return $this->render($output);
  }

mymodule/my_timeline_theme.html.twig

{{ attach_library('my_timeline/timeline') }}

The only way I can attach it is using this last line in the active theme,
ie node.html.twig

The ShortcodeBase Class uses renderplain which strips 'the attached assets and cache tags'

In the comments to the source code they say: We use renderplain so that the shortcode's cache tags would not bubble up to the parent and affect cacheability. Shortcode should be part of contentand self-container.

In order to attach the library I then rendered the Array with this code:

$renderer = \Drupal::service('renderer');
return $renderer->render($output);

and it works. Need to understand if and how it affects cache, though.


Avoid duplicate entries when programmatically adding field values This pretty cool answer taught me to push new term references like this:

$node->field_tags[] = 6;

... but if that reference already exists you get a duplicate.

This isn't possible through the UI and isn't what you would usually want. The duplicates show up in the rendered view.

Here's the horrible thing I did to check for the reference I'm trying to add:

$term_refs = $node->field_tags->getValue();
$has_ref = count(array_filter($term_refs, function ($term_ref) use($tid) {
return in_array($tid, $term_ref);
  }));
if (!$has_ref) $node->field_tags[] = $tid;

Is there a hasValue() method or magic PHP function I'm missing that I can use instead?

The structure of $term_refs (the field_tags value) looks like this:

Array
(
    [0] => Array
        (
            [target_id] => 6
        )

)

Update: Clive's solution is what I'm looking for but I couldn't get this to work. So I modified George's answer to this so I can skip existing refs:

if (in_array($tid, array_map(function ($i) { return $i['target_id']; }, $term_refs))) continue;

array_unique could solve your problem here, perhaps employing a similar solution to the one proposed in https://stackoverflow.com/questions/10408482/how-to-get-unique-value-in-multidimensional-array


How do I execute code before update the content? How do I execute code before updating nodes?

I am looking for a hook to use in a custom module.

I have created a content type. What I need to do is execute a hook before updating any content. I want to keep the history of every content, so I want to execute some code before updating, which will compare previous and currently update record. If there is any change, I want to insert it in another table.

I also want to show that history on the content detail page.

I use the Hook Post Action module because it's execute after the action. So you know that the node is really updated.

So this module introduces several new Drupal hooks to overcome this
limitation

hook_entity_postsave
hook_entity_postinsert
hook_entity_postupdate
hook_entity_postdelete
hook_node_postsave
hook_node_postinsert
hook_node_postupdate
hook_node_postdelete

But, if you want you can use the hook_node_update.
To show info in the node page you can use the EVA module.

"Eva" is short for "Entity Views Attachment;" it provides a Views
display plugin that allows the output of a View to be attached to the
content of any Drupal entity. The body of a node or comment, the
profile of a user account, or the listing page for a Taxonomy term are
all examples of entity content.


Serve a different admin theme for a user role I am making a news website. I want the administrator to have the default drupal 7 theme Seven. But I want to give the editor a custom theme that is more usable and streamlined for the task they do.

I have seen this module called ThemeKey. As far as I read it gives a lot of functions. For me as now only thing I want is when the user of the role editor login, they should be served with different admin theme. Thats all. Is there any hooks or something? Are there any examples or recommendations for achieving this?

I think that this module does exactly what you need, I used it on a project and works very well

Role theme switcher module


How to sort node resource in index call in ascending order the in service module Hi I am using service module 7.x-3.12. I am able to fetch the node resource in index call on several different parameters and its working fine but I am stuck in a situation where I need to fetch the data in ascending order. But by default I am getting the data in DESC. Is there any way I can fetch the data in ascending order by providing a custom parameter say, sort_by.

It currently isn't possible. I have an issue and patch filed to make this a possibility. If you use the patch, it is possible using this query string:

?q=endpoint/taxonomy_term.json&fields=tid,name&options[orderby][name]=asc


Inconsistent behavior with user_logout function For a drupal 8 site, I have a custom function that does the following:
It logs out the user and sends them to an external url
Inside the controller CustomController, I have:
function custom_logout(){
 if (\Drupal::currentUser()->isAuthenticated()) {
    user_logout();
    return new TrustedRedirectResponse('https://example.com');
 }
}

In the routing.yml
customl.clogout:
  path: '/customlogout'
  defaults:
    _controller: '\Drupal\user\Controller\CustomController::custom_logout'
  requirements:
    _user_is_logged_in: 'TRUE'

When I visit the /customlogout for the first time it logs me out of Drupal and redirects me to example.com. If I revisit my site and login in again, and repeat the process it still redirects me to example.com but when I check my site I am still logged in. I am wondering why this happens? I can still logout using /user/logout though
Thank you

As it turns out,
return new TrustedRedirectResponse('https://example.com');
was the culprit here.
TrustedRedirectResponse extends CacheableSecuredRedirectResponse, as a result the function was cached, and user_logout was not called even when I visited the  /customlogout
The workaround for this is adding the following lines in your routing.yml
options:

  no_cache: TRUE


How to translate a word in <a title (tpl)? How to translate the word Menu ?
t('Menu') (after class="tb-main-menu-button ...) doesn't work in this case.

<?php
if($menu_bar = render($page['menu_bar'])): ?>

<div class="container <?php print $grid; ?>">

Menu
<?php print $menu_bar; ?>

Try: <?php print t('Menu') ?>

Like so:

<?php print t('Menu') ?>

This will make the string translatable in the admin interface.


Slideshow for the homepage. Views Slideshow or another Module? I would like to have a slideshow with pagination on my homepage. Should I use Views Slideshow or is there another Module which is flexible and will give me the ability to add a slideshow block?

IMHO, adding a module for this is overkill. I prefer to create a view, add the jQuery Cycle plugin to my theme and apply the plugin to the view using just a few lines of javascript.


How to get Node IDs of nodes whose titles contain a certain string? I'm trying to get a list of nodes whose titles contain a given string, in this case the term name of a term attached to another node.

Based on other answers I've found online, I've thought this could work:

$sql = 'SELECT title FROM {node} WHERE title LIKE :title';
$result = db_query($sql, array(':title' => '%' . db_like($term->name)));

That's giving me a response but it's all empty, which makes no sense.

Here's what the response looks like:

DatabaseStatementBase Object
(
[dbh] => DatabaseConnection_mysql Object
    (
        [needsCleanup:protected] =>
        [target:protected] => default
        [key:protected] => default
        [logger:protected] =>
        [transactionLayers:protected] => Array
            (
            )

        [driverClasses:protected] => Array
            (
                [SelectQuery] => SelectQuery
                [MergeQuery] => MergeQuery
                [UpdateQuery] => UpdateQuery
                [DatabaseSchema] => DatabaseSchema_mysql
            )

        [statementClass:protected] => DatabaseStatementBase
        [transactionSupport:protected] => 1
        [transactionalDDLSupport:protected] =>
        [temporaryNameIndex:protected] => 0
        [connectionOptions:protected] => Array
            (
                STUFF
                    (
                        [default] =>
                    )

            )

        [schema:protected] => DatabaseSchema_mysql Object
            (
                [connection:protected] => DatabaseConnection_mysql Object
*RECURSION*
                [placeholder:protected] => 0
                [defaultSchema:protected] => public
                [uniqueIdentifier:protected] => 5670ef6385b8e5.94304345
            )

        [prefixes:protected] => Array
            (
                [default] =>
            )

        [prefixSearch:protected] => Array
            (
                [0] => {
                [1] => }
            )

        [prefixReplace:protected] => Array
            (
                [0] =>
                [1] =>
            )

    )

[queryString] => SELECT * FROM node WHERE title LIKE :title
)

Do I need to do something like this using CONTAINS instead?

$sql = 'SELECT title FROM {node} WHERE CONTAINS(title, :title)';
$result = db_query($sql, array(':title' => '%' . db_like($term->name)));

You need iterate over the node collection, you can use this code to do so:

$sql = 'SELECT title FROM {node} WHERE title LIKE :title';
$result = db_query($sql, array(':title' => '%' . $term->name . '%'));

foreach($result as $node) {
    //dpm($node);
    //$node is your object
    echo $node->title . '<br>';
}

Edit: If you want only specifics content types use this:

$sql = "SELECT title FROM {node} WHERE title LIKE :title AND type = 'your_content_type'";


Login link with destination I am trying to create a login link in Drupal 7 that will

keep the destination if set
generate a destination based on the page on which the link was clicked if not set
persist if set on subsequent clicks of the login link
not be generated if not already set AND the currently viewed page is an undesirable destination (such as user/logout)

I have written the following code and put it into to the body of a block only shown to anonymous users, however, as I am new to Drupal's api can someone more knowledgable here check to see if this is OK or can be optimized, and/or what other destinations other than user/* should NOT generate a destination if the destination is not already set:

<a href="/user<?php $curpath = current_path();
if (strpos($curpath, 'user/') === 0 && !isset($_GET['destination'])) {
  print '';
}
else {
  $newdest = drupal_get_destination();
  $newdestimplode = implode('', $newdest);
  print '?destination=' . drupal_get_path_alias($newdestimplode);
} ?>">Login

Alternatively if you know of a setting that puts the login link on pages for anonymous users with the above conditions or a LIGHTWEIGHT module (please don't suggest LoginTobboggan) that does this, let me know here.

I wrote this THEME_menu_link override to add a destination parameter to login links:

e.g in template.php:

/**
 * THEME_menu_link override
 * Add unique class (mlid) to all menu items.
 * Add destination param to login link
 */
function THEMENAME_menu_link($variables) {

  $element = $variables['element'];
  $sub_menu = '';

  $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  // Add destination to login link
  if ($element['#href'] == 'user/login') {
    $status = drupal_get_http_header('status');
    // don't add dest back to 403 etc..
    if(strpos($status, '403') !== FALSE){
      $dest = drupal_get_destination();
    }elseif(strpos($status, '404') !== FALSE){
      $dest = array('destination' => 'home');
    }elseif(strpos($_GET['q'], 'user/register') !== FALSE){
      $dest = array('destination' => 'home');
    }elseif(strpos($_GET['q'], 'user/login') !== FALSE){
      $dest = array('destination' => 'home');
    }elseif(strpos($_GET['q'], 'user/logout') !== FALSE){
      $dest = array('destination' => 'home');
    }else{
      $dest = array('destination' => drupal_get_path_alias());
    }
    $element['#localized_options']['query'] = $dest;
    $element['#attributes']['class'][] = 'login';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}


How to filter a node reference field in content type form I have a node reference field (User groups) in my content type; i would like to apply a filter on that field to show only the Groups belonged to the current user.
How can i apply that filter in the content type insert/edit form?

I've written step by step instructions on how to do that.

Your setup will be a bit different since you don't use flags. "Step 3" describes how to use the "views reference" feature to show the referenced nodes on your node/add,edit page using views.


Unable to upgrade from version 5.10.0 to version 8 I tried upgrading from Drush 5.10.0 to Drush 8 using sudo composer global require drush/drush:~8, but it doesn't update anything.

  Changed current directory to /home/lupiyardo/.composer
  Running composer as root/super user is highly discouraged as packages, plugins and scripts cannot always be trusted
  ./composer.json has been updated
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update
  Generating autoload files

As confirmation Drush wasn't updated, the output of drush --version is Drush 5.10.0.

I looked at the composer.json file and it contains 'require': { }.

How can I upgrade Drush?

The following code works for me in Linux Machine:
    cd /usr/local/bin
    mkdir drush-8
    cd drush-8
    composer require drush/drush:8.x
    ln -s /usr/local/bin/drush-8/vendor/bin/drush /usr/local/bin/drush8

Let me explain a little bit:

Go to folder /usr/local/bin
Create a new folder drush-8  * go
to the folder above
Install drush (here more info:
https://docs.drush.org/en/master/install/ )
Finally, create a Symbolic Links that point to new drush version


advantages of drush bam vs. drush sql-dump / drush sql-connect Is there any comparative advantage in terms of best practice, ease of use, or speed in terms of using the drush back up and migrate command (drush bam) or is it just preference?

I'm often using just a simple drush sql-dump > exportdb.sql and a $(drush sql-connect) < importdb.sql to backup a database. I find it pretty easy to use.

There aren't giant differences between the two approaches. Here are a few small differences:

drush sql-dump uses mysqldump program in the background and so is must faster than the pure PHP approach taken by BAM.

You can easily skip tables with sql-dump as well. See the help for this command.

Finally, some folks might want to use sql-sync which does all of these steps in one command. It works faster than sql-dump+sql_connect when one of the machines is remote. It also includes optional data sanitization.


Change system mail on run time when sending mail I have 4 domains using domain access module like a.com, b.com, c.com, d.com. currently when user registers he receives a mail from admin@a.com which is default in site configuration. Now what I want is to Change system mail on run time with respect to 4 diffrent domains so that when user registers from b.com he will receive mail from admin@b.com and so on.As this info is saved in system configuration so how to change the mail id of the site when sending mail on run time.

You can alter the mail using hook_mail_alter(&$message)

  Alter an email message created with MailManagerInterface->mail().

with in message array you have 'from' field as well.

Example

function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {
    // Login to get domain specific email id.
    $email_id == _some_logic_to_get_email();
    $message['from'] = $email_id;
  }
}

Refernce: https://api.drupal.org/api/drupal/core%21core.api.php/function/hook_mail_alter/8.2.x


Theme multiple rendered nodes as item_list I am retrieving/rendering multiple nodes successfully with the following code:

$nodes = node_load_multiple($nids);

$rendered_nodes = node_view_multiple($nodes, 'custom_view_mode');

return render($rendered_nodes);

I would like these nodes to be rendered as an item list. I have attempted to set the #theme property of the array to 'item_list' but it does not seem to be working. What is the correct way to theme this array of nodes returned by node_view_multiple()?

This should render multiple nodes using an item list.

$nodes = node_load_multiple($nids);
$build = array(
    '#theme' => 'item_list',
    '#items' => array_filter(reset(node_view_multiple($nodes)), function(&$node) {
        if (!is_array($node)) {
            return false;
        }

        $node = drupal_render($node);
        return true;
    }),
);

return drupal_render($build);


Display Exposed Filter value of selected exposed filter I work on drupal 7, and create a page from views used 4 exposed filter. I want to display exposed selected values., and also close button in exposed selected values

I try to selected data in field and excluded it and  used  in header Global: Unfiltered text. But not work properly.

You have a couple of options here Rituraj.

You'd need to use PHP to output the selected values in the header. See the related example here to see how to output view filter values to a template.

<?php
$view = views_get_current_view();

if(isset($view->exposed_input['field_release_date_value']['value']['year'])) {
  echo "
Press Releases for ", $view->exposed_input['field_release_date_value']['value']['year']; "
";
}
else {
  echo  "
Press Releases for ", date("Y"); "
";
}
?>

This post has an example for using an exposed filter value to override the page title as well.

My preferred method would be to use JQuery to read updates from the exposed filter and inject them into the DOM. That would have the added bonus of making it easy for you to wire up the X links to remove both the value both from the display and from the exposed filter.


Prefill content type form field with alter hook I've created a content type with a link type field.
When an user add this content type I want to prefill the link field with the user email.
I've a create a new module named prefilllink with an alter hook :

function prefilllink_alter(&$form, &$form_state, $form_id) {
  dsm($form);
  switch($form_id) {
    case "job_node_form":
      $form["field_apply"]["und"][0]["value"]["#default_value"] = $user->mail;
      break;
  }
}

But it doesn't work... Any idea?

You need to implement either hook_form_alter() or hook_form_FORM_ID_alter() (there's no hook_alter() which is what your code is implementing at the moment).

The second is probably preferable as it targets the form you're interested in:

function prefilllink_form_job_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $form["field_apply"][LANGUAGE_NONE][0]["value"]["#default_value"] = $user->mail;
}


Is db_set_active a global or local setting? I need to run a new query on another database.

I configured the settings.php

 $databases = array (
      'default' =>
      array (
        'default' =>
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
      'slave' =>
      array (
        'default' =>
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
    );

and this is my custom function:

    function myModule_test()
{

    db_set_active('slave');

    sleep(90);

    $view = views_get_view('test_view');
    $view->set_display('page');
    $view->pre_execute();
    $view->execute();

    print $view->render();
    db_set_active();

    }

the query is performed on the second database, what I do not understand is if the database change is local or global, because during the sleep (90) I tried to insert a new 'article' content and it has been inserted into the 'default' database.

It's a per-request global setting. db_set_active calls:

Database::setActiveConnection($key);

Which sets the static $activeKey property of the Database class.

Database::getConnection(), which is where the connection for all queries comes from, then uses that same static $activeKey.

So once you've used db_set_active, all queries in that request will use the new connection until changed again.

It doesn't persist across multiple requests.


How can I run a database query in code? I want something like SELECT nid FROM node WHERE type = "blablabla".

How do I do this in Drupal 8 PHP code?

You would use the database abstraction layer.

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute();

As for executing the query, you can also fetch results in various ways.

Examples:

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAll();

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAllAssoc('nid');

If you are within a class, you should inject the appropriate classes in your constructor instead of use the static Drupal container. But since you are in a preprocess function, \Drupal::database() is fine.

From core/lib/Drupal.php:

 /**
   * Returns the current primary database.
   *
   * @return \Drupal\Core\Database\Connection
   *   The current active database's master connection.
   */
  public static function database() {
    return static::getContainer()->get('database');
  }

Depending on your use case(s), you can also leverage EntityQuery:

$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$results = $query->execute();

Please note that you may want to use node_field_data table instead of node, but your query is pretty generic so it is hard to tell without a better query.

Example, get all nodes of type that are published:

$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->addField('nfd', 'nid');
$query->condition('nfd.type', 'blablabla');
$query->condition('nfd.status', 1);
$results = $query->execute();

Or:

$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$query->condition('status', 1);
$results = $query->execute();