How to create popup for email link with major email provider links? Check out this new feature craigslist implemented. WHen you click on this button (like in the link below) that says "reply to this post", it pops up with this popup that shows the different email providers options (for web browsers, and local clients like Outlook).

How can this be done for Drupal?

First take a look here. Lots of JQuery plugins that integrate with Drupal.

I think Lightbox best fit here but check the rest. It provides a pop-up overlay similar to Craigslist's

I myself don't have any experience with these but since no one has answered thought I could try point you somewhere useful.

I did a quick search and also found these that could lead somewhere:

http://www.lullabot.com/articles/announcing-beautytips-jquery-tooltip-plugin
http://www.jquerypopup.com/

Anyway, I hope those hints helps you in some way.


Print a block inside a Views header or Views footer using PHP input There seems to be multiple ways of printing a drupal 7 block via php input filter. What is the most efficient way of printing a drupal block in Views header or Views footer attachment of a global text php input filter?

Try this module https://www.drupal.org/project/views_block_area - it allows insert any block into the view's header or footer.
Another way using code

$blockObject = block_load('module', 'delta');
$block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
$output = drupal_render($block);
print $output;


Hierarchy management solution(s)? (node or taxonomy) I have a content type with a large number of nodes (70K+) and have integrated a straightforward, though custom, node hierarchy solution (node reference for the parent, sibling order using delta).

I'm implementing a custom hierarchy management tool and have started out playing with taxonomy because the hierarchy management is already present (drag & drop). However, core's default taxonomy management only goes so far, and though a good starting point, will not be suitable for a vocabulary this size (moving a large piece of the tree somewhere else isn't possible, as the vocab is paginated).

I then thought about a view combo'd with VBO, and a few custom actions, but i'm not sure drag & drop could be used with this method.

Question:
Have you used (or seen) a drag & drop hierarchy management solution (node or taxonomy) implemented either in views or a contributed module that fits this scenario?

Yes, the wonderful Taxonomy Manager module. I don't start a big project without it these days:

  This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

It's packed with features, there's a list of them on the module page. I think this one in particular will be of interest to you:

  Double Tree interface for moving terms in hierarchies, adding new translations and switching terms between different vocabularies


How do I add a variant programmatically? I have many sites in an installation that have many Panels pages. Many of them need a HTTP Response (404) variant added to them, which I would like to do programmatically.

Assume I have the page already via:

$page = page_manager_page_load($pageName);

Modifying something in the page is easy. Make the change then call page_manager_page_save($page);

It seemed the easiest way to accomplish adding a variant was to take an exported variant and import it. This is what the clone function does.

Here is an exported variant:

$handler = new stdClass();
$handler->disabled = FALSE; /* Edit this to true to make a default handler disabled initially */
$handler->api_version = 1;
$handler->name = 'page_bes_homepage__http_response_0ab6f1a9-9c98-459c-b4d3-10f63ddace56';
$handler->task = 'page';
$handler->subtask = '';
$handler->handler = 'http_response';
$handler->weight = 1;
$handler->conf = array(
  'title' => '404 Error',
  'contexts' => array(),
  'relationships' => array(),
  'code' => '404',
  'destination' => '',
  'name' => '',
);

It doesn't appear necessary to set the subtask or provide a new name since the page_manager_handler_add_to_page() appears to handle that (though at first I set those myself; didn't help).

Attempting to add and save via:

page_manager_handler_add_to_page($page, $handler);
page_manager_page_save($page);

doesn't work. Some code in page_manager.module had me think that the failure might might be because of ctools caching so I tried this:

page_manager_save_page_cache($page);
page_manager_clear_page_cache($pageName);
page_manager_page_save($page);

and that doesn't work either. Scouring the web for an example of this has not turned up anything in code snippets, tutorials or books and ctools doesn't provide this level of documentation.

How does one add a variant programmatically? Note that I do not want this in Features and I do not want this stored in code via the ctools api. I just want to run through a list of Panels pages programmatically and add a variant.

You can try this:

I found how to store manually created variants in code for custom pages (e.g. '/node/%node/test')

function MODULE_default_page_manager_pages() {
  // Copy exported page code here.

  $pages['UNIQUE_PAGE_ID_HERE'] = $page;

  return $pages;
}

Putting everthing in a file called 'MODULE.pages_default.inc' in your MODULE's main folder, and link that file with my MODULE.module via

/**
 * Implement hook_ctools_plugin_api().
 *
 * If you do this, CTools will pick up default panels pages in
 * MODULE.pages_default.inc
 */
function MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'page_manager' && $api == 'pages_default') {
    return array('version' => 1);
  }
}

Source: https://www.drupal.org/node/579036


Database schema for image field I have a module which behaves much like question and answers. Each question needs to have a help image. So far, I have written the schema as this:

function mymodule_schema() {
  $schema(mymodule_questions) = array(
      'description' => 'Stores questions for my module',
      'fields' => array(
          'qid' => array(
            'type' => 'serial',
              'not null' => TRUE,
              'description' => 'Primary Key: Question ID.'
          ),
          'prompt' => array(
             'type' => 'text',
              'not null' => TRUE,
              'size' => 'normal',
              'description' => 'Question prompt',
              'length' => '1000'
          ),
          'option_type' => array(
              'type' => 'varchar',
              'not null' => TRUE,
              'description' => 'Option Type',
              'length' => '255'
          ),
          /* Image field schema goes here */
      ),
  );
}
?>

Now, I want to add an image field, i.e. a field where admins can upload images to be shown with each question. What should be the schema for this field? Should I use the Field API in the schema (is that possible?)? If yes, how?

Thanks.

Kaustav Das Modak

To be able to integrate with field API, you would need to declare your custom data thing as a fieldable entity. This is possibly, but it is quite a bit of work and then you'll have to add the field in a install hook.

What you can do as well is simply add a single 'fid' integer column to your table, add a form element of #type 'managed_file' to your form, which will automatically save the file for you and create an entry in the file_managed table. You can then simply reference the fid (file id) of that object. Also note that you need to call file_usage_add() so that the managed file knows that it is in use. When your object is deleted, use file_usage_delete() then the file will automatically be removed.

This is exactly what is done in Drupal 7 for profile pictures, have a look at user_save() for an example.


What is 'value' type of the field? Could you please explain how it works:

$form['support']['priority']['#type'] = 'value';

On my site this code is used to hide Priority field. But I don't understand the logic (I'm pretty new in Drupal). What is really this 'value'.

Check Form API documentation on this. It looks like someone hid field priority from output so users can't see or change it from form, but value of this field still can be used on form handlers.


What entity should entity_id be joined on? I'm writing a complex custom query to get order information from a Drupal Commerce install for export.

The table field_data_commerce_customer_address has a column entity_id. I've tried to join that field on order_id, but my results are incorrect. It doesn't match to user id... hmm.

What field should I join entity_id on?

And, more generally, is there a drupal entity informational function that would tell me what columns should be joined to what? Or a master entity table, or anything? Some central location that would tell me things like this so I don't have to dig around?

Looking around the database and googling but haven't found it yet.

The customer addresses are linked to the user, see https://drupal.stackexchange.com/a/121356/2322 for more details on this, so you've got an order that references a customer profile and this references a user.

It doesn't show this part, but find a more complete description about the commerce entities in this documentation page: http://www.drupalcommerce.org/user-guide/products

In any case, I'd definitely use Entity Field Query for this, it will save you from digging in the database and it will give you a more consistent way to access your data.


TRUNCATE error -1 obliterating my sites I keep getting a cache related error.

  PDOException: SQLSTATE[HY000]: General error: 1030 Got error -1 from storage engine: TRUNCATE {cache} ; Array ( ) in cache_clear_all() (line 165 of C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc).

The issue is tied to the query file. The fix is to replace TRUNCATE with DELETE FROM in a query.inc file. That's all fine and dandy, and that error is gone. But, now I have a new one: The site is completely broken and thinks that the cache database folder still exists, which prevents me from importing the backup database, even if I drop the whole database.
In short: Backups are useless, as this error seems to do some heavy damage. As well, it shuts down the EasyPHP server.

To make things even worse, I was going over the huge site-crashing error report I just got, and it looks like the fix doesn't even work.

In regards with the above, I think it worked, but something else tied in with it is causing more cache errors.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'webone.cache_views_data' doesn't exist: DELETE FROM {cache_views_data} ; Array ( ) in cache_clear_all() (line 165 of C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc).

I applied the fix I first mention to a new website, as a preventative this time. Low and behold, it came back on the first module install.

Why are these paths different when you talk about "your project":

path 1:
C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc

path 2:
C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc)

This smells like something is horribly misconfigured.

I've made dozens of drupal sites, typically under Linux, but I have used WAMP myself in the past (not EasyPHP-DevServer). This makes me think it's an issue with the EasyPHP-DevServer and not drupal itself.

While you may not be familiar with it ... have you tried like copying your site files and DB to a Drupal 7 Quickstart project VirtualBox virtual machine, or  DrupalPro ... another off the shelf VM drupal-in-box ...


How to delete values in Link field? I have a content type with a Link field which allows an Unlimited number of values. However, it appears there is no way to Remove values like there is on an Image field with multiple values.

With an Image field, there are Remove buttons next to each item so that I can remove them:

Any idea why the Link field doesn't have a Remove button? I'm logged in as user #1 (an administrator) and just to be sure I've double checked that I have all permissions and such.

Any ideas?

It's perhaps not that obvious but all you need to do is empty the text field containing the value you want to remove. Once you save the entity the value will be gone.

