Taxonomy jump list in view in parent/child order I have a taxonomy vocabulary of universities with their parent states. I then added this taxonomy field to the user profile so I could indicate what university the person was from. I'm trying to get this taxonomy vocabulary to display in an jump menu in a view (Drupal 7, Views 3) and honor the parent hierarchy, but the child/parent relationship is not being honored. This is how my jump list looks:

    California
    University of Georgia
    --Joe
    --Mary
    Georgia
    University of California
    --Mike
    --Jill

I'd like it to look like this:

    California
    --University of California
    ----Mike
    ----Jill
    Georgia
    --University of Georgia
    ----Joe
    ----Mary

I've read many possible solutions that suggest to add, "Taxonomy: Terms on node," but I don't even see that as an option. Any help would be greatly appreciated.

You need to add "Content: Taxonomy terms on node" as a relationship.


Content Type and Sub Pages? I have a drupal 6 instance and I want to make it so when I create a content type (for example movies) it would create 2 sub pages (reviews, and photos). So if I went to

www.site.com/movie-BLAHBLAH/ it would load the node content type info
and

www.site.com/movie-BLAHBLAH/reviews/ it would display a page where I could theme the page.tpl.php file to do what i want it to do. and same with the other one.

Is this possible somehow?

See the CCK Fieldgroup Tabs module for Drupal 6. It displays CCK fieldgroups in tabs. Enables splitting up content onto tabs in both editing and display.

Note: For Drupal 7, see the Field group module, which includes tabs support.


Mandatory Group / Autosubscribe in Drupal 7 I'm using organic groups for a community website which notifies members when a new article is submitted to their group.

However I would like ALL members to receive notifications when the admins publish articles to the site.

There are 2 ideas on how I think this could be done:

Autosubscribe all users to receive notifications when articles are posted (to no group) by the admins
Have a 'General' group that all members automatically join on signup

I have seen a module for Drupal 6 which address idea 2 but so far I have not found any solution on Drupal 7.

You can use rules to do this (As OG7 uses rules for everything else).

Create new Rule
Add New Action
React on event: After saving new content
Add condition
Data Selector node:author
Choose whatever role is admin
Add Action
Send email to all users of role
Select whatever roles
Fill in your message with applicable tokens

You can also check out the notifications and Messaging framework or the new Newsletter module for D7. These are better for allowing users to control which notifications they receive and can subscribe and unsubscribe themselves.


SQLSTATE[42000]: Syntax error or access violation (db_insert Function) I try to build new module in drupal 7
I try to insert some data in some where inside the code
it was working in many functions
but suddenly when I try to do the following

  db_insert('payment_request')
    ->fields(array(
      'payment_item' => $data['payment_item'],
      'change' => $data['change'],
      'via' => $data['via'],
      'userlist' => serialize($userlisthidden),
      'startdate' => strtotime($data['startdate']),
      'enddate' => strtotime($data['enddate']),
      'hash' => $hash
    ))->execute();

it gives me an error

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, via, userlist, startdate, enddate, hash) VALUES ('2', '1', '1', 'a:1:{i:' at line 1

I checked the table and the fields and the values
every thing are correct

so I decide to insert static data like the following :

  db_insert('payment_request')
    ->fields(array(
      'payment_item' => 'qq',
      'change' => 'qq',
      'via' => 'qq',
      'userlist' => 'qq',
      'startdate' => 'qq',
      'enddate' => 'qq',
      'hash' => 'qq'
    ))->execute();

But it gives me the same error
so, what i miss here, please help me

CHANGE is a reserved word in MySQL. PDO doesn't have a built-in function for quoting identifiers (just string literals and dates), so presumably Drupal simply hasn't tried to implement this on PDO's behalf.

Using a different column name would be the simplest solution.


How to add additional information to shipping methods? I have a list of shipping methods added via the UI admin/commerce/config/shipping-methods.

I need to have an accompanying description added to each shipping method.
First I thought that I could add an additional field under the settings for shipping types, but this didn't work (Added the field, but it never shows up when adding or editing a shipping method).

I'm fine if this is only doable programmatically, but I have found absolute zero information on how to do this on drupal 8.
I would actually prefer if I can do it programmatically, as I will be adding my own shipping method plugin in the future.

Question
How do I add an additional field to each shipping method?

I know this is an old thread, but I encountered the same problem. So in case you have the same issue:

This isn't really a commerce question, rather a general one.

There is a hook, where you can simple add new fields to an existing entity: HOOK_entity_base_field_info

So in this case:

/**
 * Implements hook_entity_base_field_info().
 */
function yourmodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'commerce_shipping_method') {
    $fields['shipment_description'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Description'))
      ->setDescription(t('The shipping method description.'))
      ->setRequired(FALSE)
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
    }
}

This will add a simple textarea field type, but you can add any field type you like.

This will only add the field visually, you must also do an update to your database table. In a .install file, do something like this:

/**
 * Implements hook_install().
 */
function hartmann_add_field_install() {
  $entity_manager = \Drupal::entityManager();

  $desc_definition = $entity_manager->getFieldStorageDefinitions('commerce_shipping_method')['shipment_description'];
  $entity_manager->onFieldStorageDefinitionCreate($desc_definition);
}

/**
 * Implements hook_uninstall().
 */
function hartmann_add_field_uninstall() {
  $entity_manager = \Drupal::entityManager();

  $desc_definition = $entity_manager->getLastInstalledFieldStorageDefinitions('commerce_shipping_method')['shipment_description'];
  $entity_manager->onFieldStorageDefinitionDelete($desc_definition);
}

Then reinstall your module.
In more recent versions of Drupal 8, entitymanager is deprecated. I don't now the updated code for .install, but some research and you will find it.


How to get image path in view? I have created a content type having two fields:

Title
Image (multiple image field)

Then I create a page view for the same. Added these two fields. Now I have to create an external theming in view so from view-Theme Information- Row Style output, I have created a view-tpl.php page in the templates folder.

I have given this design in this view:

So I want to fetch one by one image path to pass in src of images. I have tried this $fields['image']->content but it print images as an object. How can I get the paths of images to pass in src tag.

Here's a Drupal 7 example showing how to use:

field_get_items() to select the field from the node,

file_load() to load the image file,

image_load() to get the URI from the image file

image_style_url() to format the image differently for different
   contexts

... and as a bonus, check for good data and substitute a default image if the field image is no good.

// If there is a field image.
if (!empty($node->field_image)) {
  $field = field_get_items('node', $node, 'field_image');
  if (!empty($field[0]['fid'])) {
    $image_file = file_load($field[0]['fid']);
    $image      = image_load($image_file->uri);
  }
}
// If image, then scale it. If not use the default image.
if (!empty($image)) {
  if (is_string($image)) {
    $image_source = $image;
  }
  else {
    $image_source = $image->source;
  }
  $url        = image_style_url('image_style', $image_source);
  $url_mobile = image_style_url('image_style_mobile', $image_source);
}
else {
  $url        = 'https://example.com/sites/default/files/default_image.png';
  $url_mobile = 'https://example.com/sites/default/files/default_image_mobile.png';
}

Hope this helps. Good luck!

EDIT: @Kevin makes a very good point in the comments above:

  All of this complexity can be avoided by using entity view modes and not doing field based views.

Basically, Drupal gives you the ability to set up view modes in the "Manage Display" tab for each content type. There, you can decide which fields will be shown or hidden in each view mode, and how they should be formatted for display. If you use this feature, you shouldn't need to deal with it in PHP template files.


How to NOT share content between multi sites? Try as I might cannot stop all changes in one sub site copying to other. They have two separate databases and settings files and conf files but because of necessary symlink to share core code base , everything else is being shared right along with it.

How can I stop this sharing everything between subsites when drupal core is in first subsite and symlinked to second?

Why is it even happening when have two sep db set up and two sep settings.php?

I don't want changes to be made to subsite2 when I make changes to subsite1 and vice versa as is happening now.

mysite.com (static html) in /var/www/html

sub1.mysite.com  (drupal install) pointing to mysite.com/sub1

/var/www/html/sub1/sites/sub2

sub2.mysite.com (symlink to sub1 in html folder) pointing to mysite.com/sub2(symlink vs)

No necessity to add sites.php or even change httpd or conf file with symlink.

My theory is you must have drupal core files in html folder not a subdir linked to subdomain below it. I will test tomorrow.

No I think I need to just know what to put as base url in conf file? Do I direct it to html/mysub.site.com  or to html/sub1/sites/mysub.site.com ?

I run several multi-sites and nothing is being shared between them except core and the modules and themes below sites/all/.  If more than this is shared (your question specifies "everything"), then you've not set up your multi-site right.

I've written a tutorial about setting up a multi-site here. I hope the instructions are clear enough to follow.

Setting up a multi-site where the primary site is in a sub-directory is not different from setting up any other multi-site, provided your DocumentRoot points to the right place.

From your latest comment, I finally understand that you're trying to do the same thing as the person at http://drupal.org/node/1882182.

In that case, you need to understand that this person is not using the subdirectory method.  He is using the  subdomain method.  You can't mix these methods, you must use one or the other.

And if you're using the subdomain method, you must not use a symbolic link (as you indicate in your question that you're using). Instead, you must configure DNS and your vhost to point to the directory that is your DocumentRoot for Drupal (in your case, it sounds as this should be  /var/www/html/sub1/.  This will take care of the fact that your Drupal core is installed in a sub-directory with a plain HTML-site in the web-root.  You must also create the following sub-directory in the Drupal sites directory: sub2.mysite.com.  Copy the default.settings.php into sub2.mysite.com. Then make sub2.mysite.com your working directory and immediately copy default.settings.php to settings.php.  Make sure that both are writeable by the web server user.  The sub2.mysite.com subdirectory will hold your settings.phpfor sub2.mysite.com. Then go to your ISPs control panel and configure DNS for sub2.mysite.com to resolve to your main site's IP-adress. Finally create the following ServerAlias: ServerAlias sub2.mysite.com in your main site's vhost configuration file.

You should now be able to point your web-browser to http://sub2.mysite.com/ and be greeted with default Drupal installaton screen.  You can then proceed and install the multi-site instance you've created.  If you get anything else than the  default Drupal installaton screen at this point, something has gone wrong and you need to find out what this is.

(All this assumes you're using Apache2 as your web-server.  If you're using something else, you need to figure out the equivalent of DoccumentRoot and ServerAlias on your brand of web-server.)


How to enforce a one-to-one relationship I want to store data about students and the books they read. Each student can read only one book, and each book can be read by only one student.

I have created a Student content type, and a Book content type, and I have created a reference field in the Student content type to reference the Book content type, and I have made the reference field to only accept one value:

So this way when I am entering data for a student, I can only enter one book value for the student (so the constraint that a student can only read one book is enforced).

But I can still enter the same book for more than one student, for example I can enter book1 for student1 and and I can also enter book1 for student2. How can I prevent this (remember that I want each book to be read by only one student)? The way I can do that if I am creating a database is to make the book foreign key in the Student table unique, but I don't think there is a way to make a field unique in Drupal.

I think you will need to use an entity reference view to enforce your restriction. In the settings for your reference type you can select Default or Views: Filter by an entity reference view

You will need to create your View first, instead of adding a Page or Block you need to add Entity Reference but this isn't available as part of the Views Wizard.

Part of the filter criteria will be to hide books which have already been assigned to a student. Hope this helps you get to your solution


Use swipe to switch blocks for mobile screen In the mobile version of my site I would like to use swipe to cycle through different blocks.
E.g. a certain block (view) is displayed and swiping the screen would show the next one in the same region. Is it possible to achieve this? Thanks!

Work with a views - slideshow, like owl or slick, where you show these blocks using views_block_area.

Show this view by css-media-queries, in which you hide the normal content ..
like:

.my-view {display: block;}
.my-block {display: none;}
@media(min-width:34em){}
@media(min-width:48em){
  .my-view {display: none;}
  .my-block {display: block;}
}
@media(min-width:62em){}
@media(min-width:75em){}

more info on the web or here https://stackoverflow.com/questions/18424798/twitter-bootstrap-3-how-to-use-media-queries


Trying to create a node_type in DP 7 I'm trying to create a simple node_type in drupal 7 based on the core blog module.

This is my hook_install:

function node_link_install() {
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['node_link']);
}

and this is then the hook_info in my node_link.module file:

function node_link_node_info() {
  return array(
    'node_link' => array(
      'name' => t('Node Link'),
      'base' => 'node_link',
      'description' => t('Just playing around'),
    )
  );
}

and here is my hook_uninstall:

function node_link_uninstall() {
  $result = db_query("SELECT n.nid FROM {node} n WHERE n.type = :type", array(':type' => 'node_link'));

  $nids = array();

  foreach ($result as $item) {
    array_push($nids, $item->nid);
  }

  if (count($nids)) {
    node_delete_multiple($nids);
  }

  drupal_uninstall_schema('node_link');
}

when I try to install the above module I get:

Notice: Undefined index: node_link in node_link_install() (line 10 of

  drupal/sites/all/modules/custom/node_link/node_link.install).
      Notice: Trying to get property of non-object in node_add_body_field() (line 555 of
  drupal/modules/node/node.module).
      Notice: Trying to get property of non-object in node_add_body_field() (line 568 of
  drupal/modules/node/node.module).
      FieldException: Attempt to create an instance of field body without a bundle. in field_create_instance() (line 460 of
  drupal/modules/field/field.crud.inc).

Several things are puzzling me here:

1) why does this work for the blog module but not my module?

2) when I uninstall this module, the entry in the system table is not deleted

what am I missing?

The error is complaining that it can't save the body field because you haven't specified the bundle of the object. But more importantly I think you want to look into the Entity API rather than creating a 'node_type'.

In drupal there are nodes and there are types of nodes called content types. To make it more abstract, nodes are entities of type 'node'.  Each content type is a 'bundle' of that entity type. Many things in drupal are entities, from users to comments to taxonomies.

If all you want to do is create a content type programatically, I think examples might have one. Otherwise just create the content type through configuration.


Different node form id for add/edit I recently found that unlike Drupal 7, D8 has a different form id for addition and edit of nodes. Is there a specific reason for that? Because this makes the hook_form_FORM_ID_alter() less granular as we now have to alter like mymodule_form_node_form_alter() and put the specific node type in there.

Sorry, could not find a discussion on this. Must be something very basic that I missed.

Thanks

I'd rather say, added granularity is exactly what has been achieved by introducing entity form ID's specific to their entity type, bundle and operation.

You can now target the form for a specific entity type and bundle with a specific operation when using hook_form_FORM_ID_alter(). Before this you had to check the bundle yourself and also figure out whether the node already had an ID or not.

The form ID will be composed of entity type identifier, bundle, operation and the _form suffix. (Compare EntityForm::getFormID().)

If you require a more generic form alter for ALL node forms, you can use hook_form_BASE_FORM_ID_alter() which will be invoked with the base form ID that is ENTITYTYPE_form for entities, so node_form for content entities.

The invocation order along with a description of all three hooks is actually well documented in the description of hook_form_alter().


Views Grouping field:Add Ordered class to Grouping row I use Views and Grouping field to integrate my data.
But i need each grouping row ordered.

I want to override the views-view-grouping.tpl.php, and change the "view-grouping" class to "view-grouping-1","view-grouping-2","view-grouping-3"...

The original code is belowed:

    <?php

/**
 * @file
 * This template is used to print a single grouping in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $grouping: The grouping instruction.
 * - $grouping_level: Integer indicating the hierarchical level of the grouping.
 * - $rows: The rows contained in this grouping.
 * - $title: The title of this grouping.
 * - $content: The processed content output that will normally be used.
 */

?>

<?php print $title; ?>

    <?php print $content; ?>

The File is located at all/module/views/theme/

Does someone meet the same problem before?

Thx for help.

Javascript?

$('.view-grouping').each(function(i){
  $(this).addClass('view-grouping-' + (i+1));
});


Add attribute to main menu item In my project I would like to add the following attributes to my "Login" main menu item:

data-toggle="modal" data-target="#login-modal" (Am using the Bootstrap theme)

I checked out the menu attribute module but it does not allow for these attributes.

Please is there a way?

You can use this HOOK_menu_link_alter and add new attribute from there.

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu_link_alter/7

function MYMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/login') {
    $item['options']['attributes']['data-toggle'] = 'modal';
    $item['options']['attributes']['data-target'] = '#login-modal';
  }
}

Note : Make sure you clear cache and are checking this for anonymous user.


What's the difference between the components ending in .system and .module in the Bug tracking system? I am a phd student focus on automated testing of complex systems and I selected the Drupal system as a case study.
First, I need to examine the bugs recorded for a number of modules in Drupal. Thus, I looked in the issues of each module, e.g. File module https://drupal.org/project/issues/drupal?text=&status=All&priorities=All&categories=1&version=All&component=file.module . But, I noticed that there exist file.module and file.system components in the issues for Drupal. And, this happens with most of Drupal modules. Thus, my question is what is the difference between file.module and file.system in the issues. I need to recorded the bugs associated to each module, so I do not know if a need to consider the bugs of .system components or .module components or both.

Thanks in advance,
Best

You're reading things slightly wrong.

There's no file.system component, or any other component ending with .system.

There are systems:

ajax system
batch system
file system
etc...

These are for issues pertaining to parts of Drupal that are not located in a module. Anything in the /includes folder of a normal Drupal installation, basically. (ajax.inc, batch.inc, file.inc for the examples above)

Then there are modules:

blog.module
file.module
menu.module
etc...

These are for module-specific issues.


How to add custom theme for Add a Product page I'm new to Drupal Commerce.

I have created new product type and added custom fields everything and it's working fine.

I want to theme the Add a Product (form page). Please suggest me how to do that.

Thanks,
Selva

It depends what part of the page you want to theme, simple CSS, change the layout, or adjust the form.

To add CSS, you could attach your CSS file in hook_page_build for that path.

To change the page template, you could override the page.tpl.php file as page--node--add--product.tpl.php

You could also set a custom template in hook_preprocess_page by checking for the relevant path and setting theme_hook_suggestions to your template (e.g node/add/product and node/[nid]/edit)