Files need a remove button as there's no other way to 'empty' that particular field (a round-trip to the server is required to purge the file that was temporarily uploaded). Other, less complex fields (like text fields), don't need to contact the server via Ajax to do that, so I guess the remove button is deemed unnecessary.

If you're interested in the mechanics of this, have a look at the hook_field_is_empty function, which all field modules are required to implement.


How can I show the field setting options like "Style Settings", "Rewrite Results" in Views I created a view and added some fields, I saw others can configure field options like "Style settings" and "Rewrite Results", but in my "Configure Field:" window, I don't have these options, only several blank rectangles. See below image,

Is there any settings I missed or any new modules I didn't installed?

It's a jQuery issue. Downgrade to 1.5 for administrative pages only (admin/config/development/jquery_update). Greater versions break views and other admin areas - not sure why though


Custom List of all items in Webform After 10 webforms have been added. How could we creat a HTML report to list all items inside drupal ?

Yeah, it sounds like you need to create a view to output submissions.

Webform helps you here by integrating fully with views so you can pull out whatever data you need. You can also create a view per webform which will enable you to have a separate page for each.

Failing that, if you go to Content Management > Webforms it gives you a summary of all webforms on the site with links to view submissions, export them, etc.

Hope this helps.


Programmatically accessing field values for a file in a custom form I have the kint() output below.

How do I get the values for the destination index?

Since the values array is a protected value, you can only access its value with a method (e.g. a magic method).

The File class extends ContentEntityBase, from which it gets the values property and the magic method that allows to access it. Supposing that $file is the variable containing an \Drupal\file\Entity\File object, you just need the following code.

$destination = $file['destination'];

Longer Explanation

The method that allows to access the content of the values array is ContentEntityBase::__get() (a magic method) that allows to access the value of an object as it would be an array. ContentEntityBase::__get() checks also the content of the values array; in fact it contains the following code.

  // Else directly read/write plain values. That way, non-field entity
  // properties can always be accessed directly.
  if (!isset($this->values[$name])) {
    $this->values[$name] = NULL;
  }
  return $this->values[$name];

So, using $file['destination'], that method would return you the value of $file->values['destination'] you cannot directly access.


Download count of file in table of files So I wanted to add date alongside the size of the file in filefield table of files so I added this snippet to templates.php

function mytheme_file_formatter_table($variables) {
  $header = array(t('Attachment'), t('Size'),t('Upload Date and Time'));
  $rows = array();
  foreach ($variables['items'] as $delta => $item) {
    if ($item['timestamp'] == 0) {
      $item['timestamp'] = 1234567890;
    }
    $rows[] = array(
      theme('file_link', array('file' => (object) $item)),
      format_size($item['filesize']),
      format_date($item['timestamp'],'custom','Y/m/d - g:i'),
    );
  }
  asort($rows);
  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}

It works just fine but I also need to show the download count of the file, and I have no clue on how to do this. Thanks

There's many ways to get this working depending on the type of file access you want.

File Download Count - counts download when it's really been downloaded and not just clicked, new so I can't post more than 2 links. Google this.

Public Download Count - track public files

Download Count - track private files


EFQ - sort by reference entity label I'm trying to add an sort condition to an EFQ on an reference entity table, I think a code example explains this better.

$query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
$ids = $query->condition('type', 'some_type')
  ->condition('some_more', 'conditions')
  ->sort('a_term_field', 'ASC')
  ->execute();

Now what happens is that the nodes will be sorted by the term id (since that is what is stored in the field table) but I would like to sort on the term label instead. Is something like that possible with EFQs?

Have you tried ->sort('a_term_field.entity.name', 'ASC'), that should work.

Some limitations exists with multilingual fields, as it is not defined on which language it should be sorted.


How can I manage a users collection of products? I am pretty new to Drupal, and I am tasked with creating a Drupal 7 site that has a lot of products; I need to enable users to maintain a list of the products that they own/have.

Basically I need the ability to take a list of products and allow a user to check off the ones they have and the ability to save this data associated with the user. Is there a module that I should take a look at, or can someone point me in the right direction?

Check out the Flag module.  You could create a product content type and then your users could flag which individual products they have.


Change the title of date_popup filed in custom form I'm building a custom form in Drupal 7 and i need to use the date_popup widget in it. It all works as expected, except the title of the field.

My code is:

  $form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
  );

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

But it keeps showing the default label "Date" for the field, as you can see on in the picture below.

Can you please let me know how can i put Start date and End date as field labels instead of just Date, or correct me if i'm doing something wrong

Just use the following code:

'#date_label_position' => 'none',

your code :

$form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
    '#date_label_position' => 'none',
  );

  $form['filter']['end_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('End date'),
    '#date_label_position' => 'none',
  );


How do I convert a Drush make commit-level dependency into Composer? I am remaking old project to use composer for building and I have a problem I cannot find solution to. Basically this is how library is defined in profile.make file:

; HybridAuth
libraries[hybridauth][directory_name] = 'hybridauth'
libraries[hybridauth][type] = 'library'
libraries[hybridauth][download][type] = 'git'
libraries[hybridauth][download][url] = 'https://github.com/hybridauth/hybridauth.git'
libraries[hybridauth][download][revision] = 'd4e5bc34008e8c187c302eb4e94200ee4a208c63'

How should I rewrite it correctly in my composer.json file? To be precise, how to get revision? This is what I have so far:

{
      "type": "package",
      "package": {
        "name": "library/hybridauth",
        "version": "d4e5bc34008e8c187c302eb4e94200ee4a208c63",
        "type": "drupal-library",
        "dist": {
          "url": "https://github.com/hybridauth/hybridauth.git",
          "type": "git"
        }
      }
    },

it is complaining about my "version" line:

  [Composer\Repository\InvalidRepositoryException]
  A repository of type "package" contains an invalid package definition: Inva
  lid package information:
  version : invalid value (d4e5bc34008e8c187c302eb4e94200ee4a208c63): Invalid
   version string "d4e5bc34008e8c187c302eb4e94200ee4a208c63"
  Invalid package definition:
  {"name":"library\/hybridauth","version":"d4e5bc34008e8c187c302eb4e94200ee4a
  208c63","type":"drupal-library","dist":{"url":"https:\/\/github.com\/hybrid
  auth\/hybridauth.git","type":"git"}}

The location you're defining it at is wrong. When defining your own packages, the version tag is used to target branches or tags. If you want specify a commit-level project requirement, do it in require object where you're specifying your requirement in the  dev-${BRANCH}#${COMMIT_HASH} format.

In repositories:

{
  "type": "package",
  "package": {
    "name": "hybridauth/hybridauth",
    "version": "master",
    "type": "drupal-library",
    "source": {
      "url": "https://github.com/hybridauth/hybridauth",
      "type": "git",
      "reference": "master"
    }
  }

In require:

"hybridauth/hybridauth": "dev-master#38f0735",


How to allow users to choose different theme? Some of my site users prefer a light theme, others prefer dark one. In drupal 6, is there a way to allow users to choose their favorite theme? How?
Thanks

I didn't look this up, but if I'm not mistaken, you should enable the themes users can choose from, and give the appropriate user role(s) the "select different theme" permission.


Node body not preserving HTML formatting? The body area of my node is set to WYSIWYG. When I enter in HTML formatting (using the WYSIWYG buttons), it doesn't make it to the content type template:

print $node->content['body']['#value'];

Why doesn't the HTML come through? How can I print the node body to the page and preserve the HTML formatting? What am I doing wrong here?

Thanks!

Your input format is likely "Filtered HTML", or something other than "Full HTML". Check the input format (below the body textarea when editing the node).


"Codebase is assembled with Composer instead of Drush" (but it wasn't!) message I'm using D7 and I'm seeing the following error message any time I try to use Drush to install a module:

  This codebase is assembled with Composer instead of Drush. Use composer update and composer require instead of drush pm-updatecode and drush pm-download. You may override this error by using the --pm-force option.

Why does Drush generate that error message? The website was not built using Composer (though there are other Composer-based Drupal project on the same web server).

FWIW, using the --pm-force option works just fine. I would just understand the reason of that error message.

It comes from a command file like policy.drush.inc.


Custom Profile Type and UPS Shipping Service I have an issue that I have been wrestling with for a few months now. I have a B2B site that needs a separate "Drop-shipping" shipping address field from the default shipping address that comes with commerce shipping. The fields need to be different because the client wants the default shipping address field to be constrained to only items in the users address book (controlled by the client, not the customer and created by the site admin when adding new registered users) but allow the second "Drop-shipping" added field to be an editable address form for drop-shipped addresses.

So, using the module "Customer Profile Type UI" I created the "Drop-shipping Information" profile type. Using "Checkout Pages" module I created a new page named "Drop-shipping Information" positioned before the checkout page, with a drop-shipping check-box. It is obviously the first page the customer will see when entering the check-out process, and before the checkout page, so that I can capture a Boolean value that will drive which check-out pane ("Drop-shipping Information" or just "Shipping Information" address fields) are shown on the checkout page.Then I use rules and "Change pane properties" to disable the "Shipping Information" pane if the user has selected "Drop-shipping" on the first page, and vice-verse if not. All of that works properly.

The problem is, when "drop-shipping is selected and a valid address provided, when moving from the checkout page to the shipping services page (with UPS enabled and tested to return rates), it returns the rates for the "Shipping Information" address, and not the "Drop-shipping Information" address.

I realize that rules may only be hiding the default "Shipping Information address form (which is including a default shipping address from the customers account profile) ... but how do it make it use the address in the "Drop-shipping Information" address form instead?

Not sure what I am doing wrong, and I see no configuration options to change the behavior. Can someone tell me what I might be missing or perhaps provide an alternate method (that doesn't require custom coding) after reading the details of my requirements above? Either way, you should know that I am not a developer, and could use at least some mid-level instruction on what I have missed or need to do.

Thanks in advance for any serious help. :)

Commerce UPS calls commerce_physical_order_shipping_field_name($order) to determine what field holds the shipping profile for a given order. That means you can then use Commerce Physical's hook_commerce_physical_order_shipping_field_name_alter() to specify a per-order shipping profile field.


Include third-party library I have a third party library located in the root/libraries directory, but it is not called on my webpage. I was wondering using subtheme/subtheme.theme or subtheme.libraries.yml. I call it from here? Any information would be great, I can't find documentation on third party libraries for Drupal 8.

You can add your library in your file theme.libraries.yml (or module.libraries.yml) like this:

# Parsley use for contact_form.
parsley:
  js:
    dist/js/vendors/parsley.min.js: { minified: true }
  dependencies:
    - core/jquery

After, you can include your library like any other libraries with a hook or a template.


How to use mysql queries in Action in a Triggered Rule? I created a triggered rule. The action will 'fill a field'. To get the value for this field I need to get a value saved in sql database. Then I check to set the value using php and create this code:

$result = mysql_query("SELECT field_codigo_value FROM content_type_inmuebles_en_venta SORT BY field_codigo_value LIMIT 1");
$value = mysql_fetch_array($result);

return array(
  0 => array('value' => $value )
);

But I get this error message:

  warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/drupal6multilingual/sites/all/modules/rules/rules/modules/php.rules.inc(107) : eval()'d code on line 2.

First off, you should be using the drupal SQL coding conventions:

db_query instead of mysql_query
db_fetch_array instead of mysql_fetch_array

I would structure the query like so:

$query = "SELECT field_codigo_value
          FROM content_type_inmuebles_en_venta
          SORT BY field_codigo_value
          LIMIT 1";

$result = db_query($query);

return $result;

You should know that triggered rules allows you to pull a value out of the database without writing a custom query. We need a bit more context as to how this node is related to your triggered rule, but I would guess that you can load the node that you just created or load a referenced node to the node that you just created and then use the available tokens to fill in the CCK field that you need filled in.


Garland theme and h2 heading On D6.2 I'm using Garland. But instead of generating h1 tags for the title it is generating h2 tag.
What is the best way to make it generate h1 instead of h2?
Should I subtheme it and modify page.tpl.php?
Isn't there any settings or module which can do it?

Subtheme is the answer. The theme is the last line in the rendering of the page which is why you generally can't override it. The H2 tags is most likely hardcoded in the page template which is why you can't alter it.

that being said, you could in a module make garland use a page template that your module has created. This require some complex altering of the Drupal theming system, and is not something you want to do, unless you understand the consequences.


How can I remove the descriptions from the registration page programatically? Using the custom module mentioned here https://www.drupal.org/node/754542#comment-2775706 I was able to remove the descriptions from the user login page.

function alterlogin_form_user_login_alter(&$form, &$form_state) {
  $form['name']['#description'] = t('');
  $form['pass'] = array('#type'  => 'password',
                        '#title' => t('Password'),
                        '#description' => t(''),
                        '#required' => TRUE,
                       );
}

however when I try

function alterlogin_form_user_register_form_alter(&$form, &$form_state) {
  $form['name']['#description'] = t('');
}

the description stays the same. I know it's targetting the page because

function alterlogin_form_user_register_form_alter(&$form, &$form_state) {
  $form['name']['#description'] = t('');
  $form['pass'] = array('#type'  => 'password',
                        '#title' => t('Password'),
                        '#description' => t(''),
                        '#required' => TRUE,
                       );
}

creates a password field on the registration page (that I assume does nothing).

Your structure is just a bit off.

$form['name']['#description'] = t('');

Should be:

$form['account']['name']['#description'] = t('');

If your ever unsure of what an array looks like, always a good idea to download devel and dpm item so you can see what the structure looks like.


Link a div to content I have made a 3d Hover effect for a Team Members about page. When you hover over a photo it flips like a box and reveals peoples credentials. I want to be able to make the div link to the team members content (the page that goes further into depth about each individual team member). I have re-written the code like so:

          [field_photo]

 [title]

 [field_position]

I tried linking it like:  . Unfortunately, no luck... I saw that I could make a php function but there must be an easier way !! if anyone could help me out that would be greatly appreciated (=

Add a field to your view of type Content:Path and drag it to the top of your field list. Then your href should be:


D7: jQuery script for creating 'active' links in menu system. (partially works) This is such a pity D7 does not have by default active links sets in the menu system. I mean everyone likes to have a clue where he is in the site by the active state of the menu.

I wonder why there is no such default feature in Drupal7?

Now I tried to do this in jQuery like this (see below) but it only works for predictable URL like static pages (it doesn't work for menu links created out of taxonomy terms). If someone can help me make it work for all the links in the menu I would appreciate.

  <script type="text/javascript">
  /*Script for creating active links*/
  $(document).ready(function(){
   var currentURL = document.location.pathname;
   var activeTopLevelPageArray = currentURL.split('/');
   var activeTopLevelPage = activeTopLevelPageArray[1];

   // applying the class to what we find
   $('#header ul li a[href^=/'+activeTopLevelPage+']')
    .addClass('active');
   // now making the nav menu do what we want with styles for the active element
    $('#header #primary-menu ul li a.active:first')
    .addClass('current-main') // assign main active bg to active link
    .parent('li') // select the parent list item
      .addClass('active-trail'); // then assign a class to it for manipulation

    /* If there is no match, just activate the "home" menu item/tab */
    var isActive = $('#header #primary-menu li.active-trail').size();
    if (isActive < 1) {
    $('#header #primary-menu li:first').addClass('active-trail');
    }
});
  </script>

I'm pretty sure Drupal 7 does that for you out of the box. I can see, from my D7 site, I have first, last active-trail classes

Opportunities

Organisations

Events

As can be seen above the LI have the class you require. Do you have any custom code, modules or theme functions causing this not to happen on your site?


drupal 7.12 : multiple taxonomy vocabularies in a single view exposed filter One of my colleagues is working on a project for a departmental store. she wants to create a single views taxonomy drop down filter with multiple (7) vocabularies. The Vocabulary name should appear in the drop down menu but should not be selectable. Some of the vocabularies and their terms are as follows.

Footwear - sandals, shoes, boots, pumps etc

Trousers - chinos, jeans, bottoms

T-shirts - polo shirts, polo neck tops etc

Dresses - maxi, ballgown, one shoulder, tunic etc

Accessories - bags, watches etc

Questions is, is it best to use multiple vocabularies or one vocabulary with multiple parent terms and children. If she uses multiple vocabularies (e.g.. footwear, trousers, tshirts) how can she make the terms in each vocabulary appear in one filter as well as the vocabulary name (but should not be selectable).

On the other hand, if she uses one vocabulary with multiple parent terms and their children, hood can she make the parent terms appear in the drop down menu but not selectable. she tried this method but the drop down is too long and the parent terms are selectable.

alternatively, is it possible to make the vocabulary names appear in one filter and have another filter conditionally showing the terms in the vocabulary selected in the first filter. To add to the complexity, the second filter should show the terms with products and hide those without (this is not a priority). This method will be beneficial but she has no idea how to implement this.

Any suggestions will be greatly appreciated. Thanks in advance.

I recently did the exact same thing for a client. The website is http://www.buyagainbaby.com.

You will notice there are 9 primary categories each with subcategories.  I achieved this by creating 9 different taxonomies. After researching this for weeks, I found this was the best solution. Here is how I did it.

9 taxonomies, each named for the product category you want, Footwear, Trousers, etc, then add as many terms as needed to each vocabulary. Now create one content type for each corresponding category and then assign that vocabulary to that managed fields area. At least this is how I did it.  It was a bit of a chore to get setup, but, bit was worth it. All the search functionality is done with views filters and having it architectured like that lets me do some very complicated things with filters and views.  Let me know if you have questions.  Oh one more thing, keep the content type name the same as the vocabulary name, and that will help tremendously in simplified complicated views to return products, etc.


How to insert a new tag with chosen module ? I installed the chosen module and its library on my site drupal 7.

I created a custom field in a content type to enter tags (words) within the vocabulary (taxonomy).

Everything is working correctly for the selection of tag between those in vocabulary, but I can not insert new tags if they do not exist.

Any help ?

I believe the Autocomplete Deluxe module aims to solve that problem.

Autocomplete Deluxe is a replacement for Chosen module. It has a similar feel to the Chosen module, but allows you to add new tags/terms.


How to find the pressed button Help me please. How can I get the value of the pressed button. Thanks!

$items = [];

foreach ($result as &$value) {
  $items[] = [
    $form['repo'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('FIELD REPO'),
    ],
    $form['repo']['repo_name'] = [
      '#type' => 'item',
      '#title' => $value->name,
    ],
    $form['repo']['user_name'] = [
      '#type' => 'hidden',
      '#title' => $value->name,
      '#value' => $value->name,
    ],
    $form['repo']['submit'] = [
      '#type' => 'submit',
      '#value' => $value->name,
    ],
  ];
}
$form['repositories_arr'] = [
  '#theme' => 'item_list',
  '#items' => $items,
  '#attributes' => ['id' => 'repositories_arr'],
];

return $form;

In the foreach loop of your example, you create multiple buttons and you can set a different/distinct '#name' property property to each submit button, e.g.:

foreach ($result as &$value) {
  ...
  $form['repo']['submit'] = [
    '#type' => 'submit',
    '#value' => $value->name,
    '#name' => $value->name,
  ];
  ...
}

In your validation and/or submit handler you can retrieve the element that triggered the form submission using $form_state->getTriggeringElement()['#name'].


Ability to 'mark' nodes and build a book functionality I am looking for ways to do the following:

users (both anonymous and authenticated) 'mark' nodes in some fashion to say that they want paper copies sent to them
users can set quantity of the paper versions they require
users get review their 'marked' nodes and potentially add/remove items from it
users enter in address to postal system

This problem could probably be solved in several ways, what is the cleanest?

For 'marking' nodes, you'll definitely want the Flag module.


translate a field before rendering I made a content type programmatically with the entity_translation module. There are about 250 fields.

240 fields are not to translate because their values are identical. So I only want to use entity_translation for about 10 fields.

Now i have a lot of checkboxes and select fields. This are all associative arrays. Out of the box the values are shown in English for German and English urls.

E.g.:
Select list: ("keyA" =>''valueA", "keyB"=>"valueB") shows "valueA" or "valueB" as result for the field in the node.
I want the t-function included to use a *.po file for translation.
Thus t('valueA') has to be implemented before rendering the field?

How can I do this?

THX in advance,

In short: use hook_field_widget_form_alter()

/*
* translate the form
*/
function mymodule_field_widget_form_alter(&$element, &$form_state, $context){

if(isset($element['#title'])){
  $element['#title'] = t($element['#title']);
}
if(isset($element['value']['#title'])){
  $element['value']['#title'] = t($element['value']['#title']);
}
if(isset($element['#description'])){
  $element['#description'] = t($element['#description']);
}
if(isset($element['value']['#description'])){
  $element['value']['#description'] = t($element['value']['#description']);
}
}

This translates titles and edscriptions of textstrings.

To show the fields title and description in the given language in node_view:

function mymodule_preprocess_field(&$vars) {
if ($node = menu_get_object()){
  if($node->type == 'immoclient'){
    // Check to be sure there's a label and it's visible.
    if(isset($vars['label']) && $vars['label_hidden'] === FALSE){
      $vars['label'] = t($vars['label']);
    }
    $field_name = $vars['element']['#field_name'];
    $trans_fields = mymodule_trans_fields();
      if(in_array($field_name, $trans_fields)){
        $items = $vars['items'];
        $result = count($items);
        for($i = 0;$i < $result; $i++){
          $vars['items'][$i]['#markup'] = t($vars['items'][$i]['#markup']) ;
        }
      }
     }
    }
   }

and mymodule_trans_fields() returns an array of fields to translate.

To show the items (and here the answer) in the appropriate language for selects and checkboxes in the form, I used hook_form_FORMID_alter:

function mymodule_form_[mynode_form]_alter(&$form,&$form_state,$form_id){
    foreach($form as $key => $value){
      $field = strpos($key, 'field_');
        //only for fields!
          if($field !== false){
            if(isset($form[$key]['und']['#description'])){
            //seems so that every field has a description, to use it for items too
            //build variables
              $res = $form[$key]['und'];
              $desc_t = t($form[$key]['und']['#description']);
              $form[$key]['und']['#description'] = $desc_t;
                }
               }
             }
           }


How to change data type from varchar to text? I'm trying to change the data type of column "mail" from table "simplenews_subscriber" from varchar to text using hook_update_N but its not getting reflected.

/**
 * Implements hook_schema().
 */
function simplenews_schema() {
  $schema['simplenews_subscriber'] = array(
    'description' => 'Subscribers to {simplenews_category}. Many-to-many relation via {simplenews_subscription}',
    'fields' => array(
      'snid' => array(
        'description' => 'Primary key: Unique subscriber ID.',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'activated' => array(
        'description' => 'Boolean indicating the status of the subscription.',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
      ),
      'mail' => array(
        'description' => "The subscriber's email address.",
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'uid' => array(
        'description' => 'The {users}.uid that has the same email address.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'language' => array(
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Subscriber preferred language.',
      ),
      'timestamp' => array(
        'description' => 'UNIX timestamp of when the user is (un)subscribed.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'changes' => array(
        'description' => 'Contains the requested subscription changes',
        'type' => 'text',
        'serialize' => TRUE,
      ),
      'created' => array(
        'description' => 'UNIX timestamp of when the subscription record was added.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('snid'),
    'indexes' => array(
      'mail' => array('mail'),
      'uid' => array('uid'),
    ),
    'foreign keys' => array(
      'uid' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
  );

  return $schema;
}

Update Hook:

function MY_MODULE_update_7001() {
  db_drop_index('simplenews_subscriber', 'mail');
  db_change_field('simplenews_subscriber', 'mail', 'mail', array(
    'type' => 'text',
    'size' => 'medium',
    )
  );
}

Any help of this will be appreciated.

You are missing recreating the index.
Also you can use your schema changes:

$schema = drupal_get_schema_unprocessed('my_module', 'simplenews_subscriber');
db_change_field('simplenews_subscriber', 'mail', 'mail', $schema['simplenews_subscriber']['fields']['mail']);

Another thing you can do is test out altering the table manually just so you can see what errors are popping up.


Why are IDs showing in URLs when clean URLs are enabled? I've enabled clean URLs on my site, and currently, URLs are of the form:

  /node/123

How can I force them to to use human-readable URLs? Something like:

  /node/title-of-node

The Clean URLs setting turns your URLs from index.php?q=node/123 to /node/123.

The path module that comes with core Drupal enables the URL path settings tab on node add/edit forms. Here you can specify any URL alias that will load the node instead of /node/123. These aliases must be entered manually for each node.

The Pathauto module allows you to automatically generate URL aliases. By enabling pathauto and not doing any further configuration your URLs will turn into /content/title-of-node. You can change how the URL is generated in the pathauto settings (so it can be /node/title-of-node for example).


Add attachments to mail How I send a mail with attachments using the mimemail module? In drupal 6 it was using the function:

mimemail($sender, $recipient, $subject, $body, $plaintext = NULL, $headers = array(), $text = NULL, $attachments = array(), $mailkey = '', $send = TRUE)

But I am not able to figure out how to do this in drupal 7.

Try this code. I'm using it with backup and migrate module

$module = 'backup_migrate';
$key = microtime();
$language = language_default();
$params = array();
$params['attachments'][] = array(
  'filepath' => $attachment->path,
  'filecontent' => 'My attachment.',
  'filename' => $attachment->filename,
  'filemime' => 'text/plain',
);

$from = $mail->from;

$send = FALSE;
$message = drupal_mail($module, $key, $to, $language, $params, $from, $send);

$message['subject'] = t('Database backup from !site: !file', array('!site' => variable_get('site_name', 'drupal'), '!file' => $attachment->filename));
$message['body'] = t('Database backup attached.') ."\n\n";

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);

// Format the message body.
$message = $system->format($message);

// Send e-mail.
$message['result'] = $system->mail($message);


Contextual Links not appearing in Panels I use panels to display almost every page on my website. I display content type article as a panel, configured from

structure->content type->article->manage display

The contextual link cogwheel is not appearing on the full content type display rendered through panels, whereas it is displayed on the teaser view, rendered on the site home page, also rendered through panels as a panel page. What might be causing the error? Is there a workaround?

Please apply a patch from Impossible to set attributes on Panels panes on Drupal.org.

This is a patch to the module I believe will fix the problem you have.


How do I get the entity ID when inserting a new node? How do I get the ID of the inserted entity?

I am trying to use hook_ENTITY_TYPE_presave() and hook_ENTITY_TYPE_insert(), but in neither of those I can get the entity ID.

In hook_ENTITY_TYPE_presave(), I used the following code.

 if ($entity->isNew()) {
    print $entity->id();
 }

The ID isn't available in hook_ENTITY_TYPE_presave() (pre meaning before, as in not saved so the database hasn't assigned it an ID yet), but is definitely available in hook_ENTITY_TYPE_insert().

This will work, for example:

function MODULE_node_insert(NodeInterface $node) {
  // No need to check `isNew()`; if it's in an insert hook, it's new.
  $nid = $node->id();
}


Node with 450+ fields, server timeout I have a node with 450-500 fields which I have already splitted in small forms that are being load via ajax.

Anyway, when I get the node form before splitting it, the function _field_invoke (at field.attach.inc) is taking such a long time that makes the server return a timeout. I'm working in a 1 core 2.2MHz 3.5 GB

Is there any way to speed on this function?
Otherwise, what alternatives do I have to speed on the load of a form with 450-500 fields?

EDIT (@Neograph734 comment)

We have a main form with 30 fields, most of them y-n that are used to select sub-forms. The form started to grow as the project was going on, and ended with 10 sub-forms form 30 to 50 fields each one.

We tried to split into different nodes and content types, but we could not find any viable solution: it must be a single document with digital signatures on each form that must be sync one each other, and the whole document follows a status that enables signatures to certain users (when a user has signed every signature field in all sub-forms, then the next user can start to sign). But in fact this is not the question here, as even if there were a better solution, we have no budget now to refactor the whole project, so we have to deal with a form of ~450 fields.

Right now we have rewritten drupal_build_form functionality to store every prepared sub-form in the cache and load them via ajax. So when a user requests the complete node, we give them the whole node but just the first 30 fields are rendered. We provide empty hidden <div>'s that will be filled via javascript with corresponding sub-forms, on demand.

Basically we keep the forms obtained after drupal_retrieve_form, drupal_prepare_form and drupal_process_form on the cache, but we assign a known cid and we store it via  cache_set, so later on we can recover them, remove the fields that we don't want to render, render it and deliver it via ajax. In this way we do not render the whole form at once, but we do it on demand.

At first time we tried to remove the fields that were not going to be used by the user, but we found that we could not submit the form: Drupal said that there were missing fields (when a node is saved, the form must be submitted with all fields, even if they are with an empty value, otherwise it raises an error on node save).

So basically what we are doing is:

Node load (get via browser or ajax) -> look in cache_form table if we find pre-cached form or sub-form, their cid are like form_form-petra_node_form-p0, form_form-petra_node_form-pa, etc... and form_state_form-petra_node_form-p0 and so on.
If we find the pre-cached form, we load it and pass it through drupal_prepare_form, we remove not caching keys (form_state_keys_no_cache()) and then drupal_process_form. This is mostly the same as drupal_build_form does. Then we save the new form to cache_form (with cache_set, an expire time of 3 hours and a random generated cid as it would do drupal_build_form) in order to recover it later in post phase. If this is a sub-form, we merge the rendered sub-form with the parent one obtained via browser get (ajax is in charge of doing so).
If the form is not there, we prepare it from scratch and save it to cache_form as pre-prepared form with expire = 0. Then we follow the same way described just before. This will nearly never happen, as we have installed a cron task that runs once a day and checks if the pre-prepared forms are there or not, and if not, the job prepares them.
If it is a post, we recover the cached form with form_get_cache and we process it with drupal_process_form

So basically we have rewritten drupal_build_form in order to have "static pre-cached forms". This increased speed significatively but right now we are trying to achieve F1 speed with this system.

I doubt that with some many fields for a single node you'll be able to "speed up that function". However, whenever time (and budget?) permits, you should consider what's mentioned in the (illuminating) article titled  "Relativity Model for Drupal". This is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

Note the speed in the last item above ...
The small handful of modules (cfr. the last bullet) is like so (apart from Drupal core):

Chaos tool suite (ctools)
Date
Entity API
Entity reference
Entity connect
Field Group
Token
Pathauto
Views

This same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".


How to get add term form of taxonomy inside node type form? I'm trying to render taxonomy add term form inside content type ('article') add form. (node/add/article)

In hook_form_alter, I called this callback function on abutton.

public function _cvv_ajax_callback(VocabularyInterface $taxonomy_vocabulary) {
    $taxonomy_vocabulary = 'cvv';
    $term = \Drupal::entityManager()->getStorage('taxonomy_term')->create(['vid' => $taxonomy_vocabulary->id()]);
    return \Drupal::entityFormBuilder()->getForm($term);
  }

But this is not return form in my node/add page, rather giving me error:

  error   php   Drupal\Core\Entity\EntityStorageException: Missing
  bundle for entity type taxonomy_term in
  Drupal\Core\Entity\ContentEntityStorageBase->doCreate()

I tried

if ($vocabulary = taxonomy_vocabulary_machine_name_load('jenis_dokumen')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $edit = array();
  $taxonomy_form = drupal_get_form('taxonomy_form_term', $edit ,$vocabulary);
  return drupal_render($taxonomy_form);
}

but this is also not working in Drupal 8.

Also tried:

 $form = \Drupal::formBuilder()->getForm('\Drupal\taxonomy\Controller\TaxonomyController::addForm','plan_features');

didn't worked :'(

Lastly I tried Inline Entity Form , the problem with module is, when a add term form get rendered inside node type form and if you do

kint($form_id); inside hook_form_alter, you won't get any form id for this inline form. Hence if you want to add custom validations for the term title, it won't be achievable even by hooks this module provides.

Please  suggest a way to do this.

Have you tried this module? It's pretty much what you could need:

Inline Entity Form


is there a way to make template for set of nodes? Is it possible to make a template for set of nodes in Drupal 7
for example page--node--[601-602-603-604].tpl
and if so what is it?

You can't do like you explain.

What you can do instead is to add a custom template suggestion for the specific nodes in the preprocess_node function to make the nodes use a specific template that can have any name.


How to use Webform values in Rules? I am using the Webform Rules module and I created an event 'After submitting webform', and an action 'Fetch webform submissions'.

When I add an action 'Show a message on the site', I get all the webform data values and I can print them out in status message.

Now I want to Get the user ID who submitted the webform to send that user a private message (about the form data). But when I add an action 'Fetch entity by ID', I get no webform data values there (I'd like to use a data value as entity ID).

Am I missing something, is this the right way to achieve this ? Any other idea on how to do this please?

Using the Webform Rules module is indeed part of the puzzle to answer your question, as you can read also on its project page:

  This module adds rules integration on webforms.

  Did you ever want to react on webform submission using rules but couldn't find the proper event?

  Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

1. Get the user ID who submitted the webform

Have a look at this example rule (in Rules export format):

{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I intentionally did not include any Rules Conditions here, just to illustrate that by using the Rules Event you're already using, you do have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail]. In other words, you don't need a Rules Action like "fetch entity by ID" for these kinds of tokens to be available.

Of course, because of the nature of your question, you may want to add a Rules Condition to check that the user is not an anonymous user.

2. About the Webform data

The "Webform data"-part of your question seems like an example (variation?) of what's asked for in the feature request "Expose submission data to rules". Here is a summary of it:

  Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue though.

The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

  You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words: checkout the screenprint included in that comment.

So you could use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

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


Year wise archive of blog using views Is it possible to generate a year-wise archive of blogs using views?I need years listed like 2001,2002,...2012 and clicking on the year should display list of blogs for that particular year.
I added a contextual Filter Content: Created year also , but it this query only SELECT DISTINCT node.nid AS nid, EXTRACT(YEAR FROM((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL 0 SECOND))) AS created_year, COUNT(node.nid) AS num_records
FROM
{node} node
WHERE (( (node.status = '1') AND (node.type IN  ('blog')) ))
GROUP BY created_year, nid
ORDER BY created_year ASC .So this results in duplicate value for years

Check “Archive” view from standard Views install for start.
In your case you need to use contextual filter “Content: Created year” instead of “Content: Created year + month”.


Remove date folder on uploaded files Currently the path where the files are saved looks like this: www.mysite.com/sites/default/files/[date when the file is uploaded]/[filename].

Is there anyway to remove the "date when the file is uploaded" directory and save it directly on the files directory?

Thanks!

Yes You can just follow few steps given below :

Go to Structure > Content-Type
Click on Manage Fields of  {{Custom Content Type}}.
Edit the file field . From File directory remove [date:custom:Y]-[date:custom:m].
And you will end up with storing files under files directory


Which version of Drush should I install? Drush 6 works great of corse on a Drupal 6 website, but will I have all of the Drush 6 features when working on a Drupal 7 website? Should I use Drush 7 when working on a drupal 7 website?

I found this post that says you can switch between the two version easily, is this correct?

switch to drush6 command:
composer global require drush/drush:6.*

switch to drush7 command:
composer global require drush/drush:dev-master

Always, always read the docs. Right at the bottom of the first page you'll find this:

Which removes any ambiguity.


Link format as a preview I'm asking if it exists a drupal module that let you make a preview of a link like the Facebook do.

In another way a display format which it gives a preview.

You can also try the Opengraph Filter which sorts of acts like Facebook's link preview. I haven't tried on link fields but it does work on a text body. Pretty neat actually :)


Drupal 7. Replacing core links with their aliases in theme templates I want to check all templates before rendering and replace links
node/1 node/3 ect to their aliases

For example, i have main landing page template
page--front.tpl.php
and there are some links in this template:
Contact
I want drupal to dynamically change such links to their aliases:
Contact
So, if i change alias for specific page, all urls will remain correct

Is it possible?

Not sure if this is what you're after, but
in your tpl.php file you can change

Contact

to

<a href="<?php print url('node/1');?>">Contact


Form state redirect to node path plus fragment How can I redirect a form to the canonical node path + fragment?

Redirect: /nodepathalias#tag

$form_state->setRedirect('entity.node.canonical',
  array('node' => $node->id()),
));

Where should I add the fragment information?

Use the third argument of the setRedirect function:

  array $options: (optional) An associative array of additional options.
  See \Drupal\Core\Url for the available keys.

And if you check that doc:

  @param array $options   (optional) An associative array of additional
  URL options, with the   following elements:

  'query': An array of query key/value-pairs (without any URL-encoding)
  to append to the URL.
  'fragment': A fragment identifier (named anchor) to append to the URL.
  Do not include the leading '#' character.
  'absolute': Defaults to FALSE. Whether to force the output to be an
  absolute link (beginning with http:). Useful for links that will be
  displayed outside the site, such as in an RSS feed.
  'attributes': An associative array of HTML attributes that will be
  added to the anchor tag if you use the \Drupal\Core\Link class to make
  the link.
  'language': An optional language object used to look up the alias
  for the URL. If $options['language'] is omitted, it defaults to the
  current language for the language type LanguageInterface::TYPE_URL.
  'https': Whether this URL should point to a secure location. If not
  defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP.

In your case you should use just fragment:

$options = [
  'fragment'   => 'tag',
];

$form_state->setRedirect('entity.node.canonical',
  ['node' => 8],
  $options
);


Multi instance Drupal on single server. Is SSO possible to be implemented? may I know if we can configure single sign on , on a single server that have 2 Drupal instance running in parallel?

I see that this answer is late but, yes.  I am setting that up now but still working through some config.

I created a D7 installation called auth.local.domain.com (these are currently only on my dev machine).  For this instance I installed oauth2_server and openid_connect_sso modules
I created a separate D7 installation called client1.local.domain.com.  Here I installed the openid_connect and openid_connect_sso modules.
I installed 9 more sub-sites (client2 - client9) under Client 1, using drush.
I used Drush to enable the openid_connect and openid_connect_sso for all sub-sites.
I added all 11 of the sites to my Apache config (I am using MAMP Pro on Mac) and tested them.
I had some config to do on on the auth site relating to each client site and to each sub-site for the SSO.

I am using https://drupalcommerce.org/blog/32567/using-openid-connect-single-sign-drupal as my general guide for setup and configuration of the modules as well as https://www.youtube.com/watch?v=3K-2IfC8lpg but the multi-site part I figured out myself.


How can I get a custom number of posts on the front page without views? I need to have 16 nodes on the front page. Drupal only allows 1-10, 15, 20, etc. I'm using views now but it breaks the AJAX of the rate module.

The default front page article count is on the Site Information admin page @ admin/config/system/site-information. For some reason you can't select 16 as a value. If you have drush you can manually set the default_nodes_main value:

drush vset default_nodes_main 16

If you don't have drush you can set its value in the variables table.


Dynamically add images to article body I want to add images to my article body field dynamically. Just like displaying advertisements in between the content.

Please help.

To accomplish this you need to edit the body field before rendering. There are 2 ways of doing this.

1) Using the node template file
In case of an article the template file would be node--article.tpl.php. Here is some sample code to edit the body field and include an ad after 4 paragraphs. The node--article.tpl.php file can be edited to make the following change.Here is the quick reference to theme pages in drupal.

 <?php
       $array = explode("<p>", render($content['body']));
       $array_size = sizeof($array);
       if($array_size < 5 ){
         $array[array_size-1] = $array[array_size-1]. $ad;
       }else{
         $array[4] = $array[4]. $ad;
       }
       $content['body'] = implode("", $array);
       print render($content['body']);
    ?>

instead of rendering the body using <?php print render($content['body']); ?>

2) Using the hook_node_view.

This node gets invoked before the node gets rendered. You can include your logic to edit the body field based on your requirement in this hook. I am assuming you have some idea of implementing hooks in your custom module. Refer to this link for more details of this hook.


What happened to the edit links in the Page Manager UI? I uploaded a site to a shared hosting environment and suddenly I can't use the edit links in the Page Manager UI any more.  As you can see in the screenshot, they've simply disappeared.  I can click the triangle and get a disable link but no edit.

I cleared the cache multiple times to no effect.  I then made a database dump of the server mysql and imported it into a local copy and experienced the same problem, even after clearing the cache multiple times.  I then turned off all of the aggregation options on the Performance configuration page and cleared the cache again, but no change.

Is this a typical problem or something I have uniquely done to screw things up?

EDIT: Upon further inspection, I noticed something else weird.  I am able to access the pages by typing in the URL manually, but when I go to edit a piece of custom content, the Edit option, which is usually just under Disable this pane, is missing:

Found the problem-- I had been lazy and replaced the "Edit" translation string with a space to remove it from some of the pages on the site, forgetting that it would remove "Edit" from all pages on the site.  Restoring the string fixed the problem.


Relation between User field and current user I have created a view for particular user role (i.e: Agent) that manage some user (for example, users with id: 1, 2, 3).

I've created a custom field for this user for associate this agent with some users.

It's possible create view who allow of this agent view, edit, ecc only content created by users who managed by him?

You'd need to add a relationship in views to your custom field you created and then provide a default value of "User ID from logged in user"


Domain Access Database prefix I am on D7.x

I have not quite figured out how to solve the table prefix problem that was solved with domain access table prefix in the 6.x branch.

I know that I will need separate caching tables for instance, but I'm not quite sure how to allow the table prefixing when everything is based off the same settings.php file.

Thanks for your help.

I figured this out by making decisions in the settings.php file.  I have a switch statement that gets the url and then sets a table prefix variable and then that determines the db name, the db password and the prefix.  The default is to share everything if something is not found.


Theme Drupal Form API checkboxes as a grid I have a custom form that displays a form element of about 2 dozen checkboxes. I would like to output them 3 per row, in a table if possible. How can I go about doing that?

$form['preference'] = array(
    '#type' => 'checkboxes',
      '#default_value' => 1373,
    '#required' => TRUE,
    '#title' => 'Choose all that apply',
    '#options' => $preference_options,
    '#prefix' => '
',
    '#suffix' => '
',
  );

First, define a custom theme function with hook_theme() and assign it to the form element with #theme.

In that theme function, you can use expand_checkboxes to convert it into an array of separate checkbox elements. Then, re-structure it into an array with 3 elements each, render the checkboxes and pass it to theme_table().

Something like this, all untested.

function theme_yourmodule_preference($element) {
  $elements = element_children(expand_checkboxes($element));

  $rows = array();
  for ($i = 0; $i < count($elements); $i += 3) {
    $row = array(drupal_render($elements[$i]));
    // The following two might not always exist, check first.
    if (isset($elements[$i + 1]) {
      $row[] = drupal_render($elements[$i + 1]);
    }
    if (isset($elements[$i + 2]) {
      $row[] = drupal_render($elements[$i + 2]);
    }
    $rows[] = $row;
  }
  return theme('table', array(), $rows);
}


Can I enable both the Internal dynamic page cache and page cache modules? Is it suggested that enabling both the caching modules in drupal 8, will not cause any issue?

According to Wim Leers, who is one of the main architects of the caching system in D8.

PUBLISHED on OCTOBER 12, 2015
Drupal 8 now has a Dynamic Page Cache. The Page Cache module only
works for anonymous users, the Dynamic Page Cache module takes that a
step further: it works for any user.
Since April 8, Drupal 8 had its Page Cache enabled by default. Exactly
5 months later, on September 8, the Dynamic Page Cache module was
added to Drupal 8, and also enabled by default.
source: Drupal 8's Dynamic Page Cache

Therefore, both of those caching modules come enabled by default out of the box, you don't have to do anything to enable them.

will not cause any issue?

No issues at all, Drupal 8 was designed to use both.

The Page Cache module caches fully rendered HTML responses — it
assumes only one variant of each response exists, which is only true
for anonymous users. The innovation in 8 on top of 7’s Page Cache is
the addition of cache tags, which allow one to use the Page Cache but
still have instantaneous updates: no more stale content.
The Dynamic Page Cache module caches mostly rendered HTML responses —
because it does not assume only a single variant exists: thanks to
cache contexts, it knows the different variants that exist of each
part of the page, and thus also of the final (fully assembled) page.
During the rendering process, auto-placeholdering ensures that the
parts of the page that are too dynamic to cache or are simply
uncacheable are replaced with placeholders. These placeholders are
only rendered at the very last moment. The Dynamic Page Cache module
caches the page just before those placeholders are replaced.
source: Drupal 8's Dynamic Page Cache


Save button missing on User Account Edit form I have months old problem of missing "Save" button on the user account edit form. Which is annoying to the point that now I have to find the solution.

I don't usually use account edit form since there is only one user. I have updated many modules and different cores but problem always remained there. Right now I am running latest core which is 7.23. And all modules are updated. This is a multilingual website.

Since this problem has appeared I am unable to save any change in any user account. Please have a look on the image attached.
Please help.

Thanks.

Try disabling i18n synchronization module.

There is another question similar to yours. Save button missing from content type edit form
Problem: save button missing from content type edit form. Reason: bug in i18n synchronization module. Solution: none here, but...

There is another case where i18n synchronization causes an infinite loop and there is patch along the lines of

if (function_exists(i18n_sync)) i18n_sync(FALSE);

This is the link, the patch is at #3. https://drupal.org/node/1372500
Maybe that will help you to the right direction.


Show only comment textarea, if entered something show required fields for anonymous user I want to make commenting easy for anonymous users. "Anonymous posters must leave their contact information." is enabled.

What I want to do is to show only the comment text field at first and if the user enter some text (more than 20 characters etc) then show the other fields (name, e-mail, homepage).

I think it will be better not to show 3-4 empty fields instead of one text area to comment. First, focus on the comment (content) and then the required fields.

Is there any out of the box solution for this or if anybody did that before?

Paste in file template.php

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'comment_node_blog_form') {
    $form['author']['name']['#attributes']['class'][] = 'validate[required]';
    $form['author']['mail']['#attributes']['class'][] = 'validate[required,custom[email]]';
    $form['comment_body']['und'][0]['#attributes']['class'][] = 'validate[required,minSize[20]]';
    $form['#attached']['js'][] = drupal_get_path('theme', 'MYTHEME') . '/js/jquery.validationEngine-en.js';
    $form['#attached']['js'][] = drupal_get_path('theme', 'MYTHEME') . '/js/jquery.validationEngine.js';
    $form['#attached']['js'][] = drupal_get_path('theme', 'MYTHEME') . '/js/scripts.js';
  }
}

change form_id with your form comment

Source jQuery validate and file scripts.js

(function ($) {
    $(document).ready(function(){
        $("#comment-form").validationEngine();
        $('#comment-form').find('.form-type-textfield').hide();
        $('#edit-comment-body').keyup(function() {
            var value = $(this).find('.text-full').val(),
                lenght = value.length;
            if (lenght > 20) {
                $('#comment-form').find('.form-type-textfield').show();
            }
            else {
                $('#comment-form').find('.form-type-textfield').hide();
            }
        });
    });
})(jQuery);

Form with empty text

Form with more 20 characters


views_query_alter apply "%LIKE%" condition Is there a way in which I can alter the view query so I can get items that contain a specified string in title?

For example something like this:

if (isset($_GET['query']) && (!empty($_GET['query']))) {
    $view->query->add_where('title', $_GET['query'], 'LIKE');
}

You can do it using code similar to the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', $_GET['query'], 'LIKE');
  }
}

The first argument that is required from $query->add_where() is the group for the WHERE to add. The documentation says to pass 0 as argument, to use the default one.

The code I shown works if $_GET['query'] contains an SQL regular expression. If $_GET['query'] contains a string that is not a regular expression, and that is used to build the regular expression for example as '%' . $_GET['query'] . '%', the code to use should be the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', '%' . db_like($_GET['query']) . '%', 'LIKE');
  }
}

Notice what reported in the documentation for views_plugin_query_default::add_where():

  The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.

References

hook_views_query_alter()
The list of functions/methods invoking hook_views_query_alter()
db_like()


Highlight autocomplete suggestions Drupal 7 I have a text field in a form, with autocomplete on. It works very well, but I cannot manage to find a way to highlight the letters in the suggested works. I found this hack in the autocomplete library (general, no Drupal related), but don't know if it applies or how to apply it. I would like the same effect:

http://output.jsbin.com/ezifi/4

Try Autocomplete Deluxe Module. May b this help you


Where can I save a CSV file that I construct dynamically to make it available for download? I dynamically construct a CSV file following that method:

$fp = fopen('export.csv', 'w');
foreach ($export as $fields) {
  fputcsv($fp, $fields);
}
fclose($fp);

A file 'export.csv' appears in the very root of my Drupal directory.

I display a link to a page, allowing user to download that CSV file:

drupal_set_message(l('Export to CSV', 'export-csv'));

In the page callback function, I make the file downloadable like this:

function grap_contact_export_csv_page() {
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"grape-export.csv\";" );
  header("Content-Transfer-Encoding: binary");
  $fp = fopen('export.csv', 'r') or die('Cannot access the file');
  echo fread($fp, filesize('export.csv'));
  fclose($fp);
  drupal_exit();
}

That works well.

What disturbs me is the location of the file. Of course, I know that I should not save it there. My question is: Where is the optimal location to save that kind of files? In the custom module's directory? In sites/default/files? What is the best practice?

The best practice is to use Drupal functions, not direct PHP functions, if there is Drupal API available. Particularly, here you may be interested in file_save_data and file_unmanaged_save_data.

If you want file available for short time, unmanaged file may be the way to go. But if you want periodic exports, archiving of prepared files, automatic clean-up etc, Managed is the way to go. If in doubt, try managed.

Examples for Developers offers a pretty good file_example.module, read it, play with it, and come back with more specific question.


How to get nid from URL alias in drupal 7? I have a URL alias sitepath/john/video/nature-beauty where john = user, video = content type and nature-beauty = node. I am trying to get nid of node nature-beauty. Node title is "Nature beauty" actually. I have set node title in URL alias.

Can anyone tell me where am I wrong in below code?

   $last_page_visited = $_SERVER['HTTP_REFERER'];
   $alias =$last_page_visited;
   $path = drupal_lookup_path("source", $alias);
   $node = menu_get_object("node", 1, $path);
   $nid=$node->nid;
   print $nid;

The $_SERVER['HTTP_REFERER'] will return the full URL, but the function drupal_lookup_path() takes only the alias as argument, so parse you URL and pass only the alias, john/video/nature-beauty then it will work.

$url = $_SERVER['HTTP_REFERER'];
$path = preg_replace('/\//','',parse_url($url,PHP_URL_PATH),1);
$org_path = drupal_lookup_path("source", $path);
$node = menu_get_object("node", 1, $org_path);
$nid=$node->nid;
print $nid;


Import currency type with Feeds import Is there a way to import a currency type when doing a Feeds import?  I have tried using the Feeds Tamper add on and am currently looking at this solution.  It seems that I am trying to reinvent the wheel :)  I have created a cck field that was called "price" as a text field and it worked beautifully.  I created this as a currency field and the new "price" currency field doesn't show up as an option to map to on the mapper UI.  I exported the Feed Import and added the field manually and then imported it back in.  When I run the import it doesn't bring over the value that is mapped.

I believe I found a fairly hacky answer for now. In feeds/mappers/content.inc I modified the function content_feeds_set_target after I added the money type to the array of included field types in line 18

function content_feeds_set_target($node, $target, $value) {

  $field = isset($node->$target) ? $node->$target : array();

  // Handle multiple value fields.
  if (is_array($value)) {
    $i = 0;
    foreach ($value as $v) {
      if (!is_array($v) && !is_object($v)) {
        $field[$i]['value'] = $v;
      }
      $i++;
    }
  }
  else {
    $field[0]['value'] = $value;
    //added these two lines to take care of the Money field
    $field[0]['amount'] = $value;
    $field[0]['currency'] = 'USD';
  }

  $node->$target = $field;
}

I know that this isn't the way to develop in Drupal and most likely I need to set up another content type or something along that line but this helped me (who am a complete noob to Drupal) to get started importing the price field.


How to programmatically create new revision and publish it? (I am using Revisioning.) I call node_load(nid, vid) (with the latest version id), give new values to some fields, and then save the node. Setting $node->is_current = TRUE before saving will ensure that this version of the node is now published. However, it does not create a new revision. So I try setting $node->revision = TRUE also, but this creates a new unpublished revision which is not what I would expect.

How can I edit a node, and save it as a new revision and also as the current published revision? Not sure if it is a bug in the module.

// Node has some new revisions since the version that is currently published.
$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
node_save($node);
// New revision created, but not published.

I think it will work when you explicitly set revision_moderation to FALSE. If moderation is not required, it should be published right away.

$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
$node->revision_moderation = FALSE;
node_save($node);

From the example here: http://drupalprogrammatically.com/anwsers/7/create-node

Poster of above url also sets $node->revision = FALSE;, but that would give me the impression no new revision is saved, which is not what you want.
I hope it helps.


How to show message view containing own and following activity? I have created a message view using the Message module. I want this view to show the current user activity and activity of the user he is following using the "follow" flag (user). i.e own + following.

The Message module comes with a "message subscribe" flag, but I do not want to use that. What should be the setting of my view particularly the relationship and contextual filters?

About the Message module and user activity

Even though you're question doesn't really say so, I'm assuming that:

"activity" in this question is about message instances created by the Message module, targeted to the current user.
"activity of the user he is following" is about message instances target to the current user (also), though they are about events related to any of the followed users (indicated by your follow-flag).

If these assumptions are correct, then your question is about creating a view of various flavors of messages (typically created using various Message Types), which are all targeted to the current user.

Creating a view about Messages by user

Add a new view

View name "Messages by user".
Show Message.
Type All.
Create a page (not a block)

Create a table display of this view

For this question here, you only need a single table display, of All messages.

To differentiate this "All", think of additional displays you might want to add later on, such as:

Read messages
Unread messages

Add Contextual Filters

Message: User uid, and for "When the filter value is NOT in the URL" use "Provide default value" with Type "User ID from logged in user".

Add Relationships

"Message: User uid" will result in the messages targeted to the current user, so that one you need for sure.

I suggest you create a first display only using the above relationship (to check the results you get so far). Then clone this display into another one, in which you add another relationship like "Flags: follow (by current user)" (assuming that follow corresponds to your follow-flag). By swapping between the 2 displays, you can decide which one you really want, or just keep both.

Add Fields

Message: Message ID (Msg ID)
Message: Timestamp (Created on)
Message: Render message (Get text) (Text)
(User) User: Name (User), and use "Exclude from display" for this field, which is only needed to add a "Global: Text area" to the views headers which contains something like Messages for user [name].

Add Sort criteria

Message: Timestamp (desc)

Further Refinements

Filter criteria: none
Page settings:

Path: /user/%/messages
Menu tab: Messages

Make the Messages manage-able

If you complete the above steps, you'll have a view that shows all relevant messages ... and that's really it. It won't be obvious for a user to remember which messages have been read already, and which ones are new (= unread). Try it for yourself (to experience the pain ..).

To implement a facility to mark messages as read/unread, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user' (= improved version of the view specifications described above).
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

Fruit of your labor

If you follow the above steps, the result of it is something similar to an eMail client inbox, whereas the eMail "messages" are not real eMails, but instances of messages created by the Message module.


Contextual filter in URL via Twig Does somebody of you know how to build a link as described in #9 in https://www.drupal.org/project/views_contextual_filter_query/issues/2686467#comment-10983075

I tried it this way

[title]

but the output ends with a "?" ... like me :-) The link to the node works, but the query/argument/contextual filter is missing in the url. How can I fix this?

Drupal offers a helper function for building URLs in Twig templates.

{{ url('entity.node.canonical', {node: nid}, {query: {foo: 'bar'}}) }}


How to uninstall a text format created by a D8 module? My module creates its own text format upon installation by having a file named config/install/filter.format.{format}.yml.

However, I can't uninstall and reinstall the module, because the format persists and will then cause a conflict. ("... already exists in active configuration.")

This looks like a bug in the filter API, but maybe there is some explicit way to delete the format when the module is removed? It's really annoying to have to manually delete the config key every time.

You need to add a dependency in your filter format to the module. Then when the module is uninstalled, the format should get deleted


Priority of execution of hooks in different modules Let's say that there is a contributed module installed in Drupal 7. It alters a SQL statement from the core. Now I have a custom module of my own which alters the same SQL statement in a different way. Now, depending on the alteration, I could have different SQL strings depending on which module hook applies before the other. For example, the first hook deletes a table "field" and the other adds the same table "field". If the first hooks executes earlier, the final SQL has the field added. If it is now the second hook which executes earlier, the extra field is added and later removed, so the SQL is completely different. How can I now the priority, any other conflicting issues and is there a way to override this apparent difficulty?

The system table has a 'weight' field. The hooks are executed in that order.

You can change during install with this code:

function your_module_name_install() {
  db_update('system')
    ->fields(array('weight' => your_preferred_weight))
    ->condition('name', '[your_module_name]', '=')
    ->execute();
}

Source: https://www.drupal.org/node/110238


views exposed "sort by" I have a view with an exposed "sort by" form.

I don't know how to skip this sort if the user did not chose any sort mode.

My view has this exposed sort widget and the second sort criteria (not exposed) is by node sticky property.
The problem is the view sorts the content by the first criteria, even though the user didn't chose something.

How can I change that?
Thanks

I just had this problem (well, similar) and I solved it the following way:

/**
 * Implements hook_views_pre_build().
 */
function MY_MODULE_views_pre_build(&$view) {
  // Trigger this only for the needed view
  if ($view->name == 'my_view_name') {
    // Check the exposed input array to see what the user submitted
    $exposed_input_arr = $view->get_exposed_input();
    // Write your exposed array checking logic here ...
    //if (empty($exposed_input_arr['field_sort_by']) || ...) {
      // Remove the sort field from the view
      unset($view->sort['field_sort_by']);
    //}
  }
}


Set a cookie whenever front page is viewed I run a Drupal 7 site (currently 7.15) since longer time and have the problem with cookies:

I need 2 cookies for non-Drupal PHP-scripts at my web site.

I set them in the hook_init of my custom module:

/**
 * Implements hook_user_login().
 */
function pref_user_login(&$edit, $account) {
    if ($account->uid <= 0) {
      return;
    }

    #drupal_set_message('
Hello, '.$account->name.'
');
    $auth  = md5(join('_', array($account->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
}

The problem is, that I need to set the both cookies each time a logged in user visits the front page and not just when the user logs in.

Does anybody please have an idea how to do it, maybe by JavaScript if I can't do it regular way?

You could do this in hook_preprocess_page() and instead of setting a variable, you could do something like this:

function pref_preprocess_page(&$vars) {
  global $user;

  // whatever other preprocess stuff you want to do here

  if ($user->uid && drupal_is_front_page()) {
    $auth  = md5(join('_', array($user->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
  }

}


Site seems to miss the "private" wrapper, how can I fix it? I can not enable the private folder getting the warning as below:

Warning: file_exists(): Unable to find the wrapper "private" -
did you forget to enable it when you configured PHP? in file_save_htaccess()
(line 365 of core/includes/file.inc).

It's Drupal 8.6.12, multisite config, other sites use private folders.

How can I fix it ?

Here are the necessary steps:

Create a directory on the server. This is typically done via SSH. For instance assuming Apache under Ubuntu, the following command can be used: sudo -u www-data mkdir -p /var/www/html/web/sites/default/files/private
Tell Drupal about your directory by editing your settings.php file. You need to have a line like the following:

 $settings['file_private_path'] = '/var/www/html/web/sites/default/files/private';

Important: clear the Drupal cache, for example with drush cr or by going to the page /admin/config/development/performance in your browser.
In the browser's address bar, go to /admin/config/media/file-system. You should see "Private local files" in the "Default download method" option. If not, then please visit the /admin/reports/status page to see any error messages.  Make sure that PHP can write in the directory. Often, for this to work, the directory has to be writable for the www-data user.

For more documentation, go to https://www.drupal.org/docs/8/core/modules/file/overview#private-file-system.


user relationship node access is not working I have enabled the module and tried to work on it. I have created the following users: mtest, emptest, and mdev.
I'm using the Views module to show the nodes. The nodes posted by emptest should only visible to mtest, but this is not happening, even after using the Node access and Content access module.

How do I restrict this?

If you are using a view, and trying to constrain the nodes listed in the view to those posted by the currently logged in user, you would use a Contextual filter to accomplish it, not Node access or Content access.

Assuming you are using Drupal 7, edit your view and under Advanced add a Contextual filter. Select Content: Author: Uid, and when the configuration screen comes up, under When the filter value is NOT available select Provide default value and use the select list to choose User ID from logged in user.

Save your view, and it will only list nodes authored by the current user.


Cannot bind delegate onClick event on .use-ajax elements I have a view, that is refreshed with ajax. I'm using Jquery 1.7.2

You click a button, that call a javascript function :

$(view_identifier).trigger('RefreshView');

Before this refresh, I've attached on click handler to an ajax link.
The link call a modal popup and must trigger a javascript function.
The link contains a picture, but I have tested with just text and I get the same result.
So I'm trying to attach an handler to an ajax link.

Here is the html :

 //lot of things ....

 //lot of things

And here is the javascript :

$('a.use-ajax > img').on('click',function(){
  console.log('test');
  foo();
});

That work fine, until the view is refreshed. After the refresh, the function foo isn't being called anymore. Thats because the handler is not being attached to dynamic elements.

So I change the part above to this :

$(document).on('click','img',function(){
  console.log('test');
  foo();
});

So that I can use the event delegation provide by Jquery.

And it isn't working.
When I click on the link, nothing is happening.
The strange part is when I remove the use-ajax on the link  (become a normal link without the Drupal ajax part), it works.

I've tested a lot of variation and nothing seems to work.

I've used an old jquery code :

$(document).click(function(event){
   //check if its a click on the link with event
   console.log('test');
})

and It doesn't trigger either. If I click anywhere on the page, the 'test' show up in console, but not when I click an ajax link. I don't understand this because, it would mean that the link isn't in the dom.

Does anyone have an idea ?

Thanks to Clive, I've found one way to make it work : wrap the code into a drupal behavior.

It look like this :

(function($) {
  Drupal.behaviors.refresh_views = {
    attach: function () {

        var view_identifier = '#view_id';

        //attach the on click handler to all links of class 'use-ajax'
        $('a.use-ajax').on('click',function(){
            $(view_identifier).trigger('RefreshView');
        });
    }
  };
})(jQuery);

I'm attaching an handler with my first version of the onclick function :

$('a.use-ajax').on('click',function(){
    foo();
});

So without the delegate part (does not work when an element is created after the script execution). In my case, I'm reloading the view with an ajax request. And in drupal 7, each time a request finishes the ajax behavior is called again. So the code is executed and it bind the on click event into the new elements.

I'm leaving a little warning here :
This script is executed on every ajax request (if you open a modal popup in the ajax way, it will add an event into the click handler). So it might bind a lot of time the same event ! So don't forget to control the amount of events that your are adding to the same handler.


How to select a shipping box for a particular product based on quantity using Drupal Commerce? I have two shipping rules for a particular product.

Case 1. (Shipping box)

Quantity: 1-12
Width: 6
Height: 6
Length: 8.75
Weight: 3

Case 2. (Shipping box)

Quantity: 13-24
Width: 8
Height: 6.5
Length: 11.25
Weight: 4

When a user purchases this particular product, if the quantity below 12, use Case 1 shipping dimensions. If greater than 12, use Case 2.

Anyone can point out how to achieve this? I'm using Drupal Commerce with Commerce FedEx as shipping service.

There's a tutorial on how to achieve something like this but it uses flat rate and not any shipping box dimensions.

Using the Commerce Box module, for which only a DEV version exists, you can create Commerce Box entities, but that's about it. E.g. it does not add any specific Rules Actions you can use to select the appropriate shipping box, such as based on product items and/or quantities.

However, there is an inspiring issue for the Commerce Fedex module, titled "Allow altering of default package dimensions". And comment nr 17 of that issue contains an interesting patch which allows for package dimensions alterations.


logged in users only for /user in user menu In my user menu I have a link for /user which produces a my account link which works as expected.  In the menu admin (logged in users only) appears next to it.

Now, when I translate the item to produce a link to /user I have found that 'logged in users only' does not appear next to it and that it is shown whether the user is logged in or not.

Is this a known bug?  Anyone know how i might solve it?

Thanks,

I suppose since /user is open to both authenticated and non authenticated users the other /user is somehow specially defined.

For others looking for a quick fix, I solved this with menu item visibility module.


Composer download Drush 9 - But conflict errors I just installed drush 7 and 8 in their own directory under /usr/bin as drush7, drush8 commands. Now I'm trying to do the same for drush9, but I'm getting a conflict error during the composer download of drush 9. How can I resolve this to only download the 9.x version?

The command I used was: composer require drush/drush:9.*

I got this idea of using all the drush versions from:

https://www.lullabot.com/articles/switching-drush-versions

When you request composer require drush/drush:9.*, you are telling Composer that you want the latest stable release of Drush on the 9.x branch.  However, Composer considers dev, alpha, beta and even RC releases to be unstable.  These releases can be downloaded in one of two two ways:

Create a composer.json file, manually add the release designation you want (e.g. 9.*), set the minimum stability to dev or alpha, or some other applicable value, and then run composer install (or composer update, if you already have a composer.lock file).
Explicitly request the version you want -- e.g. composer require drush/drush:9.0.0-alpha1, or ``composer require drush/drush:dev-master`.