Another option is using hook_custom_theme to specify a whole new theme for that specific path.

Lastly, you can theme the form itself using hook_form_alter and using either a template for the form, or adjusting the form elements there.


Querying taxonomy terms with the level hierarchy I am currently struggling against a problem I can't fix, probably because of my scarce knowledge of the Drupal API.

I  have a taxonomy tree that looks like the following one:

    SHOE BRANDS 143
         KIDS   151
         MEN    152
            STIVALE/BOOT    164
            SANDAL  165
            PANTOFOLA/LOAFER    198
            MOCASSIN    199
            DERBY   200
            FRANCESINA/OXFORD   201
            POLACCHINO/ANKLE BOOT   202
            SNEAKER 203
        OUTDOOR/SPORT   153
        WOMEN   154
            STIVALE/BOOT    166
            SANDAL  167
            POLACCHINO/ANKLE BOOT   189
            SNEAKER 190
            DERBY   191
            FRANCESINA/OXFORD   192
            PANTOFOLA/LOAFER    193
            SABOT   194
            MOCASSIN    195
            BALLERINA   196
            DECOLLETEE/PUMP 197

What I need to do is to populate a select box with the child elements of the "SHOE BRANDS" parent (which should be "KIDS" "MEN" "OUTDOOR" and "WOMEN"). After that I will populate a second select box with an Ajax call passing the tid, to get all the different shoe types.

The query I'm using to populate the first select is this one (and the problem rises here):

SELECT *
FROM node
INNER JOIN term_node AS tn
ON node.vid = tn.vid
LEFT JOIN content_type_extra_content AS xc
ON node.vid = xc.vid
WHERE tn.tid IN (SELECT th.tid FROM term_hierarchy AS th WHERE th.parent = '143')
GROUP BY tn.tid

Note the '143' which is the tid of the "SHOE BRANDS" term.

Don't know why, but I only get as output "KIDS" and "OUTDOOR" (which are the only terms with no child elements.

Am I missing something in my syntax?

have you reviewed taxonomy_get_tree() documentation? http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_get_tree/6 I guess that taxonomy_get_tree() documentation and code function could be a guidance.

  taxonomy_get_tree
  ...

  Return value

  An array of all term objects in the tree. Each term object is extended
  to have "depth" and "parents" attributes in addition to its normal
  ones.


Apache solr search words, but the search pages yield no results I have Drupal 7 set up with Search API and Apache Solr.  It was working for a while but after a lot of configuration has been done, modules installed, etc.  The search no longer yields results.  I added solr auto complete to my search block that uses the solr search, and when I start typing in "pizza" it shows that there are indeed two results that come from that search, but when I click Submit, the search page says there are no results.

Does anyone have any idea why this is not working?

EDIT: I also have facet search enabled.  To troubleshoot I disabled the facet api entirely and I'm getting the same issue.

EDIT2: Let me know what other information is needed to diagnose the issue.

The issue was that I had added the line as suggested here:
http://www.druplitec.de/partial-substring-search-using-solr-server-and-searchapi-module

I took out the line and now it works.  I guess I have to find another way to get "fuzzy search" for the solr server to work...

I had added the line to the wrong place.  I re-read through the apache solr docs and found the correct places for it to go.


Remove an uploaded file I am working with files in a Drupal module. I added this form:

$form['Background_image'] = [
  '#type'               => 'managed_file',
  '#title'              => t('Image'),
  '#progress_message'   => t('Please wait...'),
  '#progress_indicator' => 'bar',
  '#description'        => t('Click "Browse..." to select an image to upload.'),
  '#required'           => TRUE,
  '#upload_validators'  => ['file_validate_extensions' => ['jpeg jpg png gif']],
  '#upload_location'    => 'public://backgroundimage/',
  '#default_value'      => $this->options['Background_image'],
];

The file is added properly. Once the file is uploaded a remove button appears allowing to remove the file and upload a new one. The problem is that this button is not working. How can I remove an uploaded file?

Once you have uploaded a file you must be having file object so use file_delete(stdClass $file, $force = FALSE) to delete the file.


what is the difference between commerce order table and commerce line item table? which table should i consider for created date for an order in commerce_order table and commerce_line_item table.

I can see created dates in both the tables.

The commerce_order table stores data about an order. The commerce_line_item table stores line items (e.g. products, fees, misc charges) in that order.

If you need to track when the order was created, reference commerce_order.created. If you need to track when the line item was originally added to an order, reference commerce_line_item.created.


How do I make view section scrollable? I created a most read section with 4 articles in views.

The height is over. How do I make this section scrollable?

Is there any scrollbar settings in views?

#(block-id-here){
  height:200px;
  overflow-y:scroll;
}

Thanks, Smalution.

I had found out the solution for this.


Send Email to user after click submit button Currently I am doing a recruitment system using Drupal 7 where the applicant can apply the job and HR admin can shortlist the applicant.

I have created a "shortlist button" in the content type to let the HR admin change the applicant status from pending (by default) to shortlisted. I put some rules to change the user status.

So my question is: How can I send the email to notify the user after the HR admin clicks the "shortlist button" to inform the user that they has been shortlisted?

You are looking for Workbench email module.

  Provides a way for administrators to define email transitions and
  configurable email subject / messages between those transitions. Email
  transitions can be defined as when content moves from state to state.
  Based on those email transitions, configurable emails can be created /
  updated / deleted as the site admin see's fit.


Pass arguments using hook_menu I would build a confirmation screen. So I initialized the path in the hook_menu as it should be but for some reason, the argument $node isn't send with the function... What am I doing wrong?

This is my hook_menu:

$items['node/%/revisions/%/offline'] = array(
      'title' => 'Offline,
      'description' => 'Confirm the action "Fiche offline".',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('_mymodule_confirm_offline'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -4,
    );
    return $items;

And this is my function:

function _redactie_omgeving_confirm_offline($form, $form_state, $node) {
    $question = t('Take fiche offline. ');

    return confirm_form($form,
                    $question,
                    'node/7', t('You\'re about to depublish this fiche. <br />Are you sure you want to depublish this fiche?'),
                    t('Yes'), t('Cancel'));
}

But the $node-variable in my function stays empty... What do I have to do to fill in this variable?

Your page callback is drupal_get_form, and your page argument is _mymodule_confirm_offline, so the call Drupal makes is drupal_get_form('_mymodule_confirm_offline');, which doesn't at all seem to be what you want to do.

What you need is a custom callback instead.

In hook_menu:

'page callback' => '_confirmation_form_page',
'page arguments' => array(1, 3),

And then

function _confirmation_form_page($node) {
  $question = t('Take fiche offline. ');

  return confirm_form($form, $question, 'node/' . $node->nid, t('You\'re about to depublish this fiche. <br />Are you sure you want to depublish this fiche?'), t('Yes'), t('Cancel'));
}

In order to "auto-load" an object from the url, it needs to be named, otherwise Drupal can't know how to perform the load. On a url like "node/%nid", the argument is named "nid". In reality the argument would usually be called %node, but I wanted to distinguish the parts. Drupal will then look for a function called load_nid, pass the number from the URL in, and this function is responsible for returning the fully loaded object. Core has a "load_node" function, so arguments named %node will be auto-loaded without further effort from your part.

To add autoloading into your callback then, you need

$items['node/%node/revisions/%/offline'] = array(

However, this will still only give you the right node, not the right revision. node_load() supports a second argument, $vid, that we need to use to get the right revision. Telling Drupal to pass on extra arguments is used with the load arguments key, and we need to use the fourth argument from the url node/%node/revision/%/offline for this.

So in conclusion, the hook_menu implementation becomes:

$items['node/%node/revisions/%/offline'] = array(
  'title' => 'Offline',
  'description' => 'Confirm the action "Fiche offline".',
  'page callback' => '_confirmation_form_page',
  'page arguments' => array(1),
  'load arguments' => array(3),
);
return $items;


Passing Node ID/Title to Next Page Webform Field I am new to drupal 8 and assisting my development team with design part. We are stuck in one place and not manage to move forward. We want to pass the node ID info to a webform filed which exist in another page. In the attached image I have explained what we want to achieve in Drupal 8 Environment, previously with PHP hack it was possible in drupal 7 but no idea how to achieve the same in drupal 8.

Assuming you want: The user will create a node. Upon submission a form will be displayed showing the node id pre-filled in a form.
Make a module called example:

// example.module:
// we created a node type "product" (using UI). Saving this content
// will trigger the product form
/**
 * Implements hook_ENTITY_TYPE_insert().
 * @param \Drupal\node\NodeInterface
 */
function example_node_insert(NodeInterface $node) {
  if ($node->bundle() == 'product') {
    $nid = $node->id();
    $response = new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal\Core\Url::
    fromRoute('product.form', ['nid' => $nid])->toString());
    $response->send(); // When OO we will return the response object instead
  }
}

// example.routing.yml
product.form:
  path: '/form/product/{nid}'
  defaults:
    _form: '\Drupal\example\Form\ProductForm'
    _title: 'Product Form'
  requirements:
    _permission: 'access content'

// src/Form/ProductForm
<?php

namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

class ProductForm extends FormBase {

  /**
   * @var NodeInterface
   */
  protected $node;

  public function getFormId() {
    return 'example_product_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $nid = null) {
    // if you need to load the node
    // $this->node = NodeInterface::load($nid);

    $form['node_id'] = [
      '#type' => 'textfield',
      '#title' => 'Node ID',
      '#value' => $nid,
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // TODO: Implement submitForm() method.
    // you can redirect back to the node
  }

}

When dealing with this issue please realize the node id is not available until you save the node.


How should a custom module install a reference data dictionary? I'm about to write a custom module dealing with chemical hazards symbols. It's basically a 300-item dictionary of simple objects: a symbol, its description (around 100 chars) and in some cases a supplementary short information.

I'm still undecided whether I'd make my module a text filter, field or entity, but regardless (I think) of the way I choose, I'm clueless about what would be the Drupal way to install this simple dictionary, a PHP variable, a persistent variable, or a database table?

My guess would be that storing it as PHP variable would not burden the memory too much, it would provide quick lookup access, and would save database queries. Would there be any benefit to choose the table option?

What is limiting me in using taxonomy here is that some terms would have to be supplemented by a piece of information on a binding/instance level. For example, there would be a symbol (term)  P0123: Store in temperatures below %1 C/ %2 F or P2345: Wash %1 thoroughly after handling. For each node referencing that term there should be a possibility to add the precise values that might be different per node. That is the reason I have been thinking of making it a text filter that would parse line:

P0123,10,50 (<- term with supplementary contextual values, %1 and %2)
P2345,en:hands|de:Hande|es:manos (<- i18n-savvy contextual string)
P3456 (<- term without additional info)

I have already filed a feature request for the Relation module, to provide labelling of relationships on instance level. We'll see if the authors consider it as worth implementing for a wider public. For now I'm trying to find a swift workaround.

In D7 I would make a Taxonomy out of such data. Just create a new taxonomy called Chemical Dictionary. Taxonomies already have:

a title
a description field

You just need to add a custom field for the image(s) using the Field UI. You could easily import these things from CSV or a remote database table using the Migrate module if your comfortable with code.

Taxonomy terms are stored in a database table by default in drupal, they are already entities.

While typically used for tagging things, you dont have to use it that way.


Adding new website as multiwebsite under existing drupal website I have an existing Drupal website. I want to add a new website as a sub website under the existing website. I want both websites to share single database / modules.

I googled about it but didn't get use full information about.

Can anyone please explain how to add a new website as a child website of existing Drupal website?

Thanks

Domain modules will be your best bet. It will allow you to use same codebase and database for all your sites. You will also have an option to push content to a specific site if need be.

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites


How to change pager class to view I have HTML desing of pagger ,How to I assign my own class to pager in side view ?I dont have any idea about it so will you plese tell how can I ?

I believe there are two ways you can do it:-

In template.php , you can use theme_pager. Then overrite it.
You can make a views template and overrite it. For this just goto advance option in views and search for template suggestion.


Variable storing payment method in ubercart order Seems easy but I am not able to figure it. I am using ubercart module in drupal 7, I am few payment methods like paypal, innovate and free method. All the 3 payment methods are activated, When a user places any order he has to choose which payment method he want to go for, if he is going for free method,

I need to know which variable is storing this payment method value,it should be like $order->method or $order->type same like other variables like $order->order_id,$order->billing_first_name.

In short I should come to know which payment method is chosen for a particular order.

If any buddy knows please help me.

The variable you're looking for is is $order->payment_method.


user-profile-edit.tpl.php not working for user#1 I am going crazy on this one :-/

I have overridden my user edit page with a user-profile-edit.tpl.php

In my template I have:

function mytheme_theme() {
  $items = array();
  $items['user_profile_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/template',
    'template' => 'user-profile-edit',
    'preprocess functions' => array(
      'mytheme_preprocess_user_profile_form'
    ),
  );
  return $items;
}

My problem is that my user-profile-edit.tpl.php is not being picked up by user#1,
it is working however for all other authenticated users.

Is there some setting i am overlooking here?

It seems that your themes are different for your users because the template name is fine.
It will work fine with the theme in which you have added the template.


Is there an easy way to call a migration from a controller for debugging purposes I am trying to debug a migration and having issues getting xdebug to work with drush as I described in this issue.  Would there be an easy way for me to call a migration from a controller (I am able to text xdebug from browser)?

For example, I would like to debug this:

drush mi upgrade_d6_field_instance

I was thinking to create a custom module that adds a controller that I can call the migration from the browser. The only option I cant think of is to recreate a lot of the functions from migrate_tools in the controller but I feel like there has to be an easier way.

Actually, the code isn't that hard to recreate from migration_tools. Here is my controller class:

<?php

namespace Drupal\custom_migration\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

class MigrateController extends ControllerBase {

  public function process() {

    $migration = \Drupal::service('plugin.manager.config_entity_migration')->createInstance('upgrade_d6_field_instance');
    $executable = new MigrateExecutable($migration, new MigrateMessage());
    $executable->import();

    return ['#markup' => 'Migrate Debugging'];
  }
}


Rotate views results based on number of times viewed I have 10 images that I want to rotate within a views consisting of 6 viewable slots (my Views results). I want to rotate the 10 images so that each recieves (approx.) an equal number of views. The Node Statistics option added as a Sort Criteria does not work for this because you have to actually open and view the node itself for the counter to increment. What I want is for the counter to increment each time the images are shown from within the view.

IMHO I don't think that you will be able to find a module that does this. You will need to write custom code for that. Depending on how comfortable you are hacking with Drupal and PHP you might find it trivial or very difficult.

So here are the requirements:

The counter must persist between page renders, so you need to store it in the database. A CCK field (D6) or "just" field (D7) will do the trick. You would assign this new field to your image content type.
This is a View. So how could you write to CCK field when rendering a View? The answer to that is preprocessors. How to write preprocessors is beyond the scope of your question. So is how to write to a CCK field. You can look for that answer in other Stack Exchange questions and the main Drupal site.
On your View, you would then sort the images by this "counter field".

That should do it.


How to seperate products images folders based on product display categories? I am building a drupal 7 commerce site, I have installed  inline entity form module and adding products from inside the products displays.
Since I will have thousands of product displays and products, I thought of finding a way to automatically separate pictures into sub-folders at time of adding the product displays and products.
So I have installed this module
Filefield Paths
I managed the image field in the product display and set the path setting to:
pictures/products-displays/[node:field-taxonomy-terms:1:root] (as per below screenshot)

So it uploads the image, to a folder named as per the product parent category, under products displays folder. Which is exactly what I want. a nicely organized pictures structures.

The problem is not with product display images. It is with product images.
I want to have the same things for products where I  need images of products to be saved under

pictures/products/(parent category of the product display this product belongs to)

I understand that:

The product categories vocab is a reference field for Product Display and not product
A product can belong to more than one product display, so there there is no reference on the product data to the product display it belongs to, only the other way around.

So I thought my only workaround to get the category of the product display to which the product belongs to is to use the page url. (I edit my products from the same page of product display edits..remember I am using inline entity)

So [current-page:url:args:value:1] will give me the product display node id, when I am on the page of product display and its products editing.
What I need is to get the parent category of that product display node id and use it for the path. in other words I need to have a token that will get me the parent category of the product display id on the page
I know the below does not work... but just to give an idea about the logic

 [[current-page:url:args:value:1]:field-taxonomy-terms:1:root]

What you are proposing to do won't really work since you cannot embed tokens within tokens. You're going to need to split the images up based on something else. Here are some options:

Product type [commerce_product:type] (e.g. "shirt" - I haven't checked this one.)
Date [current-date:custom:Ym] (e.g. "201512")

Furthermore, unless you have hundreds of thousands of images, you're likely not going to see much of a performance degradation. If you do have that many images, perhaps you should consider using a CDN or some external system to offload image handling.


Installing SMTP module, not able to enable module On a Drupal site that I've inherited, I'm trying to fix an issue where the contact form isn't sending out emails. To that end, I'm attempting to install, enable, and configure the SMTP module to see if that will fix things.

I've attempted to install the SMTP module via direct link as well as uploading it myself. While the module appears in the site admin list, I'm not able to enable it (just goes to a yellow "on", and then back to disabled).

What are some ways to figure out what the conflict or problem may be?

Most likely, your host provider does not have one or more of the PhP extensions enabled for your site.  Check the status page / php info to see if the following items listed in the readme are there:

  REQUIREMENTS

  Access to an SMTP server
  The following PHP extensions need to be installed: ereg, hash, date & pcre.
  Optional: To connect to an SMTP server using SSL, you need to have the   openssl package installed on your server, and your webserver and
  PHP   installation need to have additional components installed and
  configured.

If the requirements are there, check the watchdog error log (you probably have).

If possible, check the actual server error logs.

If you can't check the error logs, you might try going to the Logging and Error settings in the Devel area and setting the option to display all errors with a stacklog.

NOTE: This should be reset once your debugging is done.


Is there a base module that implements the slide in, slide out behaviour like the Admin module? I am looking for a module that implements slide in and slide out on top functionality, similar to the way some websites slide out a contact form when you click the thingy at the side of the page.
 The Admin and Slidebox modules have that ability, but I am looking for some kind of container object that implements the slide in and out functionality.

PS. the tags are not the most accurate but are the nearest.

Superfish is a great option for drop down menus, and you can customise the effects: http://drupal.org/project/superfish

or Nice Menus: http://drupal.org/project/nice_menus

You can also customise the admin menu to add common tasks, by editing the actual links list.


How do I set up the Workflow module? My site has an administrator role (editor), and I want to allow the anonymous users to submit articles in my site; the node they create must be approved by editor users, before to be published.
I have been told to use the Workflow module; I installed the module, and set it, but I didn't obtain what I wanted.

These are the steps I followed:

I created a workflow which is named "teststory",  and added the "approve" state, which is applied only to the "story" content type.
I edited the workflow, which is then shown as

   from/to     approve
   (creation)  checked the author and authenticated user
   approve     nothing

Under the "access control" approve part, I allowed the authenticated user to view, edit, and delete the posts that are in this state.

It looks like you have only one state (approve). You really want to have at least two. Try adding draft. Configure the workflow so that on creation the node goes to the draft state. This should work:

From / To     draft      approved
(creation)    author         -
draft                    editor
approved        -


Multiple slideshows on a page On the home page of a site I want to list each node as an individual slideshow. Each node shown will be of the same content type. I am using views slideshow and panels if it helps.

Yes it is possible to achieve this, You have to use views along with Scrollable Content

It provides a scrolling functionality for your content. Scrollable Content will give you a nice content slider preview of your site's nodes, and provides some display options.

  The basic use is via blocks page, you'll find a block called
  "Scrollable Content" and if you want more control & you know how to
  use Views, you should use the Views style for Scrollable Content.

or you can check Scrollable Views , I'm using this in my website, but it no longer supported.


Where to declare menu hook I'm working through the second post in this thread, so I can call a custom method from jQuery.
https://stackoverflow.com/questions/4834132/how-to-pass-jquery-variable-to-drupal-ajax

(I already have a html form, so the Forms API doesn't really help me)

The post mentions a menu_hook, but always describes the hook, as belonging to a module. I only plan on adding one method, so I don't really want (or know) how to create a module from scratch.

Is it possible to add the menu hook to my template.php, or another file which already exists?

You should create your own module for your hook_menu. It's not hard or bad in any way. :) It's also near trivial.

in sites/all/modules/custom_module create two files:

custom_module.info with

name = My custom module
core = 7.x

custom_module.module with (copied from linked to question)

<?php
function custom_module_menu() {
  return 'my_custom_callback/%' = array(
    'title' => 'My Custom Callback',
    'description' => 'Listing of blogs.',
    'page callback' => 'my_custom_php_function',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

And you have a new module with a hook menu entry. Replace core = 7.x with core = 6.x if you want this to work for D6 instead of 7. And replace custom_module everywhere if you call the module something else :)


How to send mail with third party domains? I'm using mailsystem and Swift Mailer. Instead of paying for a professional service or self-hosting, I'd like my site email to be sent using my hotmail or another domain I control.

Eg let's say my Drupal domain is mydomain.com. I want the site mail address to be somethingelse@hotmail.com or me@somethingelse.com

Is this possible and does it need special configuration?

All my attempts to send mail using Outlook's STMP server or myother domain's SMTP service have led to refused connections.

It is possible to send email via SMTP using Outlook's SMTP server. Make sure you have set Swiftmailer to send mail via SMTP.

SMTP server: smtp-mail.outlook.com or smtp.office365.com
Port: 587
Encryption: TLS

Use your Hotmail address and password to log in. You'll probably need to enter your Hotmail address under "Configuration" -> "Basic site settings".

Your web hosting provider may block outgoing SMTP ports. Check with their support to make sure.

More information:

https://support.office.com/en-us/article/POP-IMAP-and-SMTP-settings-for-Outlook-com-d088b986-291d-42b8-9564-9c414e2aa040
https://docs.microsoft.com/en-us/exchange/troubleshoot/send-emails/smtp-submission-improvements#new-behavior-when-submitting-messages


How to implement a Dropbox-like functionality for authenticated users to upload files? I want to give my users some sort of upload functionality - kind of like a Dropbox. The Dropbox client module seems to have many bugs and the patches aren't fixing them for me.

So basically I am looking for users to be able to JUST upload files.

I don't want them to be able to view files which have been uploaded by others.

Any suggestions about a suitable solution?

Check out the filedepot module.

  The filedepot module is full featured Document Management module that
  has a google docs like feel. It fulfills the need for an integrated
  file management module supporting role and user based security.
  Documents can be saved outside the Drupal public directory to protect
  documents for safe access and distribution.

It works great as a ftp-like solution which allows users to upload files, except that it has a UI and is accessible the same way as default drupal pages. Lots of configuration available so you can limit the actions of users. You can also integrate organic groups with filedepot and create groups and folders available only to certain groups, if you want to get into private files for users.

or create a webform for authenticated users only and give them a file upload widget. Then you can browse the submissions in a tabular format. This allows users to upload files but not browse them if you set the permissions up properly. They will still be able to see their upload of course.


open_basedir and file uploads I've run across a problem where, when open_basedir is enabled in my php.ini, my file uploads don't work in Drupal. The parent directory is included in the open_basedir list, yet uploads still don't work. I've tested this both on my development server (running Windows Server 2008, IIS7 and PHP 5.3.2) and locally on my pc with XAMPP (running Windows 7 Enterprise, Apache 2.2 and PHP 5.3.5). The results are the same: as soon as open_basedir is disabled, file uploads within Drupal work perfectly.

Here's an example of the error I get:

Warning: move_uploaded_file(): open_basedir restriction in effect.
File(public://field/image/example_1.jpg) is not within the allowed path(s):
(K:\content;L:\content;E:\content;E:\Upload_temp) in file_save_upload()
(line 1528 of E:\content\includes\file.inc).
File upload error. Could not move uploaded file.

This is what my File System settings are:

Public file system path - sites/default/files/pictures

Temporary directory - sites/default/files/pictures/tmp

Directory structure goes like this: E:\content\drupal. As evidenced, Drupal is within the bounds of open_basedir. What am I missing here?

The warning appears because public://field/image is not included in the list of directories the open_basedir allows. Links are resolved, but an external path like public://field/image is not resolved to an internal path; for example, if the code is trying to read http://example.com/img_png/image.png and img_png is listen by the open_basedir directive, the warning will be shown.


Add link field in custom form I want add link field (label + url internal/external) in custom form

This not work:

$form['test_ink'] = array(
  '#type' => 'link',
  '#title' => $this->t('Link title'),
  '#url' => '',
);

The link (Link) render element type is used to render an anchor element on a page, and not used to provide an input element in a form that is constrained for URLs.

As an example you may look at LinkWidget::formElement, which shows how that field widget creates form elements for a Link field. And the way it does this is to use the url (Url) form element, which will provide an input element that validates URLs. Make sure that the #url property is a valid (Url) object.

$form['test_ink'] = [
  '#type' => 'url',
  '#title' => $this->t('Link title'),
  // Example of a Url object from a route. See the documentation
  // for more methods that may help generate a Url object.
  '#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),
];

Edit:

Added @imclean's suggestion to the answer for readability


When does system generate global variable $user? I want to add some data to global variable $user when user login, so when does system generate $user, and which hook I should implement?

Drupal initializes the global $user during bootstrap. Unfortunately, it doesn't invoke any hook, as modules are not yet loaded. (Loading the enabled modules is the last step of Drupal bootstrap.)

The following code is used in the Drupal session handler _drupal_session_read().

  // Handle the case of first time visitors and clients that don't store
  // cookies (eg. web crawlers).
  $insecure_session_name = substr(session_name(), 1);
  if (!isset($_COOKIE[session_name()]) && !isset($_COOKIE[$insecure_session_name])) {
    $user = drupal_anonymous_user();
    return '';
  }

  // Otherwise, if the session is still active, we have a record of the
  // client's session in the database. If it's HTTPS then we are either have
  // a HTTPS session or we are about to log in so we check the sessions table
  // for an anonymous session with the non-HTTPS-only cookie.
  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

To extend the global $user, you can implement hook_boot(), which is invoked when Drupal is still bootstrapping, or hook_init(), which is not invoked for cached pages. hook_user_load() is invoked when user_load() is called, but user_load() is not used for the global $user.

As side note, the global $user is not a complete user object. It contains the data saved in the "users" table, and not (for example) the value of any field (fields implemented from the field API) associated to the user entity.
$user->data can be used to store extra data for the user object. Its content can be altered through hook_user_presave() in the same way done by overlay_user_presave().

function overlay_user_presave(&$edit, $account, $category) {
  if (isset($edit['overlay'])) {
    $edit['data']['overlay'] = $edit['overlay'];
  }
}


How to use the OR operator in Views? How do I create a view that will display all content of type 'Accountancy' and also all content with a taxonomy term 'Accountancy' (of any content type)?

I am trying this with a filter of Type: Accountancy OR Taxonomy: Accountancy but this is only showing the taxonomy nodes. The only filter that would work was the Delta.

Thanks Елин Й & morbiD - You both suggest the same answer, however, this does not work, please see screen shot below. (N.B. all this content is not published and only used these views)

Add a Relationship Content: Taxonomy terms on node under Advanced section:

Select the vocabulary:

Add the filter Taxonomy term: Name.

Enter Value  Accountancy.

Click "And/Or, Rearrange" for the Filter Criteria and make it read like:

  Content: Published Yes AND (Content: Type = Accountancy OR (term) Taxonomy term: Name = Accountancy)


Specifying a custom node id when creating new content I want to prevent merge conflicts caused by POST requests on the API at a later stage. Is it possible to specify a custom node id when creating new content in the Drupal user interface or database? What's the fastest, most efficient way to do this?

In the UI no, and you should never interact with the database directly.

But you can do this with the API easily:

$node = Node::create(['type' => 'article', 'nid' => 5]);
$node->enforceIsNew(TRUE);
$node->save();


How do I make fields available? I am using Drupal 7, the Ubercart and Rules module; I plan to use the Views Rules) module. I want to use the Rules module to automatically publish nodes that contain data from a Ubercart order.

I'm attempting to automate a few processes on my Drupal 7 site after the completion of an order with Ubercart.  Upon completion of an order, I would like to automatically publish a content type that contains data from the order (price, customer/user, seller, product name, entity reference data, etc).  I can create the rule to publish the content type, but I'm struggling to figure out how to get the data from the order into the content type.

My approach so far has been to tag the order upon completion of an order, then fetch the order data. However, when I drill down into data selectors, the values I need are not available.  Furthermore, I'm not sure I would know how to get it loaded into the content type upon publish.

I've come across Views Rules module which, to my understanding, will allow me to define the values to fetch.  I've created views that I can load into Rules, but it appears that the View will return all results of the view instead of the result I need upon completion of the order (maybe I'm wrong about this?)

I just need a nod in the right direction on how to accomplish this.  I'm just not sure if my approach is right. I have the basics of Rules, and have only constructed very simple rules.  I imagine what I want to accomplish will require a more complex construct of Rules. Any suggestions are greatly appreciated, particularly on how to use Views to accomplish what I need.

I don't understand most of this.. "publishing a content type?" You sure you don't mean "creating a node"?

Anyways, in conditions for the rule, choose "entity has field" for each field you need. This will allow you to use them in actions.


Is there a way and/or reason to unload a node after node_load? I have a custom module that loads one specific node to get its field value, and then uses that field to make a bunch of calculations. I've seen several comments  like this one that node_load is a resource hog...

My question is if there is a significant benefit to unsetting the node object once I've retrieved my field value, and if yes what is the best way to unset it? I've googled for some time but only can find references to deleting nodes, not unsetting the object. Thanks!

It's advised to use node_load() rather than building your own queries.

If you worry about memory impact, you can unload it by unsetting it:

unset($node);

It would destroy the specified variable/object, however you don't have to do it as PHP should handle garbage collection internally.

Secondly the node would be only loaded in your local scope, so once PHP exits  your function, it should be automatically flushed from the memory at some point.

If you're worry about memory impact, you may:

reduce number of modules which hook into the node objects,
run PHP profiler (such as XDebug) to check the memory is used the most,
enable Devel and its performance checking, it'll show you how much memory is used per individual page,
implement memory caching (instead of using database layer), such as redis or memcached

See: How do you improve Drupal performance?


How to create a rule to email all users who bookmarked the author of new content? I have the Rules and Flag modules installed. I want other users to be notified of flagged user new content.

I made 2 rules:

To add the author of content to bookmarks of user:

To send an e-mail notification when bookmarked (flagged) user created new article:

But it sends an e-mail only to the user who created the article.

What am I doing wrong?

As i can see in your Actions -  Send mail - To:[site:current-user-mail]. You need to create action Send mail and chose 'Send mail to all users of role` - and chose roles for which you want to send mail.


Simple newsletter send only This is a test version of the newsletter I am using Newsletter module to send newsletter to all my registered users. I have created two lists

Blog

Project (Have created templates for them as well).

My questions are;
The test mail just sends the [node: title] like tokens. What should I add to mail the contents of the node?
Thanks

First, the newsletter module isn't yet stable, so I am giving you a solution for the Simplenews module.

If you want to send Views in a newsletter, you want to use the Viewsfield module. It allows you to create a Views field for your Simplenews content type. Then create a single Simplenews node and add your required View (there's a dropdown available with all active Views).

Since the content of the Views might change and you want to send the newsletter on a regular basis, you also need the Simplenews Scheduler module. It allows you to send the newsletter for example once a week with the updated content of your selected view.

I did something like that some time ago and also added a documentation on drupal.org.


How to install new drupal packages on local apache server I have a drupal site set up on a local mysql and a local apache server. I am trying to install a new module the problem is it brings me to the login for server ftp. I'm not sure what credentials it wants or how to do it exactly is there some way to enable apache ftp or what am I supppsed to be doing.

Thank you for any help.

Looks like this is a permission issue. You might want to make sites directory owned by the apache user and the themes or modules folder is writable as well.

$ chown -R www-data sites # Change owner sites directory

If that doesn't work, you might try setting modules and theme dir writable.

$ chmod -R 777 sites/all

Ref: https://www.drupal.org/forum/support/post-installation/2011-01-22/module-installation-requires-ftp-access


Error during entup when removing a field added in entity_base_field_info I am removing a field that was added using hook_base_field_info:

/**
 * Implements hook_entity_base_field_info().
 */
function MYMODULE_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();

  if ($entity_type->id() === 'node') {
    $field_definitions['some_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('some  field'))
      ->setDescription(t('description'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setSetting('datetime_type', 'date')
      ->setDisplayOptions('view', [
        'label' => 'inline',
        'type' => 'datetime_default',
        'weight' => 1,
        'settings' => [
          'format_type' => 'html_date',
          'timezone_override' => '',
        ],
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'datetime_default',
        'weight' => 10,
      ))
      ->setDisplayConfigurable('form', TRUE);

    return $fields;
  }
}

I removed the code and ran drush entup I get the following error repeatedly:

drush entup -y
The following updates are pending:

node entity type :
Some Field field needs to be uninstalled.

// Do you wish to run all pending updates?: yes.

 [error]  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '22906-42845-1-0-de' for key 'PRIMARY': INSERT INTO {field_deleted_revision_01c8f04bcd} (bundle, entity_id, revision_id, langcode, some_field_value, deleted, delta) SELECT base_table.type AS bundle, entity_table.nid AS entity_id, entity_table.vid AS revision_id, entity_table.langcode AS langcode, entity_table.compliance_approval_date AS some_field_value, :deleted AS deleted, :delta AS delta
FROM
{node_field_revision} entity_table
INNER JOIN {node_field_data} base_table ON entity_table.nid = base_table.nid
WHERE entity_table.some_field IS NOT NULL FOR UPDATE; Array
(
    [:deleted] => 1
    [:delta] => 0
)

Any idea why this is caused and how one might go about fixing it?

drush entup is the wrong tool (I hope you have a database backup from before you've executed this command). After uninstalling the module containing the node base field, wait until cron has gradually purged the existing field data, see the change record Base fields with existing data can now be uninstalled.


Translate menu item made by view Question is simple, in the views module you can add a normal menu item. But when in the menu itself it can't be translated. Is there anyway to do this, or should I just add the menu item myself instead of letting the view do that?

After defining your menu item via views, you have to go back to the views list (/admin/structure/views). There is a "Translate" option under "Edit".

There, you can "Add" a translation, then choose your page display options and translate the menu item (applies for Drupal 8 only).

If the menu item is not showing up, clear the caches (e.g. cache rebuild using drush cr).


How can I see all the places an asset or entity is referenced? In Drupal 8, I have a requirement from a client that they be able to find a reference of a given asset (file, node, entity, etc) throughout a Drupal site. The ultimate goal is to know that if they want to delete this asset, it's not going to create 404 errors throughout the places on the site where this is referenced in other content.

I'm thinking about a Views page where the name or ID or some type of identifier would be a contextual filter and then would show a list of all nodes or blocks where that relationship exists.

Any thoughts on how to approach solving an issue like this?

Have you looked at /admin/structure/views/view/files? Is that what you need?

Otherwise, you might try your creating your own view of files at /admin/structure/views/add.

No matter the view, you will need to check the file before deletion as there will be no functionality to warn admins.

Then for content, I think it would just be a view of content focused on adding the Content Reference field (or whatever you content reference field_name is), which can show where references are coming from.

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_content_reference
  module:
    - node
    - user
id: content_references
label: 'Content References'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 50
          offset: 0
          id: 0
          total_pages: null
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: '‹ Previous'
            next: 'Next ›'
            first: '« First'
            last: 'Last »'
          quantity: 9
      style:
        type: table
      row:
        type: fields
      fields:
        field_content_reference:
          id: field_content_reference
          table: node__field_content_reference
          field: field_content_reference
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Referenced Content'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: entity_reference_label
          settings:
            link: true
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Referenced By'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        field_content_reference_target_id:
          id: field_content_reference_target_id
          table: node__field_content_reference
          field: field_content_reference_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: 'not empty'
          value:
            min: ''
            max: ''
            value: ''
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            placeholder: ''
            min_placeholder: ''
            max_placeholder: ''
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: numeric
      sorts: {  }
      title: 'Content References'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_content_reference'
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_content_reference'

I am not sure about an all in one solution...


Block: DRUPAL_NO_CACHE not working I have a block that displays an item fetched from the database at random. The block has DRUPAL_NO_CACHE as cache parameter. However, when visiting the page as anonymous user with the cache on, the item never changes.

Some code:

function foo_block_info() {
  $blocks = array();

  $blocks['foo'] = array(
    'info' => t('Foo'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function foo_block_view($delta = '') {
  if ($delta == 'foo') {
    $block = array(
      'content' => theme(
        'foo_block',
          array(
            'item' => entity_get_controller('foo')->get_random_foo(),
          )
        ),
    );
    return $block;
  }
}

function foo_theme($existing, $type, $theme, $path) {
  return array(
    'foo_block' => array(
      'template' => 'foo-block',
      'arguments' => array(
        'item' => NULL,
      ),
    ),
  );
}

I suspect it's a Drupal Core bug, I've checked the forums but can't really find a solution for Drupal 7.

I know I could insert the item in the DOM with AJAX, but that's a last resort.

If you are caching the whole page (which is off by default in D7) then BLOCK_NO_CACHE will not make a difference on a block. Because while the block is not cached, the page is.

I think what you may want is the esi api module it allows you to use ajax to render the blocks.


how to use data of a text list field to draw a canvas image? I'm working on a website, where some information has to be drawn like a graph on a canvas. I have the javascript to draw the picture, but for input I need the values of a field (List/Text) initialized by check boxes.

What I need is a way to get the values from the field of the node and draw a canvas image with the javascript code I have but I cannot figure out how..

Any ideas?

the answer is jQuery. The comment above written by burnsjeremy

'I guess you need to get the value in the browser on the client side so you would need to use jQuery (you can pass the value from the backend '

thanks, burnsjeremy


How do I create an Events page listing all Event nodes? I have a Theatre website that I'm creating in Drupal 8, and I need to create an Event content type. This content type will be displayed on an Events page listing all Events in ascending order from closest date to latest. (I'm pretty sure I can get Views to do this.)

This is how each node should look like when listed on the Events page.

I know I need to create fields for:

Event Poster
Event Presenter
Name of the Event (This would be the Title Field)
Day(s) of the event
Time(s) of the event
Event price(s)
Link to external Ticketmaster-type website to purchase tickets

The problem I have is that not all events are only set up to be on one day or at one time; some events may be listed like the following (Where there are multiple time listings for the day) or some might be where the event is being held for multiple days and may have different times of when it is being held.

What field type should I use for the datetime field? Is there a special module I should get for this that allows multiple dates to be listed? Do I even need to worry about a special Time field or do I just keep it as a plain text field for the user to just type in the time(s)?

TL;DR: How do I create a date field that allows to list multiple days (maybe times) and then sorting the content type by the days of the event in ascending order?

You can use a Date field with an End Date (I don't have at this moment Drupal 8 installed to show you how)

With Views you can configurate your field to show the Start Date and the End Date. For use the format of Date in one place and Time in another place, you need to create a new Date format.

Maybe this question can be interesting for you: When should I use collect an end date for a field, instead of using 2 separated date fields?. Or have a look at How to Add a Custom Date Format in Drupal 8.


Just want to submit field values Created a custom form, which submit values to a table.
Fields on the form created on the go.
For example if we have 5 users, we will have 5 fields, if 6 then six fields

Say if it has 5 fields

Field 01
Field 02
Field 03
Field 04
Field 05

Just want to submit all values of all fields being created on the go.

when I dsm

dsm[$form_state[values]];

It shows me array with form fields and form info like

Field 01
Field 02
Field 03
Field 04
Field 05
form_build_id
form_token
...
..

So I can't just run loop to submit all fields because 'form_build_id' etc is also there.

How can I do this dynamically?

$user_ids = array(1, 2, 3, 4, 5, 6); // This will be dynamic based on your users

foreach ($user_ids as $uid) {
  // Your form element goes here
  $form['field_user_value_' . $uid ] = array(
    // form elements
  );
}

In your submit function you have above values

$values = $form_submit['values'];

foreach ($values as $key => $values) {
  if ($substr($key, 0, 17) == "field_user_value_") {
    // Push values to database
  }
}


How to find and delete nodes with duplicate titles? I used Feeds, and for some reason it imported several nodes multiple times; now I have many duplicates.

How could I easily find and delete such nodes?

This Drupal 6 script should do the job for you.


Change form submit #access as a result of ajax callback I have a form that requests some information first, then pre-populates other fields before a final submit.  I'm trying to change the #access value for the buttons on the form.  Both of the code snippets below come from the same form builder function.

Considering:

$form['actions'] = [
  'id_lookup' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Lookup ID',
    '#ajax' => [
      'callback' => 'my_module_populate_id_info',
      'wrapper' => 'id_info',
      'method' => 'replace',
      'effect' => 'fade',
    ],
  ],
  'submit' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Register for Event',
    '#access' => FALSE,
  ],
  '#weight' => 100
];

The above code provides two buttons, one which triggers the ajax callback (see below) and the other which will submit the final form.

The below code adds additional fields (they're all disabled) with information pre-populated.  Everything works as expected, I just want to change #access on id_lookup to false and on submit to true, it's not working.  I originally tried to just change the value, but I couldn't get that to work either.

if (!empty($form_state['values']['id'])) {
  $user_info = my_module_signup_get_id_info($form_state['values']['id']);
  $ldap_user = FALSE;
  $existing_user = FALSE;
  if (isset($user_info['ldap_user'])) {
    $ldap_user = TRUE;
    $first_name = $user_info['ldap_user']['givenname'][0];
    $last_name = $user_info['ldap_user']['sn'][0];
    $job_title = $user_info['ldap_user']['title'][0];
    $organization = $user_info['ldap_user']['department'][0];
    $email = $user_info['ldap_user']['mail'][0];

    $form['id_info']['first_name'] = [
      '#type' => 'textfield',
      '#title' => 'First Name',
      '#required' => TRUE,
      '#prefix' => '

',
      '#suffix' => '

',
      '#disabled' => TRUE,
      '#default_value' => $user_info['ldap_user']['givenname'][0],
  ];
  // ... some other fields
  // Try to change the #access on the actions
  $form['actions']['id_lookup']['#access'] = FALSE;
  $form['actions']['submit']['#access'] = TRUE;
} else {
  $form['id_info']['no_user'] = [
    '#type' => 'markup',
    '#markup' => '
No user was found for that ID
',
  ];
}

}

Everything works as expected except the access on those buttons - what am I doing wrong?

You really shouldn't alter the form in your ajax callback.  What you want to do is set a variable in the form_state in the ajax callback, and your form code should look for that variable to decide how to set #access

So in your ajax callback, lets say whatever conditions are met, and you want to disable access when it reloads...

So set a variable like, $form_state['access_to_field_revoked'] = TRUE

Then your form code:

$form['actions'] = [
  'id_lookup' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Lookup ID',
    '#access' => empty($form_state['access_to_field_revoked']) ? TRUE : FALSE,
    '#ajax' => [
      'callback' => 'my_module_populate_id_info',
      'wrapper' => 'id_info',
      'method' => 'replace',
      'effect' => 'fade',
    ],
  ],
  'submit' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Register for Event',
    '#access' => !empty($form_state['access_to_field_revoked']) ? TRUE : FALSE,
  ],
  '#weight' => 100
];

You will probably need another variable like $form_state['generate_additional_fields'] = TRUE;
and put your FAPI for those fields in the form callback, and not the ajax callback...
so in your form callback:

if(!empty($form_state['generate_additional_fields']) {
// add your additional form fields now
}

Almost never a reason to alter the $form variable in the ajax callback. It is always best to set a variable in the form_state and then look for that variable in the form callback to actually set the FAPI up.

UPDATE:
Misread the post, so your code was in the form handler, not the ajax handler, and that will work.

One way that the #access property would not get updated is if the 'actions' buttons are outside of the wrapper div that ajax replaces. If they are, they would be showing via the '#access' value from initial form load.  One solution would be to make sure that the wrapper that the ajax callback refreshes includes the action buttons, so that they are re-rendered.

In the FAPI inside your conditional, there is a suffix, with an extra /div . This maybe the closing div for your wrapper, and if that was placed after the form actions, perhaps they would get refreshed by the ajax callback, and it would work


Wierd admin_path behaviour, does it should be like this? I have even two questions - both are connected to hook_admin_path().

Does menu path 'user/*/edit' and 'user/*/account/edit' are the same, from admin_path perspective and was D7 designed with such functionality? I want menu item 'user/*/account/edit' to be shown on default theme.

When I try to show a menu item with path:

'user/*/account/edit'  - showed on admin theme
'user/*/account/edit1' - showed on default theme

result of path_get_admin_paths():
Array ([admin] =>
admin
admin/*
user/*/cancel
user/*/edit
user/*/edit/*
...
)

checked with:

path_is_admin('user/%user/account/edit'); // TRUE
drupal_match_path('user/%user/account/edit', 'user/*/edit'); // TRUE

2 . I tryed to change it with

function MY_MODULE_admin_paths_alter() {
  $paths = array(
    'user/*/edit' => FALSE,
    'user/*/edit/*' => FALSE,
  );
}

But result of path_get_admin_paths() is the same? No other functions call hook_admin_paths_alter(). As I understand, this function shall be the last and should change admin_path.

Any ideas about that?

Thank you Clive,
I mistakenly used pattern from hook_admin_paths() and not hook_admin_paths_alter() function.

The correct way was:

function MY_MODULE_admin_paths_alter(&$paths) {
  $paths['user/*/edit'] = FALSE;
  $paths['user/*/edit/*'] = FALSE;
}


How to setup reCaptcha to appear on the registration form? reCaptcha is ported to Drupal 8. I've set up captcha and recaptcha. I've read Readme.txt from recaptcha, I've registered my site and got the API key and paste it, also I've looked at Readme.md from captcha module.

But it does not appear in the user registration form.

All I can see is this

So please, what to do? Where should I set up captcha appears on regform?

In the CAPTCHA Points tab, you need to click on the enable button.


How to remove Page cached by boost message in view source I installed Boost and the page cached by boost will have a line of message at the bottom of view-source.

<!-- Page cached by Boost @ 2014-11-08 14:04:46, expires @ 2014-11-09 14:04:46, lifetime 1 day -->

How to remove the above line?

This is not possible in the 7.x-1.x version of the module (unless you patch the code). You should file a feature request in the Boost issue queue.

If you want to temporarily patch the code, open the file boost.module, around line 1145:

  $types['text/html'] = array(
    'title'           => t('HTML'),
    'description'     => t('HTML output, usually a webpage'),
    'extension'       => 'html',
    'enabled'         => TRUE,
    'gzip'            => TRUE,
    'lifetime_max'    => 3600,
    'lifetime_min'    => 0,
    'comment_start'  => NULL, // <--- set to null
    'comment_end'    => NULL, // <--- this too
    'variants'        => array(),
  );

If you would like to contribute a patch, which would be greatly appreciated, the right way to do this would be to modify the boost_exit() function, around line 315:

  // Add note to bottom of content if possible.
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end'] && $_boost['matched_header_info']['comment_footer_enabled']) {
    $expire = $_boost['matched_header_info']['lifetime_max'];
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
    $data .= $note;
  }

You would also have to set the default (TRUE) in boost_boost_storage_types(), and to the $keys in boost_get_storage_types() so that it does the variable_get(). Bonus points for also exposing it to the admin interface.


How to write SoapClient request which has basic auth in it? Actually I need to implement SoapClient in Drupal 8. Following XML is Request:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://www.example.com/common/ServiceRequestHeader_v1_0/types" xmlns:typ1="http://www.example.com/customer/CustomerViewRequest_v1_0/types">
   <soapenv:Header>
      <typ:serviceRequestHeader>
         <applicationCredential>
            <ID>USERNAME</ID>
            <credential>*****</credential>
         </applicationCredential>
         <transactionModel>
            <synchronousRequest>true</synchronousRequest>
         </transactionModel>
         <userCredential>
            <ID>RITESH</ID>
         </userCredential>
      </typ:serviceRequestHeader>
   </soapenv:Header>
   <soapenv:Body>
      <typ1:serviceRequest>
         <requestPreamble>
            <companyCode>IN</companyCode>
            <customerNumber>12345678</customerNumber>
         </requestPreamble>
      </typ1:serviceRequest>
   </soapenv:Body>
</soapenv:Envelope>

I have tried following code for the same but it is failing and I am not able to make any progress on this:

    $client = new SoapClient('https://example.com:9043/CustomerView_v1_0_vs0',
    array(
        // Stuff for development.
        'trace' => 1,
        'exceptions' => true,
        'cache_wsdl' => WSDL_CACHE_NONE,
        'features' => SOAP_SINGLE_ELEMENT_ARRAYS,

        // Auth credentials for the SOAP request.
        'ID' => 'USERNAME',
        'credential' => 'Password',

    )
);
    dump($client); die;

Its giving below error:

SOAP-ERROR: Parsing WSDL: Couldn&#039;t load

Can anyone suggest some way on this ?

I believe the answer is nearly there for you, but ID and credential are the wrong keys in the options array.

       'login' => 'USERNAME',
       'password' => 'Password',

I suggest that you put the username and password into conf in your settings.php file so they are not in your codebase nor your site configuration data. See How secure are variable_get and variable_set? for details on how to securely have credentials in Drupal's config system.


How do I get Drupal to recognize my 404 page override? I am using a custom 404 page. I also have a theme installed.

This is what I did:

I created a node 95761 which contains my 404 error page.
I set node/95761 to be my 404 error page I've created a template in my theme node--error.tpl.php
I cleared my cache after uploading node--error.tpl.php to the server.
I've verified that node--error.tpl.php exists on the server and has my custom code in my theme's templates folder.
I go to [mydomain]/pathThatDoesNotExist

Actual result: The contents of node/95761

Expected result: The modified version that is contained in node--error.tpl.php

I also tried node--95761.tpl.php and that doesn't override node/95761 either.

Any ideas why Drupal 7 is not picking up the override and how to fix it?

While we're at it, should the name of the template actually be node--error-404.tpl.php so that it doesn't override 403 or other non-404 errors?

Have you check this link http://example.com/admin/config/system/site-information.
Visit the above link in your site and set the 404 error page for your site.


Taxonomy on each field value What is the best way to add taxonomy terms to each field value (uploaded with plupload or multiupload at once) of a imagefield (should look like http://www.binaerschmiede.at/test/imagefield-tags.jpg)?

Of course I want to access this terms in views afterwards for creating media overviews.

Is there already a extension/module I've missed so far while searching because I suppose I'm not the first one with that kind of request, am I?

Example:

I create a content where I upload 3 pictures to a multiple plupload image field. Entering title, alt text and the tag the first 2 images with "Nature, Animals", the 3rd on with "Nature, Landscape".
I create another content with 2 images tagged as with "Zoo, Animals".
In a View I want all to get all images tagged with "Animals", on another view all images tagged with "Nature", ... and so on.

Thanks.

Create a multi-value Field Group, with one taxonomy term reference (tag), and one image. Field group values can be used in views via Field group views module.

Alternatively you can do the same using Field collection module - younger, without 6.x roots, written to utilize entity api (and it means native views integration).

For bulk uploading, there is Field Collection Bulkupload, it seems to work, if with issues (as to be expected for alpha module). If you need bulk upload capabilities and equivalent of collections, joining efforts with it's team should be your best bet.


If Drupal Commerce Cart is not Empty, add a class to body I'd like to add a class to body if the current user's cart is not empty.

I'd like to take the preprocess approach and not using rules.

so far using commerce_cart_order_load function I came up with this in template.php:

function THEME_preprocess_html(&$vars) {
    global $user;
    $order = commerce_cart_order_load($user->uid);

    if ($order != 0) {
        $vars['classes_array'][] = 'cart-loaded';
    }
}

but unfortunately it throws an unknown error.

Using this resource and thanks to @rémy I come up with this solution:

function THEME_preprocess_html(&$vars) {
    global $user;
    $cart = commerce_cart_order_load($user->uid);
    foreach (entity_metadata_wrapper('commerce_order', $cart)->commerce_line_items as $delta => $line_item_wrapper) {
      if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
        $vars['classes_array'][] = 'cart-loaded';
      }
    }
}

  So after a while of testing I ended up with an error with anonymous
  users, so I digged a little bit deeper and come up with something new
  and no errors this time:

function THEMENAME_preprocess_html(&$vars) {
    global $user;
    $quantity = 0;
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
        $wrapper = entity_metadata_wrapper('commerce_order', $order);
        $line_items = $wrapper->commerce_line_items;
        $quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
        if ($quantity) {
            $vars['classes_array'][] = 'cart-loaded';
        }
    }
}


Proper way to define weight / country wise shipping rates I need to configure country wise shipping rates by weight. So each country has different shipping rates for different weights. So I have divided countries in different zones. The countries in each zone have same shipping rates. So what I have done is created several flat rates services like following.

Zone 1 - 0.5KG, Zone 1 - 1.0KG, Zone 1 - 1.5KG, Zone 1 - 1.5KG, Zone 1 - 2.0KG and so on ...
Similarly Set for each Zone
Zone 2 - 0.5KG, Zone 2 - 1.0KG, Zone 2 - 1.5KG, Zone 2 - 1.5KG, Zone 2 - 2.0KG

Defined respective rates for each flat rate service. And configured like following.

Order total weight comparison
Parameter: Order: [commerce_order], Operator: <=, Value: 0.5

AND

Order address component comparison
Parameter: Order: [commerce_order], Address: Address, Address component: Country, Operator: is one of, Value: AL ...

This works for me well, but I have to configure 91 flat rate service and define the conditions manually again and again.

Though at the end I am getting my desired result, I feel there must be a better way to achieve this task, but I am not aware of that.

Please guide me to do it properly.

Have you looked at these two modules?

Commerce Shipping Postal Code Weight
Commerce Shipping Weight Tariff